code
stringlengths
1
1.72M
language
stringclasses
1 value
import logging # Change default log level to debug in dev_appserver to match production logging.getLogger().setLevel(logging.DEBUG) # but leave the default for App Engine APIs logging.getLogger('google.appengine').setLevel(logging.INFO)
Python
#!/usr/bin/env python2.7 import json import logging import os import pprint as pp import sys import unittest import urllib2 try: from webtest import TestApp except: print """Please install webtest from http://webtest.pythonpaste.org/""" sys.exit(1) # Attempt to locate the App Engine SDK based on the system PATH for d in sorted(os.environ['PATH'].split(os.path.pathsep)): path = os.path.join(d, 'dev_appserver.py') if not os.path.isfile(path): continue print 'Found the App Engine SDK directory: %s' % d sys.path.insert(0, d) # The App Engine SDK root is now expected to be in sys.path (possibly provided via PYTHONPATH) try: import dev_appserver except ImportError: error_msg = ('The path to the App Engine Python SDK must be in the ' 'PYTHONPATH environment variable to run unittests.') # The app engine SDK isn't in sys.path. If we're on Windows, we can try to # guess where it is. import platform if platform.system() == 'Windows': sys.path = sys.path + ['C:\\Program Files\\Google\\google_appengine'] try: import dev_appserver # pylint: disable-msg=C6204 except ImportError: print error_msg raise else: print error_msg raise # add App Engine libraries sys.path += dev_appserver.EXTRA_PATHS from google.appengine.ext import testbed from google.appengine.api import backends def make_state(serverid, extras=None): """Create test game server state.""" # something pseudo predictable / stable uptime = hash(serverid) / 1e16 result = { 'serverid': serverid, 'uptime': uptime } if extras: result.update(extras) return result def make_game(serverid, name, extras=None): """Create test game instance.""" result = { 'serverid': serverid, 'name': name, 'game_state': {'players': {}, 'min_players': 2, 'max_players': 4}, } if extras: result.update(extras) return result class MatchMakerTest(unittest.TestCase): def setUp(self): # see testbed docs https://developers.google.com/appengine/docs/python/tools/localunittesting self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_memcache_stub() self.testbed.init_datastore_v3_stub() self.testbed.init_urlfetch_stub() # import matcher now that testbed has been activated from client import matcher # instatiate a new matcher self.mm = matcher.MatchMaker() # no maximum length for diffs self.maxDiff = None def tearDown(self): self.testbed.deactivate() def assertGameServers(self, expected_game_servers): """Assert the global game servers state.""" if expected_game_servers != self.mm._game_servers: self.fail('Unexpected game servers state:\n----------\nEXPECTED:\n%s\n\nACTUAL:\n%s\n----------' % (expected_game_servers, self.mm._game_servers)) #self.assertEquals(expected_game_servers, self.mm._game_servers) def assertPlayerGameState(self, expected_game, player_game): """Assert a specifc game state.""" self.assertIn('game', player_game) self.assertIn('player_game_key', player_game) self.assertEquals(expected_game, player_game['game']) def assertGameServerWait(self, players_needed_for_next_game, pg): """Assert that the player is being asked to wait.""" self.assertEquals({'result': 'wait', 'players_needed_for_next_game': players_needed_for_next_game}, pg) ####################################################################### # tests to verify server and game updates ####################################################################### def test_initialized_state(self): self.assertGameServers({}) def test_update_server_info(self): self.assertGameServers({}) state_foo = make_state('foo') expected = { 'foo': { 'server_info': state_foo, 'games': {}, } } self.mm.update_server_info(state_foo) self.assertGameServers(expected) def test_update_server_info_twice(self): state_foo = make_state('foo') state_bar = make_state('bar') expected = { 'foo': { 'server_info': state_foo, 'games': {}, }, 'bar': { 'server_info': state_bar, 'games': {}, }, } self.assertGameServers({}) self.mm.update_server_info(state_foo) self.mm.update_server_info(state_bar) self.assertGameServers(expected) def test_update_server_info_thrice(self): state_foo1 = make_state('foo', {'update': 17} ) state_foo2 = make_state('foo', {'update': 42} ) state_bar = make_state('bar') expected = { 'foo': { 'server_info': state_foo2, 'games': {}, }, 'bar': { 'server_info': state_bar, 'games': {}, }, } self.assertGameServers({}) self.mm.update_server_info(state_foo1) self.mm.update_server_info(state_bar) self.mm.update_server_info(state_foo2) self.assertGameServers(expected) def test_del_server_info(self): state_foo = make_state('foo') state_bar = make_state('bar') expected = { 'bar': { 'server_info': state_bar, 'games': {}, }, } self.assertGameServers({}) self.mm.update_server_info(state_foo) self.mm.update_server_info(state_bar) self.mm.del_game_server('foo') self.assertGameServers(expected) def test_update_game(self): state_foo = make_state('foo') game_abcd = make_game('foo', 'abcd') expected = { 'foo': { 'server_info': state_foo, 'games': { 'abcd' : game_abcd, } } } self.assertGameServers({}) self.mm.update_server_info(state_foo) self.mm.update_game(game_abcd) self.assertGameServers(expected) ####################################################################### # tests to verify match making ####################################################################### def test_do_not_find_full_game(self): state_foo = make_state('foo') game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 0, 'max_players': 0}}) self.mm.update_server_info(state_foo) # we have a game, but no players are needed self.mm.update_game(game_abcd) # do not find full game pg = self.mm.find_player_game('fred') self.assertGameServerWait(-1, pg) def test_find_single_player_game(self): state_foo = make_state('foo') game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 1, 'max_players': 1}}) self.mm.update_server_info(state_foo) # no available game yet pg = self.mm.find_player_game('fred') self.assertGameServerWait(-1, pg) # game_abcd becomes available self.mm.update_game(game_abcd) # we should find it pg = self.mm.find_player_game('fred') self.assertPlayerGameState(game_abcd, pg) # we should find it again pg = self.mm.lookup_player_game('fred') self.assertPlayerGameState(game_abcd, pg) def test_wait_for_enough_players(self): state_foo = make_state('foo') # only 3 game slots remaining game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 1, 'max_players': 1}}) game_efgh = make_game('foo', 'efgh', {'game_state': {'players': {}, 'min_players': 2, 'max_players': 2}}) self.mm.update_server_info(state_foo) self.mm.update_game(game_abcd) self.mm.update_game(game_efgh) # player1 enters game_abcd pg = self.mm.find_player_game('player1') self.assertPlayerGameState(game_abcd, pg) # player2 waits for a second player pg = self.mm.find_player_game('player2') self.assertGameServerWait(2, pg) # player3 enters game_efgh pg = self.mm.find_player_game('player3') self.assertPlayerGameState(game_efgh, pg) # player4 does not get in pg = self.mm.find_player_game('player4') self.assertGameServerWait(-1, pg) # player2 finally enter game_efgh pg = self.mm.lookup_player_game('player2') self.assertPlayerGameState(game_efgh, pg) def test_honor_max_players(self): state_foo = make_state('foo') # only 3 game slots remaining game_abcd = make_game('foo', 'abcd', {'game_state': {'players': {}, 'min_players': 2, 'max_players': 4}}) self.mm.update_server_info(state_foo) # player1 is told that a new game needs to be spun up pg = self.mm.find_player_game('player1') self.assertGameServerWait(-1, pg) # a new game is made available self.mm.update_game(game_abcd) # player1 is told 2 players are required pg = self.mm.find_player_game('player1') self.assertGameServerWait(2, pg) # player2 allows the game to start pg = self.mm.find_player_game('player2') self.assertPlayerGameState(game_abcd, pg) # player3 drops in pg = self.mm.find_player_game('player3') self.assertPlayerGameState(game_abcd, pg) # player4 drops in pg = self.mm.find_player_game('player4') self.assertPlayerGameState(game_abcd, pg) # player5 does not get in pg = self.mm.find_player_game('player5') self.assertGameServerWait(-1, pg) if __name__ == '__main__': unittest.main()
Python
import os, zipfile def zip(target, source, env): f = zipfile.ZipFile(str(target[0]), 'w', zipfile.ZIP_DEFLATED) chdir = None try: chdir = env['ZIPCHDIR'] + os.sep except: pass for s in source: s = str(s) if chdir and s.find(chdir) == 0: arcname = s[len(chdir):] else: arcname = s f.write(s, arcname) f.close() zipbld = Builder(action = zip) Export('zipbld') objs = [] for subdir in ['components', 'chrome']: r = SConscript(['%s/SConscript' % subdir]) objs.extend(r) env = Environment() r = env.Install('dist', 'chrome.manifest') objs.append(r) r = env.Install('dist', 'install.rdf') objs.append(r) r = env.Install('dist', 'License.txt') objs.append(r) r = env.Install('dist/defaults/preferences', 'defaults/preferences/prefs.js') objs.append(r) zipenv = Environment(BUILDERS = {'Zip' : zipbld}, ZIPCHDIR = 'dist') zipenv.Zip('firetray.xpi', objs) Alias('xpi', 'firetray.xpi')
Python
import sys, os, string, re platform = sys.platform try: FLAGS = os.environ['CXXFLAGS']; except: FLAGS = '-O2'; linking_options=' --libs '; try: DYNAMIC_LINKING = os.environ['DYNAMIC_LINKING']; except: linking_options=' --static ' print "linking: " + linking_options FLAGS += ' -include xpcom-config.h -include mozilla-config.h' FLAGS += ' -fno-rtti -fno-exceptions -fshort-wchar' FLAGS += ' -Wall -Wconversion -Wpointer-arith -Wcast-align -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor -Wno-long-long' FLAGS += ' -pedantic -pthread -pipe' try: lib_arch = os.environ['LIB_ARCH']; except: lib_arch = ''; try: gecko_bin = os.environ['GECKO_SDK_BIN']; if gecko_bin[-1] != os.sep: gecko_bin += os.sep gecko_include = os.environ['GECKO_SDK_INCLUDE']; if gecko_include[-1] != os.sep: gecko_include += os.sep gecko_idl = os.environ['GECKO_SDK_IDL']; if gecko_idl[-1] != os.sep: gecko_idl += os.sep gecko_lib = os.environ['GECKO_SDK_LIB']; if gecko_lib[-1] != os.sep: gecko_lib += os.sep except: try: geckosdk = os.environ['GECKO_SDK'] print "Using GECKO_SDK=" + geckosdk if geckosdk[-1] != os.sep: geckosdk += os.sep gecko_bin = geckosdk + 'bin' gecko_include = geckosdk + 'include' gecko_idl = geckosdk + 'idl' gecko_lib = geckosdk + 'lib' except: print "Please set environment variable GECKO_SDK first (or in alternative the variables GECKO_SDK_BIN, GECKO_SDK_INCLUDE, GECKO_SDK_IDL, GECKO_SDK_LIB)." sys.exit(1) # Hack to detect Mozilla version version_re = re.compile('#define MOZILLA_VERSION "(.*?)"') xpcom_libs = ['xpcomglue_s'] with open(gecko_include + os.sep + 'mozilla-config.h', 'r') as f: for line in f: version_match = version_re.match(line) if version_match: version = string.split(version_match.group(1), '.') if int(version[0]) >= 2: # OK, we're building with Mozilla 2.0 FLAGS += ' -DGECKO_2' if 'GECKO_19_COMPAT' in os.environ: FLAGS += ' -DMOZ_NO_MOZALLOC' xpcom_libs = ['xpcomglue_s_nomozalloc'] else: xpcom_libs.append('mozalloc') break # Create two builders to create xpt and header files from idl. bxpt = Builder(action = 'xpidl -w -m typelib -Icomponents -I' + gecko_idl + ' -e $TARGET $SOURCE', suffix = '.xpt', src_suffix = '.idl') bhdr = Builder(action = 'xpidl -w -m header -Icomponents -I' + gecko_idl + ' -e $TARGET $SOURCE', suffix = '.h', src_suffix = '.idl') # Create environment object for build env = Environment( CPPPATH = [gecko_include], LIBPATH = [gecko_lib], LIBS = xpcom_libs, ENV = os.environ) env.AppendENVPath('PATH', gecko_bin) env.Append(BUILDERS = {'MozXPT' : bxpt, 'MozHeader' : bhdr }) env.ParseConfig('pkg-config ' + linking_options + ' --cflags gtk+-2.0') # libnotify env.ParseConfig('pkg-config --cflags nspr') env.Append( CXXFLAGS = FLAGS ) # Create headers and xpt files from idl xpts = [env.MozXPT('nsITray'), env.MozXPT('nsIFireTrayHandler')] headers = [env.MozHeader('nsITray')] parts = [] parts.extend(['nsTray.cpp', 'nsTrayModule.cpp']) nptray_name = 'nptray' + lib_arch print "NPTRAY: " + nptray_name nptray = env.SharedLibrary(nptray_name, parts) r = env.Install('#dist/components', [nptray, xpts, 'nsFireTrayHandler.js']) Default([xpts, headers, nptray]) Return('r')
Python
import os Import('zipbld') contents = [] content = 'core.js browserOverlay.xul mailOverlay.xul songOverlay.xul navigatorOverlay.xul options.xul options.js icon.png' for c in content.split(' '): contents.append('content' + os.sep + c) locales = 'bg-BG ca-AD de-DE en-US es-AR es-ES fa-IR fr-FR it-IT ja-JP mk-MK nl-NL pl-PL pt-BR ru-RU sk-SK sl-SI sv-SE tr-TR uk-UA zh-CN zh-TW' locale_files = 'browserOverlay.dtd core.properties mailOverlay.dtd options.dtd' for l in locales.split(' '): for f in locale_files.split(' '): contents.append('locale' + os.sep + l + os.sep + f) env = Environment(ZIPCHDIR= 'chrome', BUILDERS = {'Zip' : zipbld}) r = env.Zip('#dist/chrome/firetray.jar', contents) Return('r')
Python
import os, zipfile def zip(target, source, env): f = zipfile.ZipFile(str(target[0]), 'w', zipfile.ZIP_DEFLATED) chdir = None try: chdir = env['ZIPCHDIR'] + os.sep except: pass for s in source: s = str(s) if chdir and s.find(chdir) == 0: arcname = s[len(chdir):] else: arcname = s f.write(s, arcname) f.close() zipbld = Builder(action = zip) Export('zipbld') objs = [] for subdir in ['components', 'chrome']: r = SConscript(['%s/SConscript' % subdir]) objs.extend(r) env = Environment() r = env.Install('dist', 'chrome.manifest') objs.append(r) r = env.Install('dist', 'install.rdf') objs.append(r) r = env.Install('dist', 'License.txt') objs.append(r) r = env.Install('dist/defaults/preferences', 'defaults/preferences/prefs.js') objs.append(r) zipenv = Environment(BUILDERS = {'Zip' : zipbld}, ZIPCHDIR = 'dist') zipenv.Zip('firetray.xpi', objs) Alias('xpi', 'firetray.xpi')
Python
import sys, os, string, re platform = sys.platform try: FLAGS = os.environ['CXXFLAGS']; except: FLAGS = '-O2'; linking_options=' --libs '; try: DYNAMIC_LINKING = os.environ['DYNAMIC_LINKING']; except: linking_options=' --static ' print "linking: " + linking_options FLAGS += ' -include xpcom-config.h -include mozilla-config.h' FLAGS += ' -fno-rtti -fno-exceptions -fshort-wchar' FLAGS += ' -Wall -Wconversion -Wpointer-arith -Wcast-align -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor -Wno-long-long' FLAGS += ' -pedantic -pthread -pipe' try: lib_arch = os.environ['LIB_ARCH']; except: lib_arch = ''; try: gecko_bin = os.environ['GECKO_SDK_BIN']; if gecko_bin[-1] != os.sep: gecko_bin += os.sep gecko_include = os.environ['GECKO_SDK_INCLUDE']; if gecko_include[-1] != os.sep: gecko_include += os.sep gecko_idl = os.environ['GECKO_SDK_IDL']; if gecko_idl[-1] != os.sep: gecko_idl += os.sep gecko_lib = os.environ['GECKO_SDK_LIB']; if gecko_lib[-1] != os.sep: gecko_lib += os.sep except: try: geckosdk = os.environ['GECKO_SDK'] print "Using GECKO_SDK=" + geckosdk if geckosdk[-1] != os.sep: geckosdk += os.sep gecko_bin = geckosdk + 'bin' gecko_sdk_bin = geckosdk + 'sdk/bin' gecko_include = geckosdk + 'include' gecko_idl = geckosdk + 'idl' gecko_lib = geckosdk + 'lib' except: print "Please set environment variable GECKO_SDK first (or in alternative the variables GECKO_SDK_BIN, GECKO_SDK_INCLUDE, GECKO_SDK_IDL, GECKO_SDK_LIB)." sys.exit(1) # Hack to detect Mozilla version version_re = re.compile('#define MOZILLA_VERSION "(.*?)"') xpcom_libs = ['xpcomglue_s'] with open(gecko_include + os.sep + 'mozilla-config.h', 'r') as f: for line in f: version_match = version_re.match(line) if version_match: version = string.split(version_match.group(1), '.') if int(version[0]) >= 2: # OK, we're building with Mozilla 2.0 FLAGS += ' -DGECKO_2' if 'GECKO_19_COMPAT' in os.environ: FLAGS += ' -DMOZ_NO_MOZALLOC' xpcom_libs = ['xpcomglue_s_nomozalloc'] else: xpcom_libs.append('mozalloc') break # Create two builders to create xpt and header files from idl. bxpt = Builder(action = 'typelib.py -Icomponents -I' + gecko_idl + ' -o $TARGET $SOURCE' + ' --cachedir="."', suffix = '.xpt', src_suffix = '.idl') bhdr = Builder(action = 'header.py -Icomponents -I' + gecko_idl + ' -o $TARGET $SOURCE' + ' --cachedir="."', suffix = '.h', src_suffix = '.idl') # Create environment object for build env = Environment( CPPPATH = [gecko_include], LIBPATH = [gecko_lib], LIBS = xpcom_libs, ENV = os.environ) env.AppendENVPath('PATH', gecko_bin) env.AppendENVPath('PATH', gecko_sdk_bin) env.Append(BUILDERS = {'MozXPT' : bxpt, 'MozHeader' : bhdr }) env.ParseConfig('pkg-config ' + linking_options + ' --cflags gtk+-2.0') # libnotify env.ParseConfig('pkg-config --cflags nspr') env.Append( CXXFLAGS = FLAGS ) # Create headers and xpt files from idl xpts = [env.MozXPT('nsITray'), env.MozXPT('nsIFireTrayHandler')] headers = [env.MozHeader('nsITray')] parts = [] parts.extend(['nsTray.cpp', 'nsTrayModule.cpp']) nptray_name = 'nptray' + lib_arch print "NPTRAY: " + nptray_name nptray = env.SharedLibrary(nptray_name, parts) r = env.Install('#dist/components', [nptray, xpts, 'nsFireTrayHandler.js']) Default([xpts, headers, nptray]) Return('r')
Python
import os Import('zipbld') contents = [] content = 'core.js browserOverlay.xul mailOverlay.xul songOverlay.xul navigatorOverlay.xul options.xul options.js icon.png' for c in content.split(' '): contents.append('content' + os.sep + c) locales = 'bg-BG ca-AD de-DE en-US es-AR es-ES fa-IR fr-FR it-IT ja-JP mk-MK nl-NL pl-PL pt-BR ru-RU sk-SK sl-SI sv-SE tr-TR uk-UA zh-CN zh-TW' locale_files = 'browserOverlay.dtd core.properties mailOverlay.dtd options.dtd' for l in locales.split(' '): for f in locale_files.split(' '): contents.append('locale' + os.sep + l + os.sep + f) env = Environment(ZIPCHDIR= 'chrome', BUILDERS = {'Zip' : zipbld}) r = env.Zip('#dist/chrome/firetray.jar', contents) Return('r')
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- import sys,cgi,re,Image,Gnuplot,string,os sys.path+=[os.getcwd()] from types import * from firesocket import * try: form=cgi.FieldStorage() if form.has_key("server"): server=form["server"].value else: server="localhost" if form.has_key("port"): port=int(form["port"].value) else: port=12960 if form.has_key("image"): image=form["image"].value else: image="100.jpg" if form.has_key("feature"): feature=form["feature"].value else: feature="1" s=FIRESocket() s.connect(server,port) s.sendcmd("feature "+image+" "+feature) line=s.getline() suffix=string.split(line)[1] lines=[] line=s.getline() while line!="end": lines+=[line] line=s.getline() s.sendcmd("bye") if suffix.endswith(".histo") or suffix.endswith(".histo.gz") or suffix.endswith("oldhisto") or suffix.endswith("oldhisto.gz"): for l in lines: if l.startswith("data"): tokens=string.split(l) tokens.pop(0) tokens=map(lambda t: float(t),tokens) bins=len(tokens) maximum=max(tokens) g=Gnuplot.Gnuplot() g('set terminal png size 300,200') g('unset xtics') g('unset ytics') g('set data style boxes') print "Content-Type: image/png\n" sys.stdout.flush() g.plot(Gnuplot.Data(tokens)) elif suffix.endswith(".vec.gz") or suffix.endswith(".oldvec.gz") or suffix.endswith(".vec"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: if l.startswith("data"): print l[5:] print "</body></html>\n" elif suffix.endswith(".textID"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body>\n</html>" elif suffix.endswith("txt") or suffix.endswith("txt.gz"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body></html>\n" elif suffix.endswith(".png"): for l in lines: if l.startswith("sizes"): tok=string.split(l) xsize=int(tok[1]) ysize=int(tok[2]) zsize=int(tok[3]) if l.startswith("data"): tok=string.split(l) tok.pop(0) if zsize==1: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): g=int(float(tok.pop(0))*255) i.putpixel((x,y),(g,g,g)) elif zsize==3: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): r=int(float(tok.pop(0))*255) g=int(float(tok.pop(0))*255) b=int(float(tok.pop(0))*255) i.putpixel((x,y),(r,g,b)) print "Content-Type: image/png\n" sys.stdout.flush() i.save(sys.stdout,"png") else: print "Content-Type: text/html\n" sys.stdout.flush() print suffix print "feature not supported: ",suffix for l in lines: print l+"<br>" print "</body></html>\n" except IOError: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Something failed"
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- import sys,cgi,re,Image,Gnuplot,string,os sys.path+=[os.getcwd()] from types import * from firesocket import * try: form=cgi.FieldStorage() if form.has_key("server"): server=form["server"].value else: server="localhost" if form.has_key("port"): port=int(form["port"].value) else: port=12960 if form.has_key("image"): image=form["image"].value else: image="100.jpg" if form.has_key("feature"): feature=form["feature"].value else: feature="1" s=FIRESocket() s.connect(server,port) s.sendcmd("feature "+image+" "+feature) line=s.getline() suffix=string.split(line)[1] lines=[] line=s.getline() while line!="end": lines+=[line] line=s.getline() s.sendcmd("bye") if suffix.endswith(".histo") or suffix.endswith(".histo.gz") or suffix.endswith("oldhisto") or suffix.endswith("oldhisto.gz"): for l in lines: if l.startswith("data"): tokens=string.split(l) tokens.pop(0) tokens=map(lambda t: float(t),tokens) bins=len(tokens) maximum=max(tokens) g=Gnuplot.Gnuplot() g('set terminal png size 300,200') g('unset xtics') g('unset ytics') g('set data style boxes') print "Content-Type: image/png\n" sys.stdout.flush() g.plot(Gnuplot.Data(tokens)) elif suffix.endswith(".vec.gz") or suffix.endswith(".oldvec.gz") or suffix.endswith(".vec"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: if l.startswith("data"): print l[5:] print "</body></html>\n" elif suffix.endswith(".textID"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body>\n</html>" elif suffix.endswith("txt") or suffix.endswith("txt.gz"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body></html>\n" elif suffix.endswith(".png"): for l in lines: if l.startswith("sizes"): tok=string.split(l) xsize=int(tok[1]) ysize=int(tok[2]) zsize=int(tok[3]) if l.startswith("data"): tok=string.split(l) tok.pop(0) if zsize==1: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): g=int(float(tok.pop(0))*255) i.putpixel((x,y),(g,g,g)) elif zsize==3: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): r=int(float(tok.pop(0))*255) g=int(float(tok.pop(0))*255) b=int(float(tok.pop(0))*255) i.putpixel((x,y),(r,g,b)) print "Content-Type: image/png\n" sys.stdout.flush() i.save(sys.stdout,"png") else: print "Content-Type: text/html\n" sys.stdout.flush() print suffix print "feature not supported: ",suffix for l in lines: print l+"<br>" print "</body></html>\n" except IOError: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Something failed"
Python
#!/usr/bin/python import sys import cgi import re import Image sys.stderr=sys.stdout try: form=cgi.FieldStorage() imagefilename=form["image"].value outWidth=-1 outHeight=-1 maxDim=-1 if(form.has_key("max")): maxDim=int(form["max"].value) if(form.has_key("width")): outWidth=int(form["width"].value) if(form.has_key("height")): outHeight=int(form["height"].value) inImg=Image.open(imagefilename) inWidth=inImg.size[0] inHeight=inImg.size[1] if maxDim!=-1: if inWidth>inHeight: outWidth=maxDim else: outHeight=maxDim if (outWidth==-1 and outHeight==-1): outImg=inImg elif (outWidth==-1): scaleFactor=float(outHeight)/float(inHeight) outWidth=int(scaleFactor*inWidth) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) elif (outHeight==-1): scaleFactor=float(outWidth)/float(inWidth) outHeight=int(scaleFactor*inHeight) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) else: outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) contenttype="image/jpg" print "Content-Type: "+contenttype+"\n" outImg=outImg.convert("RGB") outImg.save(sys.stdout,"jpeg") except: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Access not permitted"
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- #$Header$ # print cgi-header print "Content-Type: text/html\n\n" print #print "<pre style=\"font-family:Fixedsys,Courier,1px;\">" # to have error messages as readable as possible, this # is switched of right before displaying the main part of the page #import lots of stuff import cgi, re, sys, traceback, os, Image #import cgitb; cgitb.enable() from urllib import quote,unquote from types import * # redirect stderr to have error messages on the webpage and not in the # webserver's log sys.stderr=sys.stdout # to be able to find the config sys.path+=[os.getcwd()] #import "my" socket implementation from firesocket import * # ---------------------------------------------------------------------- # import the config # it is assumed there is a file called config in the same file as the cgi. # an example for a valid config: ## settings for i6 #positiveImg="http://www-i6.iatik.rwth-aachen.de/~deselaers/images/positive.png" #negativeImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/negativ.png" #neutralImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/neutral.png" #fireLogo="/u/deselaers/work/src/fire/cgi/fire-logo.png" #i6Logo= "/u/deselaers/work/src/fire/cgi/i6.png" #TemplateFile = "/u/deselaers/work/src/fire/cgi/fire-template.html" #fireServer="deuterium" #firePort=12960 #tempdir="/tmp" #maxSize=1000, 1000 #minSize=200, 200 # ---------------------------------------------------------------------- import config # settings for the linear (standard) scoring algorithm. using this # algorithm the weights can be changed from the web interface class LinearScoring: def __init__(self): self.size=0 self.weights=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) if(tmp=="weight"): idx=status.pop(0) w=status.pop(0) self.weights+=[w] else: print "Cannot parse LinearScoring settings" def getForm(self): result="" result+="<tr><th colspan=3> Settings for LinearScoring</th></tr>" for i in range(len(self.weights)): result+="<tr><td> Weight "+str(i)+"</td>" result+="<td colspan=2><input name=\"weight"+str(i)+"\" type=\"text\" value=\""+self.weights[i]+"\"></td></tr>" return result # settings for maxent scoring algorithm class MaxEntScoring: def __init__(self): self.size=0 self.factor=0 self.offset=0 self.lambdas=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) tmp=status.pop(0) self.factor=status.pop(0) tmp=status.pop(0) self.offset=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) idx=status.pop(0) l=status.pop(0) self.lambdas+=[l] def getForm(self): result="" result+="<tr><th colspan=3> Settings for MaxEntScoring</th></tr>" for i in range(len(self.lambdas)/2): result+="<tr><td> Lambda "+str(i)+"</td>" result+="<td>"+self.lambdas[i]+"</td><td>"+self.lambdas[i+len(self.lambdas)/2]+"</td></tr>" return result # a class to store the settings of fire this classes uses the classes # defined above to manage the settings of the active scoring algorithm class FireSettings: def __init__(self): # variable initilization only. all member variables are defined here. self.fireServer=config.fireServer self.firePort=config.firePort self.dbsize=0 self.scoringname="" self.results=0 self.expansions=0 self.distances=[] self.suffices=[] self.path="" self.scoring="" def get(self,s): # get the settings from the server, i.e. read the string s and parse it. self.distances=[] self.suffices=[] s.sendcmd("info") msg=s.getline() status=re.split(" ",msg) print "<!--"+str(status)+"-->" while(len(status)>0): keyword=status.pop(0) if keyword=="filelist": self.dbsize=status.pop(0) elif keyword=="results": self.results=status.pop(0) elif keyword=="path": self.path=status.pop(0) elif keyword=="extensions": self.expansions=status.pop(0) elif keyword=="scoring": self.scoringname=status.pop(0) if self.scoringname=="linear": self.scoring=LinearScoring() elif self.scoringname=="maxent": self.scoring=MaxEntScoring() self.scoring.get(status) elif keyword=="suffix": no=status.pop(0) suffix=status.pop(0) self.suffices+=[suffix] distname=status.pop(0) self.distances+=[distname] else: print "<!-- Unknown keyword in stream : "+keyword+" -->" def display(self): # display the settings dialog self.get(s) result="<h4>Settings for fire</h4>" result=result+"<form method=\"post\" name=\"settingsForm\">" result=result+"<input type=\"hidden\" name=\"server\" value=\""+str(self.fireServer)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(self.firePort)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"settings\" value=\"1\"/>\n" result=result+"<table border=\"1\">\n" result=result+"<tr><th colspan=3> General Settings</th></tr>" result=result+"<tr><td>Number of images in database</td><td colspan=\"2\">"+str(self.dbsize)+"</td></tr>\n" result=result+"<tr><td>Number of results shown</td><td colspan=\"2\"><input type=\"text\" value=\""+self.results+"\" name=\"results\"/></td></tr>\n" result=result+"<tr><td>Scoring</td><td colspan=\"2\">"+self.getScoringChooser()+"\n" result=result+"<tr><td>Number of Images for Query Expansion</td><td colspan=\"2\"><input type=\"text\" value=\""+self.expansions+"\" name=\"extensions\"/></td></tr>\n" result=result+self.getDistForm() result=result+self.getScoringForm() result=result+"</table>\n" result=result+"Password: <input type=\"password\" name=\"password\">\n" result=result+"<input type=\"submit\" name=\"Save\" value=\"Save\"/>\n" result=result+"</form>" return result def getScoringChooser(self): # select the chooser for the server result="<select name=\"scoring\">\n<option value=\"\">" for scor in ['linear','maxent']: if self.scoringname==scor: result=result+"<option selected value=\""+scor+"\">"+scor+"</option>\n" else: result=result+"<option value=\""+scor+"\">"+scor+"</option>\n" result+="</select>\n" return result def getScoringForm(self): # display the form element to select the scoring algorihtm return self.scoring.getForm() def getDistForm(self): result="" result+="<tr><th colspan=3> Settings for Distance Functions</th></tr>" for no in range(len(self.distances)): result+="<tr><td> Distance "+str(no)+": "+self.suffices[no]+"</td><td>"+self.getDistChooser(no,self.distances[no])+"</td></tr>" return result def getDistChooser(self,no,distName): result="<select name=\"dist"+str(no)+"\">\n<option value=\"\">" s.sendcmd("setdist") distsString=s.getline() dists=re.split(" ",distsString) for d in dists: if d==distName: result=result+"<option selected value=\""+d+"\">"+d+"</option>\n" else: result=result+"<option value=\""+d+"\">"+d+"</option>\n" result=result+"</select>\n" return result def process(self,form): result="<!-- processing settings -->\n" if form.has_key("results"): if form.has_key("password"): password=form["password"].value else: password="" s.sendcmd("password "+password) l=s.getline() result+="<!-- "+l+"-->" if l!="ok": result+="Changing settings denied: Not authorized!" for i in form.keys(): if i.find("dist")==0: no=i[4:] d=form[i].value if d!=self.distances[int(no)]: # only change when changed s.sendcmd("setdist "+no+" "+d) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("weight")==0: no=i[6:] w=float(form[i].value) if self.scoringname=="linear": if(float(self.scoring.weights[int(no)])!=float(w)): s.sendcmd("setweight "+no+" "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" else: print "weights not supported" elif i.find("results")==0: if int(form[i].value)!=int(self.results): s.sendcmd("setresults "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("extensions")==0: if int(self.expansions)!=int(form[i].value): s.sendcmd("setextensions "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("scoring")==0: sn=form[i].value if(sn!=self.scoringname): # only change when changed s.sendcmd("setscoring "+sn) l=s.getline() result=result+"<!-- "+l+" -->\n" self.scoringname=sn else: result=result+"<!-- "+i+"-->\n" result=result+"<!-- settings processed -->\n" return result # ---------------------------------------------------------------------- # Load the template file and display the content in this template file # the string FIRELOGOSTRINGHERE, I6LOGOSTRINGHERE, and "INSERT CONTENT # HERE" are replaced by the configured/generated strings # ---------------------------------------------------------------------- def Display(Content): TemplateHandle = open(config.TemplateFile, "r") # open in read only mode # read the entire file as a string TemplateInput = TemplateHandle.read() TemplateHandle.close() # close the file # this defines an exception string in case our # template file is messed up BadTemplateException = "There was a problem with the HTML template." TemplateInput = re.sub("FIRELOGOSTRINGHERE",config.fireLogo,TemplateInput) TemplateInput = re.sub("I6LOGOSTRINGHERE",config.i6Logo,TemplateInput) SubResult = re.subn("INSERT CONTENT HERE",Content,TemplateInput) if SubResult[1] == 0: raise BadTemplateException print SubResult[0] def sendretrieve(querystring): filterstring="" # if(form.has_key("filter1")): # filterstring+=" -porn2-sorted/009-www.ficken.bz-images-ficken.png" # if(form.has_key("filter2")): # filterstring+=" -porn2-sorted/037-www.free-porn-free-sex.net-free-porn-free-sex-free-sex-sites.png" s.sendcmd("retrieve "+querystring+filterstring) # ---------------------------------------------------------------------- # handle a retrieval request which was generated by clicking a random # image, that is: # 1. process the form # - extract the filename of the image which is used as query # 2. send the query to the server # 3. wait for the servers answer # 4. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def retrieve(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["queryImage"].value sendretrieve("+"+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimage,0) return result # ---------------------------------------------------------------------- # resizes an image while keeping aspect ratio # ---------------------------------------------------------------------- def resizeImage(im, newSize): newX, newY = newSize if(im.size < newSize): xSize, ySize = im.size ratio=float(xSize)/float(ySize) if(ySize < xSize): newSize=(int(newY*ratio),newY) else: newSize=(newX,int(newX*(1/ratio))) out = Image.new("RGB", newSize) out = im.resize(newSize, Image.ANTIALIAS) else: im.thumbnail(newSize, Image.ANTIALIAS) out=im return out # ---------------------------------------------------------------------- # verifies the image file and resizes the image according to # minSize and maxSize parameters in config.py # ---------------------------------------------------------------------- def checkImage(imagefile): maxSize=config.maxSize minSize=config.minSize try: im=Image.open(imagefile) except: return 0 if(im.size<minSize): im=resizeImage(im, minSize) elif(im.size>maxSize): im=resizeImage(im, maxSize) im.save(imagefile) return 1 # ---------------------------------------------------------------------- # handle a serverfile-request # ---------------------------------------------------------------------- def serverFile(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["serverfile"].value checkImage(queryimage) imagename=queryimage[queryimage.rfind("/")+1:len(queryimage)] s.sendcmd("newfile 2 "+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+imagename,0) return result # ---------------------------------------------------------------------- # handle a newfile-request # ---------------------------------------------------------------------- def newFile(form): temporaryFiles=config.tempdir # standard: "/tmp" result="<h3>Retrieval Result</h3>\n" if(save_uploaded_file(form,"absolute_path",temporaryFiles)==0): result=result+"No Retrieval Result available!" return result fileitem = form["absolute_path"] # f=os.popen("ls -l "+ temporaryFiles+"/"+fileitem.filename) # print f.readlines() if(checkImage(temporaryFiles+"/"+fileitem.filename)==0): result=result+"Delivered file was not a valid image!" return result s.sendcmd("newfile 2 "+temporaryFiles+"/"+fileitem.filename+".png") msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+fileitem.filename,0) return result # This saves a file uploaded by an HTML form. # The form_field is the name of the file input field from the form. # For example, the following form_field would be "file_1": # <input name="file_1" type="file"> # The upload_dir is the directory where the file will be written. # If no file was uploaded or if the field does not exist then # this does nothing. # written by Noah Spurrier, modified by Fabian Schwahn def save_uploaded_file(form, form_field, upload_dir): if not form.has_key(form_field): return 0 fileitem = form[form_field] completepath = upload_dir + fileitem.filename if os.path.isdir(completepath): return 0 if not fileitem.file: return 0 fout = open (os.path.join(upload_dir, fileitem.filename), 'wb') while 1: chunk = fileitem.file.read(100000) if not chunk: break fout.write (chunk) fout.close() return 1 # ---------------------------------------------------------------------- # handle a retrieval request which was generated by relevance feedback. # That is: # 1. process the form # - extract the filenames of positive and negative examples # 2. generate the query string # 3. send the query to the server # 4. wait for the servers answer # 5. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def feedbackretrieve(form): print "<!-- feedback retrieve \n" print form print "-->\n" result="<h3>Retrieval Result</h3>\n" queryimages="" for field in form.keys(): if field.startswith("relevance"): imageno=re.sub("relevance","",field) imagename=form["resultImage"+imageno].value relevance=form[field].value if relevance!="0": queryimages=queryimages+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" result=result+"\n<!-- "+queryimages+" -->\n" sendretrieve(queryimages) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimages,0) return result # ---------------------------------------------------------------------- # given the retrieval result string of the server process this answer # and create the part of the html page displaying these results. this # includes the buttons for relevance feedback and the hidden fields # for server settings (e.g.\ which server, which port). also the # buttons for "more results" and "relevance feedback" are generated. # the button for saving relevances is deaktivated as it is not used # ---------------------------------------------------------------------- def displayResults(tokens,querytype,querystring,resultsStep): if(re.search("[0-9]+(\.[0-9]+)?", tokens[0]) == None): result="Could not read retrieval result.\n" s.flush() return result print "<!-- "+str(tokens)+"-->" i=0 result="<form method=\"post\" name=\"resultForm\"><table>\n<tr>\n" result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+querystring+"\"/>\n" result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+quote(querystring)+"\" />\n" result=result+"<input type=\"hidden\" name=\"resultsstep\" value=\""+str(resultsStep)+"\"/>\n" first=True while(len(tokens) > 0): resNo=str(i) img=tokens.pop(0) score=float(tokens.pop(0)) result=result+"<td>\n" result=result+"<a href=\""+config.fireurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&imageinfo="+img+"\" target=\"_blank\">" # support for the select-rectangle tool #------------- # result=result+"<a href=\"save_coord.cgi?to_do=UpdateImage&upload_type=server&port="+str(settings.firePort)+"&image_name="+settings.path+"/"+img+"\" target=\"_top\">" #------------- # shows the image #------------- # result=result+"<a href=\"img.py?image="+settings.path+"/"+img+"\" target=\"_blank\">" #------------ result=result+"<img src=\""+config.imgpyurl+"?max=150&image="+settings.path+"/"+img+"\" title=\""+str(score)+"-"+img+"\" name=\""+str(score)+"-"+img+"\">\n<br>\n" result=result+"</a>" result=result+"<input type=\"hidden\" name=\"resultImage"+resNo+"\" value=\""+img+"\">\n" if first: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\" checked><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\"><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" first=False else: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\"><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\" checked><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" result=result+"</td>\n\n" i=i+1 if i%5==0: result=result+"</tr>\n\n\n<tr>" result=result+"</tr></table>\n" # result+=filterbuttons() result=result+"<button title=\"expandresults\" name=\"expandresults\" type=\"submit\" onClick=\"document.resultForm.feedback.value='expandresults';document.resultForm.submit()\">more results</button>\n" result=result+"<button title=\"requery\" name=\"requery\" type=\"submit\" onClick=\"document.resultForm.feedback.value='requery';document.resultForm.submit()\">requery</button>\n" # result=result+"<button title=\"saverelevances\" name=\"relevancessave\" onClick=\"document.resultForm.feedback.value='saverelevances';document.resultForm.submit()\" \"type=\"submit\">save relevances</button>\n" result=result+"<input type=\"hidden\" name=\"feedback\" value=\"yes\"/>\n" result=result+"</form>\n" return result def filterbuttons(): # display the buttons for the filter result="" result=result+"filter 1: <input type=\"checkbox\" name=\"filter1\" value=\"1\">\n" result=result+"filter 2: <input type=\"checkbox\" name=\"filter2\" value=\"2\">\n<br>\n" return result # ---------------------------------------------------------------------- # ask the server for filenames of random images and create the part of # the html page showing random images. Steps: # 1. send "random" to the server # 2. receive the servers answer # 3. process the answer: # - get the filenames and for each filename create a querybutton # 4. put the "more random images" button, such that we can get a new set # of random images # ---------------------------------------------------------------------- def randomImages(): # display random images s.sendcmd("random") result="<hr><h3> Random Images - Click one to start a query </h3>" result+="""<form method="post" name="queryForm" enctype="multipart/form-data"> <input type="hidden" name="queryImage" value=""> """ result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result+=filterbuttons() res=s.getline() for img in re.split(" ",res): if img != "" and img != "\n": result=result+"<button title=\""+img+"\" name=\"searchButton\" type=\"submit\" onClick=\"document.queryForm.queryImage.value='"+img+"';document.queryForm.submit()\" value=\""+img+"\">\n" result=result+"<img src=\""+config.imgpyurl+"?max=100&image="+settings.path+"/"+img+"\" title=\""+img+"\">\n" result=result+"</button>\n" if form.has_key("demomode"): seconds=form["demomode"].value url="http://" if(os.environ.has_key("HTTP_HOST") and os.environ.has_key("REQUEST_URI")): part1=os.environ["HTTP_HOST"] part2=re.sub("&queryImage=.*$","",os.environ["REQUEST_URI"]) url=url+part1+part2+"&queryImage="+img print "<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result=result+"<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result+="<br><div align=\"right\">\n<button title=\"new random images\" name=\"morerandom\" type=\"submit\">more random images</button>\n</div>\n" return result # ---------------------------------------------------------------------- # displays the newfile-form # ---------------------------------------------------------------------- def newFileForm(): result="<hr><h3> Upload - Use query image from your file system </h3>" result+="""<input type="hidden" name="newFile" value="0">""" result+="""<input name="absolute_path" type="file" size="30" onClick="document.queryForm.newFile.value=1;document.queryForm.submit()">""" result+="\n" return result # ---------------------------------------------------------------------- # generate the text field and the query button for text # queries # ---------------------------------------------------------------------- def textQueryForm(settings): result = "<hr><h3>Query by " if("textfeature" in settings.distances): result += "description" if("metafeature" in settings.distances): result += " or meta information" elif("metafeature" in settings.distances): result += "meta information" result += "</h3>\n" result += "<form method=\"post\" name=\"textQueryForm\">\n" result += "<input type=\"hidden\" name=\"server\" value=\""+str(settings.fireServer)+"\"/>\n" result += "<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" result += "<input type=\"hidden\" name=\"resultsstep\" value=\"0\"/>\n" result += "<input type=\"text\" name=\"textquerystring\" size=\"30\" value=\"\"/>\n" result += "<input type=\"submit\" value=\"query\"/>\n" if("metafeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&metafeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on meta info</a>" if("textfeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&textfeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on description</a>" result += "</form>" return result def displayMetaFeatureInfo(): s.sendcmd("metafeatureinfo") mfi = s.getline() mfil = mfi.split(" ") result = "<h4>Help on queries by meta info</h4>\n" result += """If you want to find images with certain meta information attached, type in a request of the form <h5>key1:val1,key2:val2,...</h5>\n The following meta keys are available in this corpus:<br><br>\n""" #TODO: The table looks ugly! result += "<table>\n" result += "<tr>\n" result += " <th>key</th>\n" result += " <th>example value</th>\n" result += "</tr>\n" for mf in mfil: mfl = mf.split(":") result += "<tr>\n" result += " <td><b>"+mfl[0]+"</b></td>\n" # I know <b> is deprecated, but it still works :-) result += " <td>"+mfl[1]+"</td>\n" result += "</tr>\n" result += "</table>\n" return result def displayTextFeatureInfo(): result = "<h4>Help on queries by description</h4>\n" result += """If you want to find images which have text information attached to them, just enter the query into the textbox. Fire will then use an information retrieval engine to find the images that best match your query.<br><br> If you have text information in multiple languages for each image, you can give a query for every language. For example, if you have german and french text information and you want to search for "hand" in the respective languages, you enter <h5>Ge:"hand" Fr:"mains"</h5> Here, "Ge" has to be the suffix for the german textfiles and "Fr" has to be the suffix for the fench textfiles. Fire will then use both queries and send them to separate information retrieval engines.""" return result # ---------------------------------------------------------------------- # this function makes the server save a relevances logfile # but it is not used at the moment, because the saverelevances button # is deaktivated # ---------------------------------------------------------------------- def saveRelevances(form): querystring=form["querystring"].value relevancestring="" for field in form.keys(): if field.startswith("relevance-"): imagename=re.sub("relevance-","",field) relevance=form[field].value if relevance!="0": relevancestring=relevancestring+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" s.sendcmd("saverelevances Q "+querystring+" R "+relevancestring) res=s.getline(); message="<a href=\"javascript:back()\"> Go back to last query </a>" return message # ---------------------------------------------------------------------- # this is the "getMoreResults" function it basically does the same as # retrieve, uses the same query string as the last query used (this is # gotten from the form) and the calls displayResults # ---------------------------------------------------------------------- def expandQuery(form): resultsstep=int(form["resultsstep"].value) resultsstep=resultsstep+1 if(form.has_key("metaquerystring")): result="<h3>Metatag-based retrieval result</h3>\n" queryfield = "metaquerystring" cmd = "metaexpand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) elif(form.has_key("textquerystring")): result="<h3>Text-based retrieval result</h3>\n" queryfield = "textquerystring" cmd = "textexpand" queryimages = unquote(form["textquerystring"].value) s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) else: result="<h3>Retrieval Result</h3>\n" queryfield = "querystring" cmd = "expand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) msg=s.getline() tokens=re.split(" ",msg) if(tokens[0] == "notextinformation"): result=result+"No images matched your query: "+querystring result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,queryfield,queryimages,resultsstep) return result # ---------------------------------------------------------------------- # process a query using text- or metainformation from the text input # field. The query type is set to metaquery when the search string has # a leading "META " # This works identical as the retrieve function # ---------------------------------------------------------------------- def processTextQuery(form): # Check if it's meta or text # It's meta either if there's only the metafeature or it has a leading "META " hasmeta = "metafeature" in settings.distances hastext = "textfeature" in settings.distances querystring = form["textquerystring"].value if (hasmeta and (not hastext or querystring[:5] == "META ")): if(querystring[:5] == "META "): querystring = querystring[5:] querytype = "metaquerystring" result="<h3>Metatag-based retrieval result</h3>\n" s.sendcmd("metaretrieve +"+querystring) else: querytype = "textquerystring" result="<h3>Text-based retrieval result</h3>\n" s.sendcmd("textretrieve +"+querystring) msg=s.getline() tokens=re.split(" ",msg) if( (tokens[0] == "notextinformation") or (tokens[0] == "nometainformation") ): result=result+"No images matched your query: "+querystring if(querytype == "metaquerystring"): if(hastext): result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'META key1:val1,key2:val2,...'<br><br>\n" else: result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'key1:val1,key2:val2,...'<br><br>\n" result=result+"Also have a look at the help to see which keys are available.<br>\n" if(querytype == "textquerystring"): result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,querytype,querystring,0) return result # ---------------------------------------------------------------------- # create the link for the "settings" at the bottom of the page # ---------------------------------------------------------------------- def adminLink(fireServer, firePort): result="" result=result+"<a name=\"#\"></a>" result=result+"<a href=\"#\" "+\ "onClick=\"window.open('"+config.fireurl+"?server="+ \ fireServer+"&port="+str(firePort)+"&settings=1','newwindow',"+\ "'height=600, width=600')\">settings</a>" return result #<SCRIPT LANGUAGE="javascript"> #<!-- #window.open ('titlepage.html', 'newwindow', config='height=100, #width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no, #location=no, directories=no, status=no') #--> #</SCRIPT> # ---------------------------------------------------------------------- # the main program # ---------------------------------------------------------------------- # get form information in easily accessible manner form=cgi.FieldStorage() # make socket s = FIRESocket() settings=FireSettings() # see what server we have and if the webinterface specifed another one # than the one in the config file if form.has_key("server"): settings.fireServer=form["server"].value if form.has_key("port"): settings.firePort=int(form["port"].value) try: # connect to the server s.connect(settings.fireServer, settings.firePort) except: # if the server is down, give an error message # print "</pre>" message=""" <h2>FIRE Server down</h2> <p> Try again later, complain to <a href="mailto:deselaers@informatik.rwth-aachen.de">deselaers@informatik.rwth-aachen.de</a> or try other servers. """ Display(message) else: # everything is fine, connection to server is ok # try: message="" settings.get(s) # do we want to show the settings window? if(form.has_key("settings")): # see if there have been new settings defined message=settings.process(form) # generate the settings dialog message+=settings.display() # disonnect from server s.sendcmd("bye") print "</pre>" # display the settings dialog Display(message) # do we want to show the metafeatureinfo window? elif(form.has_key("metafeatureinfo")): message+=displayMetaFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) elif(form.has_key("imageinfo")): imagename=form["imageinfo"].value s.sendcmd("image "+imagename) line="" while(line != "end"): line=s.getline() tokens=re.split(" ",line) if tokens[0]=="imagefilename": message+="<img src=\""+config.imgpyurl+"?image="+tokens[1]+"\" alt=\""+tokens[1]+"\"/><br>"+"\n" elif tokens[0]=="class": message+="class: "+tokens[1]+"<br>\n" elif tokens[0]=="description": message+="description: "+tokens[1:]+"<br>\n" elif tokens[0]=="features": features=[] noffeatures=int(tokens[1]) for i in range(noffeatures): line=s.getline() tokens=re.split(" ",line) message+="<h3>"+str(i)+": "+tokens[2]+"</h3>\n<br>\n" if tokens[2].endswith(".histo.gz") \ or tokens[2].endswith(".histo") \ or tokens[2].endswith(".oldhisto.gz") \ or tokens[2].endswith(".png"): message+="<img src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\" alt=\""+tokens[2]+"\"/><br><br>\n" elif tokens[2].endswith(".vec.gz") \ or tokens[2].endswith(".oldvec.gz") \ or tokens[2].endswith(".vec") \ or tokens[2].endswith("txt") \ or tokens[2].endswith("txt.gz") \ or tokens[2].endswith("textID"): message+="<iframe src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\"></iframe><br><br>\n" else: message+="not yet supported<br>\n" line=s.getline() # get end s.sendcmd("bye") Display(message) elif(form.has_key("textfeatureinfo")): message+=displayTextFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) else: # we do not want to show the settings window if(form.has_key("newFile") and form["newFile"].value=="1"): #message+=str(form["newFile"]) message+=newFile(form) elif(form.has_key("serverfile")): message+=serverFile(form) elif(form.has_key("feedback")): # result images have been selected and are part of this query if form["feedback"].value=="requery": # relevance feedback message+=feedbackretrieve(form) elif form["feedback"].value=="expandresults": # more results message+=expandQuery(form) else: # save relevances (this will not happen currently) message=saveRelevances(form) elif(form.has_key("queryImage") and form["queryImage"].value!=""): # no relevance feedback, but just one of the random images was clicked message+=retrieve(form) elif form.has_key('textquerystring'): # no relevance feedback, no query image, but a query string for text queries message+=processTextQuery(form) # now generate the remainder of the website: queryfield for meta information, random images, adminlink if("textfeature" in settings.distances or "metafeature" in settings.distances): message+=textQueryForm(settings) message+=randomImages() message+=newFileForm() message+="<p align=\"right\">"+adminLink(settings.fireServer, settings.firePort)+"</p>" message+="</form>" # disconnect from server s.sendcmd("bye") print "</pre>" # display the generated webpage Display(message) # except Exception, e: # if anything went wrong: # show the error message as readable as possible, # disconnect from the server to keep it alive # and end yourself # print "<pre>" # print "Exception: ",e # s.sendcmd("bye") # print "</pre>"
Python
#default settings positiveImg="images/positive.png" negativeImg="images/negativ.png" neutralImg="images/neutral.png" fireLogo="images/fire-logo.png" i6Logo="images/i6.png" TemplateFile = "fire-template.html" fireServer="localhost" firePort=12960 imgpyurl="img.py" fireurl="fire.py" #tempdir="/tmp" #maxSize=1000, 1000 #minSize=200, 200
Python
#!/usr/bin/python import sys import cgi import re import Image sys.stderr=sys.stdout try: form=cgi.FieldStorage() imagefilename=form["image"].value outWidth=-1 outHeight=-1 maxDim=-1 if(form.has_key("max")): maxDim=int(form["max"].value) if(form.has_key("width")): outWidth=int(form["width"].value) if(form.has_key("height")): outHeight=int(form["height"].value) inImg=Image.open(imagefilename) inWidth=inImg.size[0] inHeight=inImg.size[1] if maxDim!=-1: if inWidth>inHeight: outWidth=maxDim else: outHeight=maxDim if (outWidth==-1 and outHeight==-1): outImg=inImg elif (outWidth==-1): scaleFactor=float(outHeight)/float(inHeight) outWidth=int(scaleFactor*inWidth) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) elif (outHeight==-1): scaleFactor=float(outWidth)/float(inWidth) outHeight=int(scaleFactor*inHeight) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) else: outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) contenttype="image/jpg" print "Content-Type: "+contenttype+"\n" outImg=outImg.convert("RGB") outImg.save(sys.stdout,"jpeg") except: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Access not permitted"
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- #$Header$ # print cgi-header print "Content-Type: text/html\n\n" print #print "<pre style=\"font-family:Fixedsys,Courier,1px;\">" # to have error messages as readable as possible, this # is switched of right before displaying the main part of the page #import lots of stuff import cgi, re, sys, traceback, os, Image #import cgitb; cgitb.enable() from urllib import quote,unquote from types import * # redirect stderr to have error messages on the webpage and not in the # webserver's log sys.stderr=sys.stdout # to be able to find the config sys.path+=[os.getcwd()] #import "my" socket implementation from firesocket import * # ---------------------------------------------------------------------- # import the config # it is assumed there is a file called config in the same file as the cgi. # an example for a valid config: ## settings for i6 #positiveImg="http://www-i6.iatik.rwth-aachen.de/~deselaers/images/positive.png" #negativeImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/negativ.png" #neutralImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/neutral.png" #fireLogo="/u/deselaers/work/src/fire/cgi/fire-logo.png" #i6Logo= "/u/deselaers/work/src/fire/cgi/i6.png" #TemplateFile = "/u/deselaers/work/src/fire/cgi/fire-template.html" #fireServer="deuterium" #firePort=12960 #tempdir="/tmp" #maxSize=1000, 1000 #minSize=200, 200 # ---------------------------------------------------------------------- import config # settings for the linear (standard) scoring algorithm. using this # algorithm the weights can be changed from the web interface class LinearScoring: def __init__(self): self.size=0 self.weights=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) if(tmp=="weight"): idx=status.pop(0) w=status.pop(0) self.weights+=[w] else: print "Cannot parse LinearScoring settings" def getForm(self): result="" result+="<tr><th colspan=3> Settings for LinearScoring</th></tr>" for i in range(len(self.weights)): result+="<tr><td> Weight "+str(i)+"</td>" result+="<td colspan=2><input name=\"weight"+str(i)+"\" type=\"text\" value=\""+self.weights[i]+"\"></td></tr>" return result # settings for maxent scoring algorithm class MaxEntScoring: def __init__(self): self.size=0 self.factor=0 self.offset=0 self.lambdas=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) tmp=status.pop(0) self.factor=status.pop(0) tmp=status.pop(0) self.offset=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) idx=status.pop(0) l=status.pop(0) self.lambdas+=[l] def getForm(self): result="" result+="<tr><th colspan=3> Settings for MaxEntScoring</th></tr>" for i in range(len(self.lambdas)/2): result+="<tr><td> Lambda "+str(i)+"</td>" result+="<td>"+self.lambdas[i]+"</td><td>"+self.lambdas[i+len(self.lambdas)/2]+"</td></tr>" return result # a class to store the settings of fire this classes uses the classes # defined above to manage the settings of the active scoring algorithm class FireSettings: def __init__(self): # variable initilization only. all member variables are defined here. self.fireServer=config.fireServer self.firePort=config.firePort self.dbsize=0 self.scoringname="" self.results=0 self.expansions=0 self.distances=[] self.suffices=[] self.path="" self.scoring="" def get(self,s): # get the settings from the server, i.e. read the string s and parse it. self.distances=[] self.suffices=[] s.sendcmd("info") msg=s.getline() status=re.split(" ",msg) print "<!--"+str(status)+"-->" while(len(status)>0): keyword=status.pop(0) if keyword=="filelist": self.dbsize=status.pop(0) elif keyword=="results": self.results=status.pop(0) elif keyword=="path": self.path=status.pop(0) elif keyword=="extensions": self.expansions=status.pop(0) elif keyword=="scoring": self.scoringname=status.pop(0) if self.scoringname=="linear": self.scoring=LinearScoring() elif self.scoringname=="maxent": self.scoring=MaxEntScoring() self.scoring.get(status) elif keyword=="suffix": no=status.pop(0) suffix=status.pop(0) self.suffices+=[suffix] distname=status.pop(0) self.distances+=[distname] else: print "<!-- Unknown keyword in stream : "+keyword+" -->" def display(self): # display the settings dialog self.get(s) result="<h4>Settings for fire</h4>" result=result+"<form method=\"post\" name=\"settingsForm\">" result=result+"<input type=\"hidden\" name=\"server\" value=\""+str(self.fireServer)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(self.firePort)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"settings\" value=\"1\"/>\n" result=result+"<table border=\"1\">\n" result=result+"<tr><th colspan=3> General Settings</th></tr>" result=result+"<tr><td>Number of images in database</td><td colspan=\"2\">"+str(self.dbsize)+"</td></tr>\n" result=result+"<tr><td>Number of results shown</td><td colspan=\"2\"><input type=\"text\" value=\""+self.results+"\" name=\"results\"/></td></tr>\n" result=result+"<tr><td>Scoring</td><td colspan=\"2\">"+self.getScoringChooser()+"\n" result=result+"<tr><td>Number of Images for Query Expansion</td><td colspan=\"2\"><input type=\"text\" value=\""+self.expansions+"\" name=\"extensions\"/></td></tr>\n" result=result+self.getDistForm() result=result+self.getScoringForm() result=result+"</table>\n" result=result+"Password: <input type=\"password\" name=\"password\">\n" result=result+"<input type=\"submit\" name=\"Save\" value=\"Save\"/>\n" result=result+"</form>" return result def getScoringChooser(self): # select the chooser for the server result="<select name=\"scoring\">\n<option value=\"\">" for scor in ['linear','maxent']: if self.scoringname==scor: result=result+"<option selected value=\""+scor+"\">"+scor+"</option>\n" else: result=result+"<option value=\""+scor+"\">"+scor+"</option>\n" result+="</select>\n" return result def getScoringForm(self): # display the form element to select the scoring algorihtm return self.scoring.getForm() def getDistForm(self): result="" result+="<tr><th colspan=3> Settings for Distance Functions</th></tr>" for no in range(len(self.distances)): result+="<tr><td> Distance "+str(no)+": "+self.suffices[no]+"</td><td>"+self.getDistChooser(no,self.distances[no])+"</td></tr>" return result def getDistChooser(self,no,distName): result="<select name=\"dist"+str(no)+"\">\n<option value=\"\">" s.sendcmd("setdist") distsString=s.getline() dists=re.split(" ",distsString) for d in dists: if d==distName: result=result+"<option selected value=\""+d+"\">"+d+"</option>\n" else: result=result+"<option value=\""+d+"\">"+d+"</option>\n" result=result+"</select>\n" return result def process(self,form): result="<!-- processing settings -->\n" if form.has_key("results"): if form.has_key("password"): password=form["password"].value else: password="" s.sendcmd("password "+password) l=s.getline() result+="<!-- "+l+"-->" if l!="ok": result+="Changing settings denied: Not authorized!" for i in form.keys(): if i.find("dist")==0: no=i[4:] d=form[i].value if d!=self.distances[int(no)]: # only change when changed s.sendcmd("setdist "+no+" "+d) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("weight")==0: no=i[6:] w=float(form[i].value) if self.scoringname=="linear": if(float(self.scoring.weights[int(no)])!=float(w)): s.sendcmd("setweight "+no+" "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" else: print "weights not supported" elif i.find("results")==0: if int(form[i].value)!=int(self.results): s.sendcmd("setresults "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("extensions")==0: if int(self.expansions)!=int(form[i].value): s.sendcmd("setextensions "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("scoring")==0: sn=form[i].value if(sn!=self.scoringname): # only change when changed s.sendcmd("setscoring "+sn) l=s.getline() result=result+"<!-- "+l+" -->\n" self.scoringname=sn else: result=result+"<!-- "+i+"-->\n" result=result+"<!-- settings processed -->\n" return result # ---------------------------------------------------------------------- # Load the template file and display the content in this template file # the string FIRELOGOSTRINGHERE, I6LOGOSTRINGHERE, and "INSERT CONTENT # HERE" are replaced by the configured/generated strings # ---------------------------------------------------------------------- def Display(Content): TemplateHandle = open(config.TemplateFile, "r") # open in read only mode # read the entire file as a string TemplateInput = TemplateHandle.read() TemplateHandle.close() # close the file # this defines an exception string in case our # template file is messed up BadTemplateException = "There was a problem with the HTML template." TemplateInput = re.sub("FIRELOGOSTRINGHERE",config.fireLogo,TemplateInput) TemplateInput = re.sub("I6LOGOSTRINGHERE",config.i6Logo,TemplateInput) SubResult = re.subn("INSERT CONTENT HERE",Content,TemplateInput) if SubResult[1] == 0: raise BadTemplateException print SubResult[0] def sendretrieve(querystring): filterstring="" # if(form.has_key("filter1")): # filterstring+=" -porn2-sorted/009-www.ficken.bz-images-ficken.png" # if(form.has_key("filter2")): # filterstring+=" -porn2-sorted/037-www.free-porn-free-sex.net-free-porn-free-sex-free-sex-sites.png" s.sendcmd("retrieve "+querystring+filterstring) # ---------------------------------------------------------------------- # handle a retrieval request which was generated by clicking a random # image, that is: # 1. process the form # - extract the filename of the image which is used as query # 2. send the query to the server # 3. wait for the servers answer # 4. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def retrieve(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["queryImage"].value sendretrieve("+"+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimage,0) return result # ---------------------------------------------------------------------- # resizes an image while keeping aspect ratio # ---------------------------------------------------------------------- def resizeImage(im, newSize): newX, newY = newSize if(im.size < newSize): xSize, ySize = im.size ratio=float(xSize)/float(ySize) if(ySize < xSize): newSize=(int(newY*ratio),newY) else: newSize=(newX,int(newX*(1/ratio))) out = Image.new("RGB", newSize) out = im.resize(newSize, Image.ANTIALIAS) else: im.thumbnail(newSize, Image.ANTIALIAS) out=im return out # ---------------------------------------------------------------------- # verifies the image file and resizes the image according to # minSize and maxSize parameters in config.py # ---------------------------------------------------------------------- def checkImage(imagefile): maxSize=config.maxSize minSize=config.minSize try: im=Image.open(imagefile) except: return 0 if(im.size<minSize): im=resizeImage(im, minSize) elif(im.size>maxSize): im=resizeImage(im, maxSize) im.save(imagefile) return 1 # ---------------------------------------------------------------------- # handle a serverfile-request # ---------------------------------------------------------------------- def serverFile(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["serverfile"].value checkImage(queryimage) imagename=queryimage[queryimage.rfind("/")+1:len(queryimage)] s.sendcmd("newfile 2 "+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+imagename,0) return result # ---------------------------------------------------------------------- # handle a newfile-request # ---------------------------------------------------------------------- def newFile(form): temporaryFiles=config.tempdir # standard: "/tmp" result="<h3>Retrieval Result</h3>\n" if(save_uploaded_file(form,"absolute_path",temporaryFiles)==0): result=result+"No Retrieval Result available!" return result fileitem = form["absolute_path"] # f=os.popen("ls -l "+ temporaryFiles+"/"+fileitem.filename) # print f.readlines() if(checkImage(temporaryFiles+"/"+fileitem.filename)==0): result=result+"Delivered file was not a valid image!" return result s.sendcmd("newfile 2 "+temporaryFiles+"/"+fileitem.filename+".png") msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+fileitem.filename,0) return result # This saves a file uploaded by an HTML form. # The form_field is the name of the file input field from the form. # For example, the following form_field would be "file_1": # <input name="file_1" type="file"> # The upload_dir is the directory where the file will be written. # If no file was uploaded or if the field does not exist then # this does nothing. # written by Noah Spurrier, modified by Fabian Schwahn def save_uploaded_file(form, form_field, upload_dir): if not form.has_key(form_field): return 0 fileitem = form[form_field] completepath = upload_dir + fileitem.filename if os.path.isdir(completepath): return 0 if not fileitem.file: return 0 fout = open (os.path.join(upload_dir, fileitem.filename), 'wb') while 1: chunk = fileitem.file.read(100000) if not chunk: break fout.write (chunk) fout.close() return 1 # ---------------------------------------------------------------------- # handle a retrieval request which was generated by relevance feedback. # That is: # 1. process the form # - extract the filenames of positive and negative examples # 2. generate the query string # 3. send the query to the server # 4. wait for the servers answer # 5. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def feedbackretrieve(form): print "<!-- feedback retrieve \n" print form print "-->\n" result="<h3>Retrieval Result</h3>\n" queryimages="" for field in form.keys(): if field.startswith("relevance"): imageno=re.sub("relevance","",field) imagename=form["resultImage"+imageno].value relevance=form[field].value if relevance!="0": queryimages=queryimages+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" result=result+"\n<!-- "+queryimages+" -->\n" sendretrieve(queryimages) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimages,0) return result # ---------------------------------------------------------------------- # given the retrieval result string of the server process this answer # and create the part of the html page displaying these results. this # includes the buttons for relevance feedback and the hidden fields # for server settings (e.g.\ which server, which port). also the # buttons for "more results" and "relevance feedback" are generated. # the button for saving relevances is deaktivated as it is not used # ---------------------------------------------------------------------- def displayResults(tokens,querytype,querystring,resultsStep): if(re.search("[0-9]+(\.[0-9]+)?", tokens[0]) == None): result="Could not read retrieval result.\n" s.flush() return result print "<!-- "+str(tokens)+"-->" i=0 result="<form method=\"post\" name=\"resultForm\"><table>\n<tr>\n" result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+querystring+"\"/>\n" result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+quote(querystring)+"\" />\n" result=result+"<input type=\"hidden\" name=\"resultsstep\" value=\""+str(resultsStep)+"\"/>\n" first=True while(len(tokens) > 0): resNo=str(i) img=tokens.pop(0) score=float(tokens.pop(0)) result=result+"<td>\n" result=result+"<a href=\""+config.fireurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&imageinfo="+img+"\" target=\"_blank\">" # support for the select-rectangle tool #------------- # result=result+"<a href=\"save_coord.cgi?to_do=UpdateImage&upload_type=server&port="+str(settings.firePort)+"&image_name="+settings.path+"/"+img+"\" target=\"_top\">" #------------- # shows the image #------------- # result=result+"<a href=\"img.py?image="+settings.path+"/"+img+"\" target=\"_blank\">" #------------ result=result+"<img src=\""+config.imgpyurl+"?max=150&image="+settings.path+"/"+img+"\" title=\""+str(score)+"-"+img+"\" name=\""+str(score)+"-"+img+"\">\n<br>\n" result=result+"</a>" result=result+"<input type=\"hidden\" name=\"resultImage"+resNo+"\" value=\""+img+"\">\n" if first: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\" checked><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\"><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" first=False else: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\"><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\" checked><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" result=result+"</td>\n\n" i=i+1 if i%5==0: result=result+"</tr>\n\n\n<tr>" result=result+"</tr></table>\n" # result+=filterbuttons() result=result+"<button title=\"expandresults\" name=\"expandresults\" type=\"submit\" onClick=\"document.resultForm.feedback.value='expandresults';document.resultForm.submit()\">more results</button>\n" result=result+"<button title=\"requery\" name=\"requery\" type=\"submit\" onClick=\"document.resultForm.feedback.value='requery';document.resultForm.submit()\">requery</button>\n" # result=result+"<button title=\"saverelevances\" name=\"relevancessave\" onClick=\"document.resultForm.feedback.value='saverelevances';document.resultForm.submit()\" \"type=\"submit\">save relevances</button>\n" result=result+"<input type=\"hidden\" name=\"feedback\" value=\"yes\"/>\n" result=result+"</form>\n" return result def filterbuttons(): # display the buttons for the filter result="" result=result+"filter 1: <input type=\"checkbox\" name=\"filter1\" value=\"1\">\n" result=result+"filter 2: <input type=\"checkbox\" name=\"filter2\" value=\"2\">\n<br>\n" return result # ---------------------------------------------------------------------- # ask the server for filenames of random images and create the part of # the html page showing random images. Steps: # 1. send "random" to the server # 2. receive the servers answer # 3. process the answer: # - get the filenames and for each filename create a querybutton # 4. put the "more random images" button, such that we can get a new set # of random images # ---------------------------------------------------------------------- def randomImages(): # display random images s.sendcmd("random") result="<hr><h3> Random Images - Click one to start a query </h3>" result+="""<form method="post" name="queryForm" enctype="multipart/form-data"> <input type="hidden" name="queryImage" value=""> """ result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result+=filterbuttons() res=s.getline() for img in re.split(" ",res): if img != "" and img != "\n": result=result+"<button title=\""+img+"\" name=\"searchButton\" type=\"submit\" onClick=\"document.queryForm.queryImage.value='"+img+"';document.queryForm.submit()\" value=\""+img+"\">\n" result=result+"<img src=\""+config.imgpyurl+"?max=100&image="+settings.path+"/"+img+"\" title=\""+img+"\">\n" result=result+"</button>\n" if form.has_key("demomode"): seconds=form["demomode"].value url="http://" if(os.environ.has_key("HTTP_HOST") and os.environ.has_key("REQUEST_URI")): part1=os.environ["HTTP_HOST"] part2=re.sub("&queryImage=.*$","",os.environ["REQUEST_URI"]) url=url+part1+part2+"&queryImage="+img print "<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result=result+"<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result+="<br><div align=\"right\">\n<button title=\"new random images\" name=\"morerandom\" type=\"submit\">more random images</button>\n</div>\n" return result # ---------------------------------------------------------------------- # displays the newfile-form # ---------------------------------------------------------------------- def newFileForm(): result="<hr><h3> Upload - Use query image from your file system </h3>" result+="""<input type="hidden" name="newFile" value="0">""" result+="""<input name="absolute_path" type="file" size="30" onClick="document.queryForm.newFile.value=1;document.queryForm.submit()">""" result+="\n" return result # ---------------------------------------------------------------------- # generate the text field and the query button for text # queries # ---------------------------------------------------------------------- def textQueryForm(settings): result = "<hr><h3>Query by " if("textfeature" in settings.distances): result += "description" if("metafeature" in settings.distances): result += " or meta information" elif("metafeature" in settings.distances): result += "meta information" result += "</h3>\n" result += "<form method=\"post\" name=\"textQueryForm\">\n" result += "<input type=\"hidden\" name=\"server\" value=\""+str(settings.fireServer)+"\"/>\n" result += "<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" result += "<input type=\"hidden\" name=\"resultsstep\" value=\"0\"/>\n" result += "<input type=\"text\" name=\"textquerystring\" size=\"30\" value=\"\"/>\n" result += "<input type=\"submit\" value=\"query\"/>\n" if("metafeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&metafeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on meta info</a>" if("textfeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&textfeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on description</a>" result += "</form>" return result def displayMetaFeatureInfo(): s.sendcmd("metafeatureinfo") mfi = s.getline() mfil = mfi.split(" ") result = "<h4>Help on queries by meta info</h4>\n" result += """If you want to find images with certain meta information attached, type in a request of the form <h5>key1:val1,key2:val2,...</h5>\n The following meta keys are available in this corpus:<br><br>\n""" #TODO: The table looks ugly! result += "<table>\n" result += "<tr>\n" result += " <th>key</th>\n" result += " <th>example value</th>\n" result += "</tr>\n" for mf in mfil: mfl = mf.split(":") result += "<tr>\n" result += " <td><b>"+mfl[0]+"</b></td>\n" # I know <b> is deprecated, but it still works :-) result += " <td>"+mfl[1]+"</td>\n" result += "</tr>\n" result += "</table>\n" return result def displayTextFeatureInfo(): result = "<h4>Help on queries by description</h4>\n" result += """If you want to find images which have text information attached to them, just enter the query into the textbox. Fire will then use an information retrieval engine to find the images that best match your query.<br><br> If you have text information in multiple languages for each image, you can give a query for every language. For example, if you have german and french text information and you want to search for "hand" in the respective languages, you enter <h5>Ge:"hand" Fr:"mains"</h5> Here, "Ge" has to be the suffix for the german textfiles and "Fr" has to be the suffix for the fench textfiles. Fire will then use both queries and send them to separate information retrieval engines.""" return result # ---------------------------------------------------------------------- # this function makes the server save a relevances logfile # but it is not used at the moment, because the saverelevances button # is deaktivated # ---------------------------------------------------------------------- def saveRelevances(form): querystring=form["querystring"].value relevancestring="" for field in form.keys(): if field.startswith("relevance-"): imagename=re.sub("relevance-","",field) relevance=form[field].value if relevance!="0": relevancestring=relevancestring+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" s.sendcmd("saverelevances Q "+querystring+" R "+relevancestring) res=s.getline(); message="<a href=\"javascript:back()\"> Go back to last query </a>" return message # ---------------------------------------------------------------------- # this is the "getMoreResults" function it basically does the same as # retrieve, uses the same query string as the last query used (this is # gotten from the form) and the calls displayResults # ---------------------------------------------------------------------- def expandQuery(form): resultsstep=int(form["resultsstep"].value) resultsstep=resultsstep+1 if(form.has_key("metaquerystring")): result="<h3>Metatag-based retrieval result</h3>\n" queryfield = "metaquerystring" cmd = "metaexpand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) elif(form.has_key("textquerystring")): result="<h3>Text-based retrieval result</h3>\n" queryfield = "textquerystring" cmd = "textexpand" queryimages = unquote(form["textquerystring"].value) s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) else: result="<h3>Retrieval Result</h3>\n" queryfield = "querystring" cmd = "expand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) msg=s.getline() tokens=re.split(" ",msg) if(tokens[0] == "notextinformation"): result=result+"No images matched your query: "+querystring result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,queryfield,queryimages,resultsstep) return result # ---------------------------------------------------------------------- # process a query using text- or metainformation from the text input # field. The query type is set to metaquery when the search string has # a leading "META " # This works identical as the retrieve function # ---------------------------------------------------------------------- def processTextQuery(form): # Check if it's meta or text # It's meta either if there's only the metafeature or it has a leading "META " hasmeta = "metafeature" in settings.distances hastext = "textfeature" in settings.distances querystring = form["textquerystring"].value if (hasmeta and (not hastext or querystring[:5] == "META ")): if(querystring[:5] == "META "): querystring = querystring[5:] querytype = "metaquerystring" result="<h3>Metatag-based retrieval result</h3>\n" s.sendcmd("metaretrieve +"+querystring) else: querytype = "textquerystring" result="<h3>Text-based retrieval result</h3>\n" s.sendcmd("textretrieve +"+querystring) msg=s.getline() tokens=re.split(" ",msg) if( (tokens[0] == "notextinformation") or (tokens[0] == "nometainformation") ): result=result+"No images matched your query: "+querystring if(querytype == "metaquerystring"): if(hastext): result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'META key1:val1,key2:val2,...'<br><br>\n" else: result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'key1:val1,key2:val2,...'<br><br>\n" result=result+"Also have a look at the help to see which keys are available.<br>\n" if(querytype == "textquerystring"): result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,querytype,querystring,0) return result # ---------------------------------------------------------------------- # create the link for the "settings" at the bottom of the page # ---------------------------------------------------------------------- def adminLink(fireServer, firePort): result="" result=result+"<a name=\"#\"></a>" result=result+"<a href=\"#\" "+\ "onClick=\"window.open('"+config.fireurl+"?server="+ \ fireServer+"&port="+str(firePort)+"&settings=1','newwindow',"+\ "'height=600, width=600')\">settings</a>" return result #<SCRIPT LANGUAGE="javascript"> #<!-- #window.open ('titlepage.html', 'newwindow', config='height=100, #width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no, #location=no, directories=no, status=no') #--> #</SCRIPT> # ---------------------------------------------------------------------- # the main program # ---------------------------------------------------------------------- # get form information in easily accessible manner form=cgi.FieldStorage() # make socket s = FIRESocket() settings=FireSettings() # see what server we have and if the webinterface specifed another one # than the one in the config file if form.has_key("server"): settings.fireServer=form["server"].value if form.has_key("port"): settings.firePort=int(form["port"].value) try: # connect to the server s.connect(settings.fireServer, settings.firePort) except: # if the server is down, give an error message # print "</pre>" message=""" <h2>FIRE Server down</h2> <p> Try again later, complain to <a href="mailto:deselaers@informatik.rwth-aachen.de">deselaers@informatik.rwth-aachen.de</a> or try other servers. """ Display(message) else: # everything is fine, connection to server is ok # try: message="" settings.get(s) # do we want to show the settings window? if(form.has_key("settings")): # see if there have been new settings defined message=settings.process(form) # generate the settings dialog message+=settings.display() # disonnect from server s.sendcmd("bye") print "</pre>" # display the settings dialog Display(message) # do we want to show the metafeatureinfo window? elif(form.has_key("metafeatureinfo")): message+=displayMetaFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) elif(form.has_key("imageinfo")): imagename=form["imageinfo"].value s.sendcmd("image "+imagename) line="" while(line != "end"): line=s.getline() tokens=re.split(" ",line) if tokens[0]=="imagefilename": message+="<img src=\""+config.imgpyurl+"?image="+tokens[1]+"\" alt=\""+tokens[1]+"\"/><br>"+"\n" elif tokens[0]=="class": message+="class: "+tokens[1]+"<br>\n" elif tokens[0]=="description": message+="description: "+tokens[1:]+"<br>\n" elif tokens[0]=="features": features=[] noffeatures=int(tokens[1]) for i in range(noffeatures): line=s.getline() tokens=re.split(" ",line) message+="<h3>"+str(i)+": "+tokens[2]+"</h3>\n<br>\n" if tokens[2].endswith(".histo.gz") \ or tokens[2].endswith(".histo") \ or tokens[2].endswith(".oldhisto.gz") \ or tokens[2].endswith(".png"): message+="<img src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\" alt=\""+tokens[2]+"\"/><br><br>\n" elif tokens[2].endswith(".vec.gz") \ or tokens[2].endswith(".oldvec.gz") \ or tokens[2].endswith(".vec") \ or tokens[2].endswith("txt") \ or tokens[2].endswith("txt.gz") \ or tokens[2].endswith("textID"): message+="<iframe src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\"></iframe><br><br>\n" else: message+="not yet supported<br>\n" line=s.getline() # get end s.sendcmd("bye") Display(message) elif(form.has_key("textfeatureinfo")): message+=displayTextFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) else: # we do not want to show the settings window if(form.has_key("newFile") and form["newFile"].value=="1"): #message+=str(form["newFile"]) message+=newFile(form) elif(form.has_key("serverfile")): message+=serverFile(form) elif(form.has_key("feedback")): # result images have been selected and are part of this query if form["feedback"].value=="requery": # relevance feedback message+=feedbackretrieve(form) elif form["feedback"].value=="expandresults": # more results message+=expandQuery(form) else: # save relevances (this will not happen currently) message=saveRelevances(form) elif(form.has_key("queryImage") and form["queryImage"].value!=""): # no relevance feedback, but just one of the random images was clicked message+=retrieve(form) elif form.has_key('textquerystring'): # no relevance feedback, no query image, but a query string for text queries message+=processTextQuery(form) # now generate the remainder of the website: queryfield for meta information, random images, adminlink if("textfeature" in settings.distances or "metafeature" in settings.distances): message+=textQueryForm(settings) message+=randomImages() message+=newFileForm() message+="<p align=\"right\">"+adminLink(settings.fireServer, settings.firePort)+"</p>" message+="</form>" # disconnect from server s.sendcmd("bye") print "</pre>" # display the generated webpage Display(message) # except Exception, e: # if anything went wrong: # show the error message as readable as possible, # disconnect from the server to keep it alive # and end yourself # print "<pre>" # print "Exception: ",e # s.sendcmd("bye") # print "</pre>"
Python
#!/usr/bin/python import sys,re import filelist filelist=filelist.FileList() filelist.load(sys.argv[1]) for i in filelist: cls=i[1] fname=i[0] print fname, for j in filelist: if j[1]==cls and j[0]!=fname: print j[0], print #print filelist
Python
import re,sys,string,os class FileList: def __init__(self): self.files=[] self.classes=False self.featuredirectories=False self.descriptions=False self.path="" self.rawpath="" self.suffices=[] self.filename2idx={} def __str__(self): result="" result+="Suffices: "+str(self.suffices) result+="Files: "+str(self.files) return result def __getitem__(self,i): return self.files[i] def __getslice__(self,i): return self.files[i] def index(self,filename): if self.filename2idx.has_key(filename): return self.filename2idx[filename] else: print >>sys.stderr,filename,"not in database, returning -1" #print >>sys.stderr,self.filename2idx #print >>sys.stderr,self.files return -1 #result=-1 #for i in range(len(self.files)): # if self.files[i][0]==filename: # result=i #if result==-1: # print "filelist.py: file",filename,"not in database" #return result def load(self, filename): fl=open(filename,"r") lines=fl.readlines() for l in lines: l=re.sub("\n","",l) tokens=string.split(l) if tokens[0] == "file": f=tokens[1] if self.classes==True: cls=int(tokens[2]) if self.descriptions: desc=tokens[3:] self.files+=[[f,cls,desc]] else: self.files+=[[f,cls]] elif self.descriptions: desc=tokens[2:] self.files+=[[f,0,desc]] else: self.files+=[[f,]] elif tokens[0] == "classes": if tokens[1]=="yes": self.classes=True elif tokens[0] == "descriptions" or tokens[0] == "description": if tokens[1]=="yes": self.descriptions=True elif tokens[0] == "featuredirectories": if tokens[1]=="yes": self.featuredirectories=True elif tokens[0] == "path": self.rawpath=tokens[1] self.path=self.rawpath if self.path.startswith("this"): self.path=self.path.replace("this+","") offs=os.path.dirname(filename) cwd=os.path.realpath(os.path.curdir) self.path=offs+"/"+self.path+"/" elif tokens[0] == "suffix": self.suffices+=[tokens[1]] self.initMap() def add(self, filename, class_=0, description=""): if description == "": assert(self.descriptions == False) self.files.append([filename, class_, description]) else: assert(self.descriptions == True) self.files.append([filename, class_]) def save(self, filename): if filename=="-": f=sys.stdout else: f=open(filename,"w") print >>f,"FIRE_filelist" if self.classes: print >>f,"classes yes" if self.descriptions: print >>f,"descriptions yes" if self.featuredirectories: print >>f,"featuredirectories yes" print >>f,"path",self.rawpath for s in self.suffices: print >>f,"suffix",s for fi in self.files: print >>f, "file %s" % " ".join(map(lambda x: str(x), fi)) def initMap(self): self.filename2idx={} for i in range(len(self.files)): self.filename2idx[self.files[i][0]]=i def basenameify(self): for i in range(len(self.files)): if len(self.files[i])==3: self.files[i]=(os.path.basename(self.files[i][0]),self.files[i][1], self.files[i][2]) if len(self.files[i])==2: self.files[i]=(os.path.basename(self.files[i][0]),self.files[i][1]) if len(self.files[i])==1: self.files[i]=(os.path.basename(self.files[i][0]),) def nameWithSuffix(self, item, suffix): assert item < len(self.files) assert suffix < len(self.suffices) return self.files[item][0] + "." + self.suffices[suffix] # generator for images with full path def fullpaths(self): for image in self.files: yield os.path.join(self.rawpath, image[0]) def get_full_path_for_item(self, item, suffixidx=-1): name = os.path.join(self.rawpath, self.files[item][0]) if suffixidx > -1 and len(self.suffices) > 0: name += "." + self.suffices[suffixidx] return name
Python
#!/usr/bin/python import sys, socket, re, os, string, time sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist #----------------------------------------------------------------- s=firesocket.FIRESocket() try: if len(sys.argv) < 5: print """USAGE: makedistfiles.py <querylist> <server> <port> <suffix> [-q] """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) suffix=sys.argv[4] try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." lines=ql.readlines() lines=map(lambda line: re.sub("\n","",line), lines) ql.close() i=0 for line in lines: print i,"/",len(lines) i+=1 tokens=re.split(" ",line) file=tokens[0] cmd="savedistances "+file+" "+file+"."+suffix print "SENDING: ",cmd s.sendcmd(cmd) res=s.getline() print res sys.stdout.flush() sys.stdout.flush() if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer filelist=filelist.FileList() filelist.load(sys.argv[1]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in filelist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class SparseHistogramFeature: def __init__(self): self.bins={} self.data={} self.steps=[] self.stepSize=[] self.min=[] self.max=[] self.dim=0 self.numberofBins=0 self.counter=0 self.filename="" def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_sparse_histogram" print >>f,"# sparse histogram file for FireV2" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps",reduce(lambda x,y: str(x)+" "+str(y),self.steps) print >>f,"min",reduce(lambda x,y: str(x)+" "+str(y),self.min) print >>f,"max",reduce(lambda x,y: str(x)+" "+str(y),self.max) print >>f,"bins",len(self.bins) for i in self.bins: print >>f,"data",i,self.bins[i] f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_sparse_histogram": fine=True elif line[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="bins": self.numberofBins=int(toks[1]) elif toks[0]=="data": self.bins[toks[1]]=int(toks[2]) self.data[toks[1]]=float(toks[2])/float(self.counter) else: print "Unparsed line: '"+line+"'."
Python
#------------------------------------------------------------------------------ # proxyserver implementation for communication with the web frontend and fire # server system # server must be reachable via network sockets in order to be of any use # #------------------------------------------------------------------------------ __author__ = "Jens Forster <jens.forster@rwth-aachen.de>" __version__= "0.1" from SocketServer import * from firesocket import * # Needed for stringhandling # re provides regular expressions and methods import re import string # Needed for suitable choosing of random images # hence each retrieval server will only have access to unique # part of the database import random # Needed for logging import logging #from logging.handlers import TimedRotatingFileHandler import sys import os import os.path __all__ =["FIREProxyServer", "FIREProxyHandler"] class FIREProxyServer(TCPServer): request_queque_size = 1 allow_reuse_address = True def __init__(self,server_address, retr_addrs, RequestHandlerClass,logDestination=None): TCPServer.__init__(self,server_address,RequestHandlerClass) if len(retr_addrs) == 0: raise RuntimeError, "no retrieval servers spezified" else: self.retr_addrs = retr_addrs self.retr_sock = [] # initializing loggin system self.log = self._server_log(logDestination) self.log.log(logging.INFO,'Initializing proxyserver') self.log.log(logging.DEBUG,'Logging system and retrieval servers list ready') # initializing boolean values for request and server termination # and user authorization self.notBye = True # true -> web interface didn't quit yet self.notQuit = True # true -> proxy and retrieval servers still running self.notProxyquit = True # false -> proxy going down, retrieval servers will remain online self.auth = False self.sendErrorsFrom = [] # a list which will contain retrieval servers which crashed or aren't reachable anymore self.results = 0 # given results per retrieval server self.log.log(logging.INFO,"Proxyserver running on "+str(server_address)) def sendToRetrievers(self,cmd,upperBound=None): if upperBound != None: if upperBound < 0: raise RuntimeError, "no retrieval servers specified for sending, Proxyserver: method sendToRetrievers: upperBound "+str(upperBound) relevantRetr = zip(self.retr_sock,range(upperBound)) for sock,idx in relevantRetr: try: sock.sendcmd(cmd) self.log.log(logging.getLevelName("SEND "+str(self.retr_addrs[idx])),cmd) except: # iff no socket error occured until now name,port = self.retr_addrs[idx] if self.sendErrorsFrom == []: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str((name,port))+" did break" ) raise RuntimeError, "socket connection to retrieval server "+str((name,port))+" did break" elif str(name) in self.sendErrorsFrom: pass else: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str((name,port))+" did break") else: for sock,addr in zip(self.retr_sock,self.retr_addrs): try: sock.sendcmd(cmd) self.log.log(logging.getLevelName("SEND "+str(addr)),cmd) except: name,port = addr self.log.log(logging.INFO,"sendErrorsFrom: "+str(self.sendErrorsFrom)) if self.sendErrorsFrom == []: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str(addr)+" did break") raise RuntimeError, "socket connection to retrieval server "+str(addr)+" did break" elif str(name) in self.sendErrorsFrom: self.log.log(logging.DEBUG,"error in socket communication for retrieval server "+str(name)+" already known") else: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str(addr)+" did break") def getFromRetrievers(self): answer = [] for sock,addr in zip(self.retr_sock,self.retr_addrs): try: ans = sock.getline() except: self.log.log(logging.CRITICAL,"retrieval server "+str(addr)+" doesn't respond") name,port = addr self.sendErrorsFrom.append(str(name)) raise RuntimeError, "retrieval server "+str(addr)+" didn't respond in method getFromRetrievers" answer.append(ans) self.log.log(logging.getLevelName("RECV "+str(addr)),ans) return answer def handle_request(self): """Handle one request in terms of one connection possibly containing several actions, possibly blocking.""" errorCode = 0 try: request, client_address = self.get_request() self.log.log(logging.INFO,"client "+str(client_address)+" connected") except: self.notQuit = False self.log.log(logging.ERROR,"an error occured during client's connection attempt") self.log.log(logging.ERROR,"maybe the socket/pipe did break or there are network problems") self.log.log(logging.ERROR,"proxyserver shutting down (retrieval server system may still be online)") try: request.close() self.socket.close() except: pass errorCode = 1 return errorCode else: try: for serverNum in range(len(self.retr_addrs)): serverNum_sock = FIRESocket() self.retr_sock.append(serverNum_sock) except: self.notQuit = False self.log.log(logging.ERROR,"couldn't create necessary network sockets for communication with retrieval servers") self.log.log(logging.ERROR,"proxyserver shutting down (retrieval server system may still be online)") request.close() self.socket.close() while self.retr_sock != []: firesock = self.retr_sock.pop(0) firesock.sock.close() del firesock errorCode = 2 return errorCode else: self.log.log(logging.DEBUG,"network sockets for communication with retrieval servers created") if self.verify_request(request, client_address): try: self.process_request(request, client_address) return errorCode except RuntimeError, msg: self.handle_error(request,msg) errorCode = 3 return errorCode except: self.handle_error(request,"an error involving networksockets or an unknown error occured") errorCode = 3 return errorCode def process_request(self , request, client_addr): self.finish_request(request, client_addr) try: self.close_request(request) except: pass def close_request(self, client): client.close() self.log.log(logging.INFO,"client disconnected") self.auth = False # the network sockets designated for communication with retrieval servers # will only be closed if bye, quit or an error are encountered if self.notQuit: self.sendToRetrievers("bye") while self.retr_sock != []: firesock = self.retr_sock.pop(0) firesock.sock.close() del firesock def serve(self): self.log.log(logging.INFO,"proxy handling requests") # iff the error code is True no error occured while handling errorCode = 0 while self.notQuit and self.notProxyquit : errorCode = self.handle_request() self.log.log(logging.DEBUG,"errorCode "+str(errorCode)) if errorCode == 0: self.server_close() else: logging.shutdown() def server_close(self): # no auth necessary due to prior authentification if self.notProxyquit: self.log.log(logging.INFO,"sending shutdown signal to retrieval servers") self.sendToRetrievers("quit") self.socket.close() # closing and deleting network sockets while self.retr_sock != []: sock = self.retr_sock.pop(0) sock.sock.close() del sock if self.notProxyquit: self.log.log(logging.INFO,"proxyserver and retrieval servers stopped") else: self.log.log(logging.INFO,"proxyserver stopped, retrieval servers running") self.log.log(logging.DEBUG,"shutting logging system down") logging.shutdown() # printing the error message in to the logging file, closing connection to all retrieval servers # and shutting down def handle_error(self,request,msg): self.notQuit = False self.log.log(logging.ERROR,"an error occured while handling requests") self.log.log(logging.ERROR,"for further information view the log file") self.log.log(logging.DEBUG,msg) self.log.log(logging.ERROR,"shutting proxyserver down") request.close() self.sendToRetrievers("bye") self.socket.close() while self.retr_sock != []: sock = self.retr_sock.pop(0) sock.sock.close() del sock del self.retr_sock # logging.shutdown() # Note that _server_log will always return a logger which will always log global statements to stdout # and if intended will log everything to a file depending on the message's importance level def _server_log(self,logDestination): if logDestination == None: location = None else: # exists is only needed if in future an other file logger should be used # that doesn't check fileexistance location, exists = self._logFilehandling(logDestination) # Setting up the logging System # The root logger shall log to stdout, all debug msg will be found in the files # Adding new message levels to the logging system # DEBUG (10) and NOTSET (0) needn't to be altered logging.addLevelName(1020,"CRITICAL") logging.addLevelName(1010,"ERROR") logging.addLevelName(1005,"WARNING") logging.addLevelName(1000,"INFO") logging.addLevelName(11,"RECV (Web/Bash)") logging.addLevelName(12,"SEND (Web/Bash)") logging.INFO = 1000 logging.ERROR = 1010 logging.CRITICAL = 1020 logging.WARNING = 1005 # so the levels 13 up to 999 are free for retrieval servers # because every server needs two numbers this logging system is capable of 493 retrieval servers # now levels for the retrieval servers are added # they are formated as SEND/RECV (IP-Address/Name) level = 13 for addrs in self.retr_addrs: logging.addLevelName(level,"SEND "+str(addrs)) logging.addLevelName(level+1,"RECV "+str(addrs)) level += 2 # now configurating the root logger which will log only to stdout sys.stdout = sys.stderr root = logging.getLogger('') root.setLevel(logging.DEBUG) console = logging.StreamHandler(sys.stdout) console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)-10s %(message)s','%a, %d-%m-%Y %H:%M:%S') console.setFormatter(formatter) root.addHandler(console) # setting up the main file logger if location != None: # when = 'midnight' # filesPerDay = 1 # backUpCount = 7 # file = TimedRotatingFileHandler(location,when,filesPerDay,backUpCount) if exists: file = logging.FileHandler(location,'a') else: file = logging.FileHandler(location,'w') file.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(levelname)-6s %(message)s','%a, %d-%m-%Y %H:%M:%S') file.setFormatter(formatter) root.addHandler(file) return root def _logFilehandling(self,logDestination): if logDestination == "default": cwd = os.getcwd() # determinating whether mac, unix/linux or windows if os.name in ["mac","nt","posix"]: if os.name == "nt": # windows os osPathTag = "\\" else: # unix/linux os or macintosch osPathTag = "/" try: # checking whether dir exists location = cwd+osPathTag+"fireproxylogs" exist = os.path.isdir(location) if not exist: os.mkdir(location) location += osPathTag+"proxylog" del exist del osPathTag except: raise RuntimeError, "error initalizing logging system (default logging location)" else: raise RuntimeError, "OS not supported for logging" del cwd # iff the user specified a storing location # outer if-clause else: # if only a directory is given (logDestination must be terminated by the os's # path separator (e.g / on linux \ on windows os)) default logfile name will be used head,tail = os.path.split(logDestination) osType = os.name if osType in ["mac","posix"]: osPathTag = "/" elif osType == "nt": osPathTag = "\\" else: raise RuntimeError, "OS not supported for logging" # checking whether a path name is given if head != "": # checking whether the user set all path separators' right head = os.path.normcase(head) head = os.path.normpath(head) # figuring out whether the supplied directories exist and # if not which have to be created if not os.path.isdir(head): dirToCreate = [head] newHead, newTail = os.path.split(head) while newTail != "" and (not os.path.isdir(newHead)): dirToCreate.append(newHead) newHead, newTail = os.path.split(newHead) while dirToCreate != []: os.mkdir(dirToCreate.pop()) del newHead del newTail # path is valid now checking if a filename was supplied if tail != "": location = logDestination else: location = logDestination+osPathTag+"proxylog" del dirToCreate # no path given by the user # tail must be != "" in this case otherwise it would be the default case else: # assuming current workdirectory was intended cwd = os.getcwd() location = cwd+osPathTag+tail del osPathTag del osType del head del tail # Outer If Clause ends here # testing if the file exist or not exists = True try: file = open(location,'r+') except IOError: exists = False else: file.close() return (location,exists) # Overidden to be useless, because this proxy shall quit when all retrievers quit def serve_forever(self): pass class FIREProxyHandler(StreamRequestHandler): def __init__(self, request, client_addr, server): StreamRequestHandler.__init__(self,request, client_addr, server) def sendToWeb(self,msg): self.wfile.write(msg+"\r\n") self.server.log.log(logging.getLevelName("SEND (Web/Bash)"),msg) def _validateSettings(self,settings): self.server.log.log(logging.DEBUG,"valSet Argu:"+repr(settings)) leng = len(settings) self.server.log.log(logging.DEBUG,"len: "+repr(leng)) if leng: if settings[0][0] != "filelist": retur = (False,"Settingsstream starts with wrong keyword") else: retur = (True, "") if leng > 1: lenSingle = map(lambda single: len(single),settings) boolList = map(lambda single: single == lenSingle[0],lenSingle) if not (reduce(lambda fst,snd: fst == snd,boolList)): retur = (False,"At least one retrieval server didn't send complete settings") # Fine all retrieval servers did send there complete settings # or all made the same mistake :D lenSetting = lenSingle[0] # deleting helper variables del boolList # checking rest for idx in range(lenSetting): if (idx != 1): for jdx in range(leng): if (settings[0][idx] != settings[jdx][idx]): # settings differ and singaling it return (False,"settings of servers "+str(0)+" and "+str(jdx)+" differ in "+ settings[0][idx]+" "+settings[jdx][idx]) else: retur = (True,"") return retur else: return (False,"no info information at all received") def setup(self): StreamRequestHandler.setup(self) error = False try: for retr, addr in zip(self.server.retr_sock,self.server.retr_addrs): name, port = addr try: retr.connect(name,port) self.server.log.log(logging.DEBUG,"connection to retrival server "+str(addr)+" established") except: # sending error message to web frontend self.sendToWeb("failure "+str(name)+" down") self.server.sendErrorsFrom.append(str(name)) # closing error = True self.server.log.log(logging.CRITICAL,"retrieval server "+str(addr)+" not reachable") except: pass else: if error: self.finish() raise RuntimeError, "some of the retrieval servers arent't reachable via network" else: self.server.notBye = True # signal: connection to retrieval servers established # currently unix specific linefeed self.server.log.log(logging.INFO,"connection to retrieval server system established") def handle(self): retrieveAndMetaCommands = ["retrieve","expand","retrieveandsaveranks","metaretrieve","metaexpand","textretrieve","textexpand"] # handling actions until "bye", "quit" or doomsday while self.server.notBye and self.server.notQuit: webMsg = self.rfile.readline() self.server.log.log(logging.DEBUG,webMsg) webMsg = re.sub("[\r\n\t\v\f]","",webMsg) self.server.log.log(logging.getLevelName("RECV (Web/Bash)"),webMsg) webKeyS = string.split(webMsg) keyWord = webKeyS.pop(0) # grabbing the very first element if keyWord == "info": self.server.sendToRetrievers("info") answer = self.server.getFromRetrievers() # convert list of single strings in usable format # e.g ["hello world","how do you do?"] becomes # [['hello','world'],['how','do','you','do?']] settings = map(lambda strin: string.split(strin),answer) bool, comment = self._validateSettings(settings) if bool: sum = 0 # summing up total databank size for idx in range(len(settings)): sum += int(settings[idx][1]) settings[0][1] = sum self.server.results = int(settings[0][3]) self.sendToWeb(re.sub("[[,'\]]","",str(settings[0]))) # deleting helper variables del bool del answer del comment del settings else: self.finish() raise RuntimeError, "handle():"+comment elif keyWord == "password": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) bool = True idx = 0 while bool and idx < len(answer): if tokens[idx][0] != "ok": bool = False idx += 1 if not bool: self.sendToWeb(answer[idx-1]) self.server.auth = False else: self.sendToWeb("ok") self.server.auth = True # deleting helper variables del answer del tokens del idx del bool elif keyWord == "bye": self.server.notBye = False elif keyWord == "quit": self.server.notBye = False if self.server.auth: self.server.notQuit = False else: self.server.sendToRetrievers("bye") elif keyWord in retrieveAndMetaCommands: self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() self.server.log.log(logging.DEBUG,"answer(handle()): "+repr(answer)) # converting retrieval servers' answers from strings to list of # strings like above and afterwards merging all such lists into # one if keyWord in ["metaretrieve","metaexpand","textretrieve","textexpand"]: listed = map(lambda string: re.split("[ :]",string),answer) else: listed = map(lambda strin: string.split(strin),answer) listed = reduce(lambda fst,snd: fst+snd,listed) if "nometainformation" in listed: self.sendToWeb("nometainformation") elif "notextinformation" in listed: self.sendToWeb("notextinformation") elif "" in listed: self.server.log.log(logging.INFO,"at least one retrival server answered with an empty string") self.server.log.log(logging.ERROR,"retrival aborted") elif not self.server.results == 0: # for sorting purposes changing data structure to a list of tupels # consistent of distance as a float and filename as a string toSort = [(float(listed[i+1]),listed[i]) for i in range(0,len(listed),2)] toSort.sort() toSort.reverse() retrievalString = "" for tup in toSort[:self.server.results]: dist, name = tup if keyWord in ["metaretrieve","metaexpand","textretrieve","textexpand"]: retrievalString += name+":"+str(dist) else: retrievalString += name+" "+str(dist) retrievalString += " " # removing trailing blank retrievalString = re.sub(" $","",retrievalString) self.sendToWeb(retrievalString) #deleting helper variables del toSort del retrievalString else: self.server.log.log(logging.INFO,"Proxyserver assumes that settings for results equals 0") self.server.log.log(logging.INFO,"Please use setresults to set results to an usefull value") self.server.log.log(logging.DEBUG,"possible mismath between retrieval servers settings and proxyserver") self.server.log.log(logging.ERROR,"retrieval aborted") # deleting helper variables del answer del listed elif keyWord == "help": self.server.sendToRetrievers(webMsg,1) answer = self.server.retr_sock[0].getline() ans = string.split(answer) try: ans.remove("filelist") except: pass answer = "proxy only: quitproxy ||normal fire commands: " for cmd in ans: answer += cmd answer += " " answer += "||not supported in proxy mode: filelist" self.sendToWeb(answer) del answer elif keyWord == "savedistances": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() fst = answer[0] bool = True for name in answer: if name != fst: bool = False if not bool: self.finish() raise RuntimeError,"distance filenames differ" self.sendToWeb(fst) del answer del bool del fst elif keyWord == "random": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) tokenList = reduce(lambda fst,snd:fst+snd,tokens) # choosing randomly images from all random images # because every retrieval server only accesses an unique database # subset randomImg = random.sample(tokenList,self.server.results) self.sendToWeb(re.sub("[[',\]]","",str(randomImg))) # deleting helper variables del answer del tokens del tokenList del randomImg elif keyWord == "saverelevances": self.server.sendToRetrievers(webMsg) elif keyWord in ["setscoring","setresults","setextensions","setdist","setweight"]: self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) keyToken = re.sub("set","",keyWord) # checking if all retrieval servers accepted new settings # first checking keyword boolList = map(lambda list: list[0] == keyToken,tokens) boolAll = reduce(lambda fst,snd:fst == snd,boolList) # checking iff snd argument must be checked # in case it will be "=" testing is omitted if keyToken in ["weight","dist"]: sndArg = tokens[0][1] boolList = map(lambda list: list[1] == sndArg,tokens) boolSnd = reduce(lambda fst,snd: fst == snd,boolList) boolAll = boolAll and boolSnd del boolSnd # checking third argument trdArg = tokens[0][2] boolList = map(lambda list: list[2] == trdArg,tokens) boolTrd = reduce(lambda fst,snd:fst == snd,boolList) boolAll = boolAll and boolTrd if boolAll: self.sendToWeb(answer[0]) if keyToken == "results" and tokens[0][0] != "Invalid": self.server.results = int(tokens[0][2]) else: self.server.sendToRetrievers(keyWord,1) alterMsg = self.server.retr_sock[0].getline() self.sendToWeb(alterMsg) del alterMsg del boolAll del boolTrd del boolList del answer del tokens elif keyWord == "listfiles": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() result = "" for idx in range(len(answer)): result += answer[idx] result += " " # deleting trailing blank result = re.sub(" $","",result) self.sendToWeb(result) del answer del result elif keyWord == "class": self.server.sendToRetrievers(webMsg) self.server.log.log(logging.INFO,webMsg+" send") answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) tokens = reduce(lambda fst,snd: fst+snd,tokens) # since retrieval servers will only return a single value # it is only neccessary to destinguish the three possible modes of the class command # for error handling # do all retrieval servers have classes or don't they if "yes" in tokens: for item in tokens: if "yes" != item: self.finish() raise RuntimeError, "not all retrieval servers do have classes" self.sendToWeb("yes") elif "no" in tokens: for item in tokens: if "no" != item: self.finish() raise RuntimeError, "not all retrieval servers don't have classes" self.sendToWeb("no") else: try: intList = [] for item in tokens: intItem = int(item) if intItem >= 0: intList.append(intItem) except: self.finish() raise RuntimeError, "neiter yes/no nor numbers were returned for classes" else: boolList = map(lambda it: intList[0]==it,intList) booL = reduce(lambda fst, snd: fst and snd,boolList) if booL: self.sendToWeb(str(intList[0])) else: self.finish() raise RuntimeError, "retrieval servers classes differ" del boolList del booL del tokens del answer elif keyWord == "metafeatureinfo": self.server.sendToRetrievers(webMsg) self.server.log.log(logging.INFO,webMsg+" send") answer = self.server.getFromRetrievers() answer = map(lambda string: re.sub(" $","",string),answer) returnstring = "" for strings in answer: returnstring += strings returnstring += " " self.sendToWeb(re.sub(" $","",returnstring)) del answer del returnstring # Note that the commands filelist is dumped on purpose # because every retrieval server accesses it's own databade subset # The interactor command is dumped too. elif keyWord in ["filelist","interactor"]: self.sendToWeb(keyWord+" is not avaible since fireproxy is in use") elif keyWord == "quitproxy": self.server.notBye = False self.server.notProxyquit = False else: self.sendToWeb("Unknown command: "+webMsg) del retrieveAndMetaCommands del webKeyS del webMsg
Python
#!/usr/bin/python from string import split, lower, strip from random import shuffle import sys import os from os.path import join, getsize ARCH=os.environ["ARCH"] # returns the string after a certain option string def getStringAfter(name, array, default): for i in range(len(array)): if array[i] == name: if (len(array) == i+1): return default else: return array[i+1] return default def usage(commandline): print "note: before you use this program make \"make all\" in the firedirectory. " print commandline[0], "(-np|-npfromdb|-ndb|-ndbfromp|-showf|-e|-h) [options]" print print "mandatory options (choose exactly one of them):" print " -h shows this help" print " -showf show all possible features that can be extracted" print " -e extracts features. options: -limages -ldb -ld -selectf " print " -p -db -d -c -f -q -n" print " -np creates a new purefiles file using the filenames of the " print " files in the directory. options: -d -p" print " -npfromdb creates a new purefiles file from the data of the dbfile." print " options: -d -db -p" print " -ndb creates a new database file using the filenames of the " print " files in the directory. options: -d -db" print " -ndbfromp creates a new database file from the data of the purefiles " print " file. options: -d -p -db" print print "options:" print " -d dir directory of where the files are. default: ." print " -p path path of an [existing] purefiles file. default: purefiles" print " -db path path of an [existing] database file. default: list" print " -c path configfile that shall be used. " print " default:", os.path.dirname(sys.argv[0]) + "/features.conf" print " -f dir directory where fire resides. " print " default:", os.path.dirname(sys.argv[0]) + "../../bin/"+ARCH+"/" print " -q (day|week)" print " put all jobs into the queuingsystem. default: no queuing" print " -n name of the jobs in the queue. default: extractor" print " -selectf feature1 [feature2 [... [featureN]]" print " extracts only feature1 ... featureN of the config file" print " -v verbose" print " -limages image1 [image2 [... [imageN]]" print " extracts features of image1 ... imageN only" print " -ldb extracts the images from the dbfile" print " (hint: it is smarter to create a db file first, using" print " -ndb or -ndbfromp)" print " -ld extracts the images of the directory" print " (hint: it is smarter to create a purefiles file first," print " using -np or -npfromdb)" class Extractor: def __init__(self): self.datadir = "." self.purefiles = "purefiles" self.dbfile = "list" self.progdir = os.path.dirname(sys.argv[0]) # path of the tool self.firedir = self.progdir + "/../../bin/"+ARCH+"/" self.config = "features.conf" self.extensionlist = ["jpg", "png", "gif", "jpeg", "tif", "tiff"] self.images = [] self.features = {} self.selectedFeatures = [] self.queue = None self.name = "extractor" # gets for the attributes def setPurefiles(self, new): self.purefiles = new def setDBFile(self, new): self.dbfile = new def setDatadir(self, new): self.datadir = new def setFiredir(self, new): self.firedir = new def setConfigfile(self, new): self.config = new def setExtensionlist(self, newl): self.extensionlist = newl def setQueue(self, new): self.queue = new def setName(self, new): self.name = new # printing def printInfo(self): print "config info of extractor" print "datadir", self.datadir print "purefiles", self.purefiles print "dbfile", self.dbfile print "progdir", self.progdir print "firedir", self.firedir print "configfile", self.config print "extensionlist", self.extensionlist # prints available features def printFeatures(self): for feature in self.features.keys(): print feature, self.features[feature] def printImages(self): if self.images == []: print "error: no images loaded." else: print "images:" for image in self.images: print image # loading # load images from the directory def loadImagesFromDir(self): print "loading images from directory." self.images = [] for root, dirs, files in os.walk(self.datadir): for file in files: if self.checkExtension(file): if (root == self.datadir): self.images.append(file) else: self.images.append(root[len(self.datadir)+1:] + "/" + file) if self.images == []: print "error: no images found." # loads images from database file # (does not consider path information of the db file yet) def loadImagesFromDB(self): print "loading images from dbfile." f = open(self.dbfile, "r") lines = f.readlines() f.close() for line in lines: if strip(split(line)[0]) == "file": self.images.append(strip(split(line)[1])) #print "file:", strip(split(line)[1]) if self.images == []: print "error: no images found." # loads features from the config file def loadFeatures(self): print "loading features file." try: f = open(self.config, "r") except IOError: print "warning: no specific config file found. I try the one in the tooldir." f = open(self.progdir + "/features.conf") lines = f.readlines() f.close() for line in lines: if line[0] == "#": #print "comment: ", line pass elif len(strip(line)) < 1: pass else: key = strip(split(line)[0]) #print "key", key feature = strip(line)[len(key)+1:] #print "feature", feature self.features[key] = feature # loads an existing purefiles list def loadImagesFromPurefiles(self): print "loading images from purefiles." self.images = [] file = open(self.purefiles, 'r') lines = file.readlines() file.close() num = len(lines) print "info: number of images =", num for line in lines: self.images.append(strip(line)) # loads images from commandline def loadImagesFromCommandline(self, argv): self.images = [] print "loading images from commandline." catch = False for command in argv: #print "command:", command if command == "-limages": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: self.images.append(command) if self.images == []: print "error: no images found" def loadSelectedFeaturesFromCommandline(self, argv): self.selectedFeatures = [] print "loading selected features from commandline." catch = False for command in argv: #print "command:", command if command == "-selectf": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: #print "added", command self.selectedFeatures.append(command) if self.selectedFeatures == []: print "error: no features found" # checking # check if image file has a correct extension def checkExtension(self, filename): extension = split(filename, ".")[-1] if lower(extension) in self.extensionlist: return True return False def pureFileExists(self): try: f = open(self.purefiles, "r") except IOError: return False else: return True # writing # writes the purefilesfile def writePurefiles(self): print "writing purefiles file." if self.images == []: print "error: cannot write a purefiles file, because image list is empty." else: f = open(self.purefiles, "w") for image in self.images: f.write(image) f.write("\n") f.close() # creates the database file def writeDBFile(self): # possible feature: dbfiles with feature directories? # possible feature: non recursive traversion print "writing dbfile." f = open(self.dbfile, "w") f.write("FIRE_filelist\n") f.write("classes no\n") f.write("descriptions no\n") f.write("featuredirectories no\n") f.write("path this\n") for file in self.images: f.write("file ") f.write(file) f.write("\n") f.close() # selection # selects features def selectFeatures(self): if self.selectedFeatures == []: print "error: there are no features to select" print "hint: maybe wrong spelling?" temp = {} for key in self.features.keys(): #print "key", key if key in self.selectedFeatures: temp[key] = self.features[key] self.features = temp # extraction # extracts all features for all images def extractFeatures(self): for key in self.features.keys(): self.extractFeature(key) # extracts one feature for all images def extractFeature(self, feature): if self.images != []: commandline = self.firedir + self.features[feature] + " --images" for image in self.images: commandline = commandline + " " + image else: if not self.pureFileExists(): print "error: purefiles file not existing" print "hint: create with -np a new file or use -limage, -ldb or -ld to load images" return False else: #self.printInfo() #print "self.features[feature]", self.features[feature] #self.printFeatures() commandline = self.firedir + self.features[feature] + " --filelist " + self.purefiles print "commandline:", commandline if self.queue == "day": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 8:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) elif self.queue == "week": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 24:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) else: os.system(commandline) if __name__ == "__main__": if "-h" in sys.argv: usage(sys.argv) else: e = Extractor() # adjusting file locations if "-p" in sys.argv: e.setPurefiles(getStringAfter("-p", sys.argv, None)) if "-db" in sys.argv: e.setDBFile(getStringAfter("-db", sys.argv, None)) if "-d" in sys.argv: e.setDatadir(getStringAfter("-d", sys.argv, None)) if "-c" in sys.argv: e.setConfigfile(getStringAfter("-c", sys.argv, None)) if "-f" in sys.argv: e.setFiredir(getStringAfter("-f", sys.argv, None)) if "-q" in sys.argv: e.setQueue(getStringAfter("-q", sys.argv, None)) if "-n" in sys.argv: e.setName(getStringAfter("-n", sys.argv, None)) ## maybe later # if "-el" in sys.argv # e.setExtensionlist(...) if "-v" in sys.argv: e.printInfo() if "-np" in sys.argv: e.loadImagesFromDir() e.writePurefiles() elif "-npfromdb" in sys.argv: e.loadImagesFromDB() e.writePurefiles() elif "-ndb" in sys.argv: e.loadImagesFromDir() e.writeDBFile() elif "-ndbfromp" in sys.argv: e.loadImagesFromPurefiles() e.writeDBFile() elif "-showf" in sys.argv: e.loadFeatures() e.printFeatures() elif "-e" in sys.argv: # loading the images (if no purefiles file is used) if "-limages" in sys.argv: e.loadImagesFromCommandline(sys.argv) if "-v" in sys.argv: e.printImages() elif "-ldb" in sys.argv: e.loadImagesFromDBFile() elif "-ld" in sys.argv: e.loadImagesFromDatadir() else: pass e.loadFeatures() if "-selectf" in sys.argv: e.loadSelectedFeaturesFromCommandline(sys.argv) e.selectFeatures() if "-v" in sys.argv: print "selected features:" e.printFeatures() e.extractFeatures() else: print "wrong usage. use -h for help."
Python
#!/usr/bin/python from string import split, lower, strip from random import shuffle import sys import os from os.path import join, getsize ARCH=os.environ["ARCH"] # returns the string after a certain option string def getStringAfter(name, array, default): for i in range(len(array)): if array[i] == name: if (len(array) == i+1): return default else: return array[i+1] return default def usage(commandline): print "note: before you use this program make \"make all\" in the firedirectory. " print commandline[0], "(-np|-npfromdb|-ndb|-ndbfromp|-showf|-e|-h) [options]" print print "mandatory options (choose exactly one of them):" print " -h shows this help" print " -showf show all possible features that can be extracted" print " -e extracts features. options: -limages -ldb -ld -selectf " print " -p -db -d -c -f -q -n" print " -np creates a new purefiles file using the filenames of the " print " files in the directory. options: -d -p" print " -npfromdb creates a new purefiles file from the data of the dbfile." print " options: -d -db -p" print " -ndb creates a new database file using the filenames of the " print " files in the directory. options: -d -db" print " -ndbfromp creates a new database file from the data of the purefiles " print " file. options: -d -p -db" print print "options:" print " -d dir directory of where the files are. default: ." print " -p path path of an [existing] purefiles file. default: purefiles" print " -db path path of an [existing] database file. default: list" print " -c path configfile that shall be used. " print " default:", os.path.dirname(sys.argv[0]) + "/features.conf" print " -f dir directory where fire resides. " print " default:", os.path.dirname(sys.argv[0]) + "../../bin/"+ARCH+"/" print " -q (day|week)" print " put all jobs into the queuingsystem. default: no queuing" print " -n name of the jobs in the queue. default: extractor" print " -selectf feature1 [feature2 [... [featureN]]" print " extracts only feature1 ... featureN of the config file" print " -v verbose" print " -limages image1 [image2 [... [imageN]]" print " extracts features of image1 ... imageN only" print " -ldb extracts the images from the dbfile" print " (hint: it is smarter to create a db file first, using" print " -ndb or -ndbfromp)" print " -ld extracts the images of the directory" print " (hint: it is smarter to create a purefiles file first," print " using -np or -npfromdb)" class Extractor: def __init__(self): self.datadir = "." self.purefiles = "purefiles" self.dbfile = "list" self.progdir = os.path.dirname(sys.argv[0]) # path of the tool self.firedir = self.progdir + "/../../bin/"+ARCH+"/" self.config = "features.conf" self.extensionlist = ["jpg", "png", "gif", "jpeg", "tif", "tiff"] self.images = [] self.features = {} self.selectedFeatures = [] self.queue = None self.name = "extractor" # gets for the attributes def setPurefiles(self, new): self.purefiles = new def setDBFile(self, new): self.dbfile = new def setDatadir(self, new): self.datadir = new def setFiredir(self, new): self.firedir = new def setConfigfile(self, new): self.config = new def setExtensionlist(self, newl): self.extensionlist = newl def setQueue(self, new): self.queue = new def setName(self, new): self.name = new # printing def printInfo(self): print "config info of extractor" print "datadir", self.datadir print "purefiles", self.purefiles print "dbfile", self.dbfile print "progdir", self.progdir print "firedir", self.firedir print "configfile", self.config print "extensionlist", self.extensionlist # prints available features def printFeatures(self): for feature in self.features.keys(): print feature, self.features[feature] def printImages(self): if self.images == []: print "error: no images loaded." else: print "images:" for image in self.images: print image # loading # load images from the directory def loadImagesFromDir(self): print "loading images from directory." self.images = [] for root, dirs, files in os.walk(self.datadir): for file in files: if self.checkExtension(file): if (root == self.datadir): self.images.append(file) else: self.images.append(root[len(self.datadir)+1:] + "/" + file) if self.images == []: print "error: no images found." # loads images from database file # (does not consider path information of the db file yet) def loadImagesFromDB(self): print "loading images from dbfile." f = open(self.dbfile, "r") lines = f.readlines() f.close() for line in lines: if strip(split(line)[0]) == "file": self.images.append(strip(split(line)[1])) #print "file:", strip(split(line)[1]) if self.images == []: print "error: no images found." # loads features from the config file def loadFeatures(self): print "loading features file." try: f = open(self.config, "r") except IOError: print "warning: no specific config file found. I try the one in the tooldir." f = open(self.progdir + "/features.conf") lines = f.readlines() f.close() for line in lines: if line[0] == "#": #print "comment: ", line pass elif len(strip(line)) < 1: pass else: key = strip(split(line)[0]) #print "key", key feature = strip(line)[len(key)+1:] #print "feature", feature self.features[key] = feature # loads an existing purefiles list def loadImagesFromPurefiles(self): print "loading images from purefiles." self.images = [] file = open(self.purefiles, 'r') lines = file.readlines() file.close() num = len(lines) print "info: number of images =", num for line in lines: self.images.append(strip(line)) # loads images from commandline def loadImagesFromCommandline(self, argv): self.images = [] print "loading images from commandline." catch = False for command in argv: #print "command:", command if command == "-limages": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: self.images.append(command) if self.images == []: print "error: no images found" def loadSelectedFeaturesFromCommandline(self, argv): self.selectedFeatures = [] print "loading selected features from commandline." catch = False for command in argv: #print "command:", command if command == "-selectf": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: #print "added", command self.selectedFeatures.append(command) if self.selectedFeatures == []: print "error: no features found" # checking # check if image file has a correct extension def checkExtension(self, filename): extension = split(filename, ".")[-1] if lower(extension) in self.extensionlist: return True return False def pureFileExists(self): try: f = open(self.purefiles, "r") except IOError: return False else: return True # writing # writes the purefilesfile def writePurefiles(self): print "writing purefiles file." if self.images == []: print "error: cannot write a purefiles file, because image list is empty." else: f = open(self.purefiles, "w") for image in self.images: f.write(image) f.write("\n") f.close() # creates the database file def writeDBFile(self): # possible feature: dbfiles with feature directories? # possible feature: non recursive traversion print "writing dbfile." f = open(self.dbfile, "w") f.write("FIRE_filelist\n") f.write("classes no\n") f.write("descriptions no\n") f.write("featuredirectories no\n") f.write("path this\n") for file in self.images: f.write("file ") f.write(file) f.write("\n") f.close() # selection # selects features def selectFeatures(self): if self.selectedFeatures == []: print "error: there are no features to select" print "hint: maybe wrong spelling?" temp = {} for key in self.features.keys(): #print "key", key if key in self.selectedFeatures: temp[key] = self.features[key] self.features = temp # extraction # extracts all features for all images def extractFeatures(self): for key in self.features.keys(): self.extractFeature(key) # extracts one feature for all images def extractFeature(self, feature): if self.images != []: commandline = self.firedir + self.features[feature] + " --images" for image in self.images: commandline = commandline + " " + image else: if not self.pureFileExists(): print "error: purefiles file not existing" print "hint: create with -np a new file or use -limage, -ldb or -ld to load images" return False else: #self.printInfo() #print "self.features[feature]", self.features[feature] #self.printFeatures() commandline = self.firedir + self.features[feature] + " --filelist " + self.purefiles print "commandline:", commandline if self.queue == "day": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 8:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) elif self.queue == "week": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 24:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) else: os.system(commandline) if __name__ == "__main__": if "-h" in sys.argv: usage(sys.argv) else: e = Extractor() # adjusting file locations if "-p" in sys.argv: e.setPurefiles(getStringAfter("-p", sys.argv, None)) if "-db" in sys.argv: e.setDBFile(getStringAfter("-db", sys.argv, None)) if "-d" in sys.argv: e.setDatadir(getStringAfter("-d", sys.argv, None)) if "-c" in sys.argv: e.setConfigfile(getStringAfter("-c", sys.argv, None)) if "-f" in sys.argv: e.setFiredir(getStringAfter("-f", sys.argv, None)) if "-q" in sys.argv: e.setQueue(getStringAfter("-q", sys.argv, None)) if "-n" in sys.argv: e.setName(getStringAfter("-n", sys.argv, None)) ## maybe later # if "-el" in sys.argv # e.setExtensionlist(...) if "-v" in sys.argv: e.printInfo() if "-np" in sys.argv: e.loadImagesFromDir() e.writePurefiles() elif "-npfromdb" in sys.argv: e.loadImagesFromDB() e.writePurefiles() elif "-ndb" in sys.argv: e.loadImagesFromDir() e.writeDBFile() elif "-ndbfromp" in sys.argv: e.loadImagesFromPurefiles() e.writeDBFile() elif "-showf" in sys.argv: e.loadFeatures() e.printFeatures() elif "-e" in sys.argv: # loading the images (if no purefiles file is used) if "-limages" in sys.argv: e.loadImagesFromCommandline(sys.argv) if "-v" in sys.argv: e.printImages() elif "-ldb" in sys.argv: e.loadImagesFromDBFile() elif "-ld" in sys.argv: e.loadImagesFromDatadir() else: pass e.loadFeatures() if "-selectf" in sys.argv: e.loadSelectedFeaturesFromCommandline(sys.argv) e.selectFeatures() if "-v" in sys.argv: print "selected features:" e.printFeatures() e.extractFeatures() else: print "wrong usage. use -h for help."
Python
#!/usr/bin/env python import sys,gzip class Feature: def __init__(self): self.posx=0 self.posy=0 self.scale=0 self.vec=[] class LocalFeatures: def __init__(self): self.winsize=0 self.dim=0 self.subsampling=0 self.padding=0 self.numberOfFeatures=0 self.varthreshold=0 self.zsize=0 self.filename="" self.imagesize=(0,0) self.features=[] self.selffilename="" def __getitem__(self,i): return self.features[i] def load(self,filename): f=gzip.GzipFile(filename) self.selffilename=filename for l in f: toks=l.split() if toks[0]=="FIRE_localfeatures": fine=True elif toks[0]=="winsize": self.winsize=int(toks[1]) elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="subsampling": self.subsampling=int(toks[1]) elif toks[0]=="padding": self.padding=int(toks[1]) elif toks[0]=="numberOfFeatures": self.numberOfFeatures=int(toks[1]) elif toks[0]=="varthreshold": self.varthreshold=float(toks[1]) elif toks[0]=="zsize": self.zsize=int(toks[1]) elif toks[0]=="filename": self.filename=toks[1] elif toks[0]=="imagesize": self.imagesize=(int(toks[1]),int(toks[2])) elif toks[0]=="features": if self.numberOfFeatures!=int(toks[1]): print "Weird... inconsistent number of Features and features expected in the file" elif toks[0]=="feature": f=Feature() toks.pop(0) f.posx=float(toks.pop(0)) f.posy=float(toks.pop(0)) f.scale=float(toks.pop(0)) f.vec=map(lambda x: float(x), toks) self.features+=[f] else: print "'%s' is an unknown keyword... ignoring and continuiing nonetheless."%(toks[0]) def save(self,filename): f=gzip.GzipFile(filename,"w") f.write("FIRE_localfeatures\n") f.write("winsize %d\ndim %d\nsubsampling %d\npadding %d\nnumberOfFeatures %d\nvarthreshold %d\nzsize %d\nfilename %s\nimagesize %d %d\nfeatures %d\n" % (self.winsize,self.dim,self.subsampling,self.padding,self.numberOfFeatures,self.varthreshold,self.zsize,self.filename,self.imagesize[0],self.imagesize[1],len(self.features))) for lf in self.features: f.write("feature %d %d %d " % (lf.posx,lf.posy,lf.scale)) for v in lf.vec: f.write(str(v)+" ") f.write("\n") f.close()
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class HistogramFeature: def __init__(self): self.steps=[] self.bins=[] self.min=[] self.max=[] self.stepsize=[] self.dim=0 self.counter=0 self.filename="" self.data=[] def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_histogram" print >>f,"# created with histogramfeature.py" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps"," ".join(map(lambda x: str(x),self.steps)) print >>f,"min"," ".join(map(lambda x: str(x), self.min)) print >>f,"max"," ".join(map(lambda x: str(x), self.max)) print >>f,"data"," ".join(map(lambda x: str(x), self.data)) f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_histogram": fine=True elif toks[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="data": self.bins=map(lambda x: int(x),toks[1:]) try: self.data=map(lambda x: float(x)/float(self.counter), self.bins) except: print "Error reading file:", filename,"probably division by zero, continuing anyway." else: print "Unparsed line: '"+line+"'."
Python
#!/usr/bin/python import sys #this script merges fire distance files. # # as command line parameters, arbitrary many distance files are given and # the merged distance file is printed. infiles=[] line=[] for i in sys.argv[1:]: infiles.append(open(i,"r")) line.append("") line[0]=infiles[0].readline() count=0 while(line[0]): for i in range(1,len(infiles)): line[i]=infiles[i].readline() if line[0].startswith("nofdistances"): nDist=0 nImg=0 for l in line: toks=l.split() nDist+=int(toks[2]) nImg=int(toks[1]) print "nofdistances",nImg,nDist elif not line[0].startswith("#"): print count, for l in line: toks=l.split() for i in range(1,len(toks)): print float(toks[i]), print count+=1 line[0]=infiles[0].readline()
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer querylist=filelist.FileList() filelist=filelist.FileList() filelist.load(sys.argv[1]) querylist.load(sys.argv[2]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in querylist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: if len(sys.argv) != 4: print """USAGE: querylistwqueryexpansion.py <querylist> <server> <port> """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." files=ql.readlines() ql.close() s.sendcmd("setresults 10") s.sendcmd("setextensions 2") for file in files: file=re.sub('\n','',file) cmd="retrieveandsaveranks 1030 "+file+".ranks "+file s.sendcmd(cmd) res=s.getline() print res s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback,numarray import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-f": database=sys.argv.pop(0) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-l1o": l1o=True elif argv=="-x": quit=True else: print "Unknown option:",argv print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o if database=="" or querybase=="" and not l1o: print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o sys.stdout.flush() f=filelist.FileList() f.load(database) q=filelist.FileList() if not l1o: q.load(querybase) else: q=f if not f.classes: print "Need classes in database file" sys.exit(10) if not l1o and not q.classes: print "Need classes in querybase file" sys.exit(10) s=firesocket.FIRESocket() s.connect(server,port) try: s.sendcmd("info") res=s.getline() status=re.split(" ",res) keyword=status.pop(0) dbSize=int(status.pop(0)) if dbSize!=len(f.files): print "database in retriever and database loaded are of different size:", dbSize,"!=",len(f.files) s.sendcmd("bye") time.sleep(1) sys.exit(10) print "database has",dbSize,"images." if not l1o: s.sendcmd("setresults 1"); res=s.getline() else: s.sendcmd("setresults 2"); res=s.getline() classified=0; errors=0; correct=0 no_classes=0 for qf in q.files: if qf[1]>no_classes: no_classes=qf[1] for df in f.files: if df[1]>no_classes: no_classes=df[1] no_classes+=1 print no_classes,"classes." confusionmatrix=numarray.zeros((no_classes,no_classes),numarray.Int) counter=0 for qf in q.files: counter+=1 qname=qf[0] qcls=qf[1] s.sendcmd("retrieve "+qname) res=s.getline() res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) if not l1o: if len(results)!=2: print "expected 2 tokens, got",len(results) sys.exit(10) else: if len(results)!=4: print "expected 4 tokens, got",len(results) sys.exit(10) results.pop(0) results.pop(0) returnedimage=results.pop(0) score=float(results.pop(0)) for df in f.files: if not l1o: if df[0]==returnedimage: dcls=df[1] break else: if df[0]==returnedimage and df[0]!=qname: dcls=df[1] break classified+=1 if dcls==qcls: correct+=1 else: errors+=1 confusionmatrix[dcls][qcls]+=1 print "Query "+str(counter)+"/"+str(len(q.files))+":",qname,"("+str(qcls)+") NN:",returnedimage,"("+str(dcls)+")","ER:",float(errors)/float(classified)*100 sys.stdout.flush() print "RESULT: ER:",float(errors)/float(classified)*100 print confusionmatrix time.sleep(1) if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) useX="-x" in sys.argv verbose="-v" in sys.argv try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." fileprefix="" if len(sys.argv)>4: if sys.argv[4]!="-q" and sys.argv[4]!="-x" and sys.argv[4]!="-v": fileprefix=sys.argv[4] lines=ql.readlines() # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); ql.close() classified=0 ###query images and evaluate results for line in lines: line=re.sub('\n','',line) relevant=re.split(" ",line) query=fileprefix+relevant[0] # this is the name of the query image relevant=relevant[1:] # this are the names of the images relevant to the query image cmd="retrieve +"+query s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimage=re.sub(fileprefix,"",returnedimage) returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] if verbose: print "results:",returnedimages[0],"->0", sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize param["useX"] = useX param["verbose"] = verbose def calculate(param): data = param["data"] dbSize = param["dbSize"] useX = param["useX"] verbose = param["verbose"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] if useX: g=Gnuplot.Gnuplot() g.title('PR graph') g('set data style linespoints') g('set xrange [0.0:1.0]') g('set yrange [0.0:1.0]') data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 if verbose: print returnedimages[Ri],"->",Ri, print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] if useX: g.plot(Gnuplot.Data(PRgraph,title="PRgraph current query"),Gnuplot.Data(tmpAPRgraph,title="PRgraph average")) print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [<fileprefix>] [-q] [-x] -q: quit the server after finished eval -x: show PR graph after each query on X display -v: verbose <fileprefix> should not be necessary """ else: param = {} retrieveData(param) calculate(param)
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: host=sys.argv[1] if len(sys.argv) >=3: port=int(sys.argv[2]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." s.sendcmd("listfiles") fileline=s.getline() files=string.split(fileline," ") s.sendcmd("setresults 2") s.getline() classified=0 correct=0 error=0 for file in files: if len(file)>0: cmd="retrieve +"+file s.sendcmd(cmd) res=s.getline() parts=string.split(res," ") result=parts[2] print res #get classes s.sendcmd("class "+file) qclass=s.getline() s.sendcmd("class "+result) rclass=s.getline() qc=int(qclass) rc=int(rclass) if(rc==qc): correct=correct+1 else: error=error+1 classified=classified+1 er=float(error)/float(classified)*100.0 print file+" wrong="+str(error)+" correct="+str(correct)+" classified="+str(classified)+" ER="+str(er) s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer filelist=filelist.FileList() filelist.load(sys.argv[1]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in filelist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class SparseHistogramFeature: def __init__(self): self.bins={} self.data={} self.steps=[] self.stepSize=[] self.min=[] self.max=[] self.dim=0 self.numberofBins=0 self.counter=0 self.filename="" def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_sparse_histogram" print >>f,"# sparse histogram file for FireV2" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps",reduce(lambda x,y: str(x)+" "+str(y),self.steps) print >>f,"min",reduce(lambda x,y: str(x)+" "+str(y),self.min) print >>f,"max",reduce(lambda x,y: str(x)+" "+str(y),self.max) print >>f,"bins",len(self.bins) for i in self.bins: print >>f,"data",i,self.bins[i] f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_sparse_histogram": fine=True elif line[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="bins": self.numberofBins=int(toks[1]) elif toks[0]=="data": self.bins[toks[1]]=int(toks[2]) self.data[toks[1]]=float(toks[2])/float(self.counter) else: print "Unparsed line: '"+line+"'."
Python
#!/usr/bin/python import sys, socket, re, os, string, time sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist #----------------------------------------------------------------- s=firesocket.FIRESocket() try: if len(sys.argv) < 5: print """USAGE: makedistfiles.py <querylist> <server> <port> <suffix> [-q] """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) suffix=sys.argv[4] try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." lines=ql.readlines() lines=map(lambda line: re.sub("\n","",line), lines) ql.close() i=0 for line in lines: print i,"/",len(lines) i+=1 tokens=re.split(" ",line) file=tokens[0] cmd="savedistances "+file+" "+file+"."+suffix print "SENDING: ",cmd s.sendcmd(cmd) res=s.getline() print res sys.stdout.flush() sys.stdout.flush() if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); classified=0 ###query images and evaluate results for line in ql: [query,relevant]=line.split('#') relevant=relevant.strip() query=query.strip() cmd="retrieve "+query relevant=relevant.split() print "SEND:'"+cmd+"'." s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize def calculate(param): data = param["data"] dbSize = param["dbSize"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [-q] -q: quit the server after finished eval """ else: param = {} # do the queries retrieveData(param) # querying finished, now evaluated the gathered data calculate(param)
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback #sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False start=-1 stop=-1 while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-x": quit=True elif argv=="-S": suffix=sys.argv.pop(0) elif argv=="-start": start=int(sys.argv.pop(0)) elif argv=="-stop": stop=int(sys.argv.pop(0)) else: print "Unknown option:",argv print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist, -1 for full database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"querybase=",querybase if querybase=="": print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist -x exit after having finished """ sys.exit(10) sys.stdout.flush() q=filelist.FileList() q.load(querybase) s=firesocket.FIRESocket() s.connect(server,port) if start==-1: start=0 if stop==-1: stop=len(q.files) try: for qf in q.files[start:stop]: cmd="savedistances "+qf[0]+" "+qf[0]+"."+suffix s.sendcmd(cmd) res=s.getline() print res if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/python import sys,re import filelist filelist=filelist.FileList() filelist.load(sys.argv[1]) for i in filelist: cls=i[1] fname=i[0] print fname, for j in filelist: if j[1]==cls and j[0]!=fname: print j[0], print #print filelist
Python
#!/usr/bin/python import sys,re,filelist if len(sys.argv)<3: print """USAGE filelistquery2querylist.py <querylist> <dblist>""" sys.exit(5) qlist=filelist.FileList() qlist.load(sys.argv[1]) dblist=filelist.FileList() dblist.load(sys.argv[2]) for i in qlist: cls=i[1] fname=i[0] print fname, for j in dblist: if j[1]==cls: print j[0], print
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) useX="-x" in sys.argv verbose="-v" in sys.argv try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." fileprefix="" if len(sys.argv)>4: if sys.argv[4]!="-q" and sys.argv[4]!="-x" and sys.argv[4]!="-v": fileprefix=sys.argv[4] lines=ql.readlines() # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); ql.close() classified=0 ###query images and evaluate results for line in lines: line=re.sub('\n','',line) relevant=re.split(" ",line) query=fileprefix+relevant[0] # this is the name of the query image relevant=relevant[1:] # this are the names of the images relevant to the query image cmd="retrieve +"+query s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimage=re.sub(fileprefix,"",returnedimage) returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] if verbose: print "results:",returnedimages[0],"->0", sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize param["useX"] = useX param["verbose"] = verbose def calculate(param): data = param["data"] dbSize = param["dbSize"] useX = param["useX"] verbose = param["verbose"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] if useX: g=Gnuplot.Gnuplot() g.title('PR graph') g('set data style linespoints') g('set xrange [0.0:1.0]') g('set yrange [0.0:1.0]') data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 if verbose: print returnedimages[Ri],"->",Ri, print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] if useX: g.plot(Gnuplot.Data(PRgraph,title="PRgraph current query"),Gnuplot.Data(tmpAPRgraph,title="PRgraph average")) print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [<fileprefix>] [-q] [-x] -q: quit the server after finished eval -x: show PR graph after each query on X display -v: verbose <fileprefix> should not be necessary """ else: param = {} retrieveData(param) calculate(param)
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: host=sys.argv[1] if len(sys.argv) >=3: port=int(sys.argv[2]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." s.sendcmd("listfiles") fileline=s.getline() files=string.split(fileline," ") s.sendcmd("setresults 2") s.getline() classified=0 correct=0 error=0 for file in files: if len(file)>0: cmd="retrieve +"+file s.sendcmd(cmd) res=s.getline() parts=string.split(res," ") result=parts[2] print res #get classes s.sendcmd("class "+file) qclass=s.getline() s.sendcmd("class "+result) rclass=s.getline() qc=int(qclass) rc=int(rclass) if(rc==qc): correct=correct+1 else: error=error+1 classified=classified+1 er=float(error)/float(classified)*100.0 print file+" wrong="+str(error)+" correct="+str(correct)+" classified="+str(classified)+" ER="+str(er) s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: if len(sys.argv) != 4: print """USAGE: querylistwqueryexpansion.py <querylist> <server> <port> """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." files=ql.readlines() ql.close() s.sendcmd("setresults 10") s.sendcmd("setextensions 2") for file in files: file=re.sub('\n','',file) cmd="retrieveandsaveranks 1030 "+file+".ranks "+file s.sendcmd(cmd) res=s.getline() print res s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys,re,filelist if len(sys.argv)<3: print """USAGE filelistquery2querylist.py <querylist> <dblist>""" sys.exit(5) qlist=filelist.FileList() qlist.load(sys.argv[1]) dblist=filelist.FileList() dblist.load(sys.argv[2]) for i in qlist: cls=i[1] fname=i[0] print fname, for j in dblist: if j[1]==cls: print j[0], print
Python
import socket, os, sys,re # ---------------------------------------------------------------------- # socket implementation for comunication with the server system # running on any computer which is reachable via network sockets # here we need mainly the functions # * connect # * sendcmd # * getline # * close # for the communication # ---------------------------------------------------------------------- class FIRESocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock #self.sock.settimeout(10.0) def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): #print "PUT:",msg; sys.stdout.flush() totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line #print "GOTR:",result; sys.stdout.flush() return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk!= '\r' and chunk != '\n': msg=msg+chunk msg=re.sub("[ ]$","",msg) #print "GOTL:",msg; sys.stdout.flush() return msg def flush(self): chunk=self.sock.recv(5000) return
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer querylist=filelist.FileList() filelist=filelist.FileList() filelist.load(sys.argv[1]) querylist.load(sys.argv[2]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in querylist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback #sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False start=-1 stop=-1 while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-x": quit=True elif argv=="-S": suffix=sys.argv.pop(0) elif argv=="-start": start=int(sys.argv.pop(0)) elif argv=="-stop": stop=int(sys.argv.pop(0)) else: print "Unknown option:",argv print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist, -1 for full database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"querybase=",querybase if querybase=="": print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist -x exit after having finished """ sys.exit(10) sys.stdout.flush() q=filelist.FileList() q.load(querybase) s=firesocket.FIRESocket() s.connect(server,port) if start==-1: start=0 if stop==-1: stop=len(q.files) try: for qf in q.files[start:stop]: cmd="savedistances "+qf[0]+" "+qf[0]+"."+suffix s.sendcmd(cmd) res=s.getline() print res if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class HistogramFeature: def __init__(self): self.steps=[] self.bins=[] self.min=[] self.max=[] self.stepsize=[] self.dim=0 self.counter=0 self.filename="" self.data=[] def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_histogram" print >>f,"# created with histogramfeature.py" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps"," ".join(map(lambda x: str(x),self.steps)) print >>f,"min"," ".join(map(lambda x: str(x), self.min)) print >>f,"max"," ".join(map(lambda x: str(x), self.max)) print >>f,"data"," ".join(map(lambda x: str(x), self.data)) f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_histogram": fine=True elif toks[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="data": self.bins=map(lambda x: int(x),toks[1:]) try: self.data=map(lambda x: float(x)/float(self.counter), self.bins) except: print "Error reading file:", filename,"probably division by zero, continuing anyway." else: print "Unparsed line: '"+line+"'."
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); classified=0 ###query images and evaluate results for line in ql: [query,relevant]=line.split('#') relevant=relevant.strip() query=query.strip() cmd="retrieve "+query relevant=relevant.split() print "SEND:'"+cmd+"'." s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize def calculate(param): data = param["data"] dbSize = param["dbSize"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [-q] -q: quit the server after finished eval """ else: param = {} # do the queries retrieveData(param) # querying finished, now evaluated the gathered data calculate(param)
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback,numarray import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-f": database=sys.argv.pop(0) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-l1o": l1o=True elif argv=="-x": quit=True else: print "Unknown option:",argv print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o if database=="" or querybase=="" and not l1o: print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o sys.stdout.flush() f=filelist.FileList() f.load(database) q=filelist.FileList() if not l1o: q.load(querybase) else: q=f if not f.classes: print "Need classes in database file" sys.exit(10) if not l1o and not q.classes: print "Need classes in querybase file" sys.exit(10) s=firesocket.FIRESocket() s.connect(server,port) try: s.sendcmd("info") res=s.getline() status=re.split(" ",res) keyword=status.pop(0) dbSize=int(status.pop(0)) if dbSize!=len(f.files): print "database in retriever and database loaded are of different size:", dbSize,"!=",len(f.files) s.sendcmd("bye") time.sleep(1) sys.exit(10) print "database has",dbSize,"images." if not l1o: s.sendcmd("setresults 1"); res=s.getline() else: s.sendcmd("setresults 2"); res=s.getline() classified=0; errors=0; correct=0 no_classes=0 for qf in q.files: if qf[1]>no_classes: no_classes=qf[1] for df in f.files: if df[1]>no_classes: no_classes=df[1] no_classes+=1 print no_classes,"classes." confusionmatrix=numarray.zeros((no_classes,no_classes),numarray.Int) counter=0 for qf in q.files: counter+=1 qname=qf[0] qcls=qf[1] s.sendcmd("retrieve "+qname) res=s.getline() res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) if not l1o: if len(results)!=2: print "expected 2 tokens, got",len(results) sys.exit(10) else: if len(results)!=4: print "expected 4 tokens, got",len(results) sys.exit(10) results.pop(0) results.pop(0) returnedimage=results.pop(0) score=float(results.pop(0)) for df in f.files: if not l1o: if df[0]==returnedimage: dcls=df[1] break else: if df[0]==returnedimage and df[0]!=qname: dcls=df[1] break classified+=1 if dcls==qcls: correct+=1 else: errors+=1 confusionmatrix[dcls][qcls]+=1 print "Query "+str(counter)+"/"+str(len(q.files))+":",qname,"("+str(qcls)+") NN:",returnedimage,"("+str(dcls)+")","ER:",float(errors)/float(classified)*100 sys.stdout.flush() print "RESULT: ER:",float(errors)/float(classified)*100 print confusionmatrix time.sleep(1) if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/env python import sys,gzip class Feature: def __init__(self): self.posx=0 self.posy=0 self.scale=0 self.vec=[] class LocalFeatures: def __init__(self): self.winsize=0 self.dim=0 self.subsampling=0 self.padding=0 self.numberOfFeatures=0 self.varthreshold=0 self.zsize=0 self.filename="" self.imagesize=(0,0) self.features=[] self.selffilename="" def __getitem__(self,i): return self.features[i] def load(self,filename): f=gzip.GzipFile(filename) self.selffilename=filename for l in f: toks=l.split() if toks[0]=="FIRE_localfeatures": fine=True elif toks[0]=="winsize": self.winsize=int(toks[1]) elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="subsampling": self.subsampling=int(toks[1]) elif toks[0]=="padding": self.padding=int(toks[1]) elif toks[0]=="numberOfFeatures": self.numberOfFeatures=int(toks[1]) elif toks[0]=="varthreshold": self.varthreshold=float(toks[1]) elif toks[0]=="zsize": self.zsize=int(toks[1]) elif toks[0]=="filename": self.filename=toks[1] elif toks[0]=="imagesize": self.imagesize=(int(toks[1]),int(toks[2])) elif toks[0]=="features": if self.numberOfFeatures!=int(toks[1]): print "Weird... inconsistent number of Features and features expected in the file" elif toks[0]=="feature": f=Feature() toks.pop(0) f.posx=float(toks.pop(0)) f.posy=float(toks.pop(0)) f.scale=float(toks.pop(0)) f.vec=map(lambda x: float(x), toks) self.features+=[f] else: print "'%s' is an unknown keyword... ignoring and continuiing nonetheless."%(toks[0]) def save(self,filename): f=gzip.GzipFile(filename,"w") f.write("FIRE_localfeatures\n") f.write("winsize %d\ndim %d\nsubsampling %d\npadding %d\nnumberOfFeatures %d\nvarthreshold %d\nzsize %d\nfilename %s\nimagesize %d %d\nfeatures %d\n" % (self.winsize,self.dim,self.subsampling,self.padding,self.numberOfFeatures,self.varthreshold,self.zsize,self.filename,self.imagesize[0],self.imagesize[1],len(self.features))) for lf in self.features: f.write("feature %d %d %d " % (lf.posx,lf.posy,lf.scale)) for v in lf.vec: f.write(str(v)+" ") f.write("\n") f.close()
Python
#!/usr/bin/python import sys #this script merges fire distance files. # # as command line parameters, arbitrary many distance files are given and # the merged distance file is printed. infiles=[] line=[] for i in sys.argv[1:]: infiles.append(open(i,"r")) line.append("") line[0]=infiles[0].readline() count=0 while(line[0]): for i in range(1,len(infiles)): line[i]=infiles[i].readline() if line[0].startswith("nofdistances"): nDist=0 nImg=0 for l in line: toks=l.split() nDist+=int(toks[2]) nImg=int(toks[1]) print "nofdistances",nImg,nDist elif not line[0].startswith("#"): print count, for l in line: toks=l.split() for i in range(1,len(toks)): print float(toks[i]), print count+=1 line[0]=infiles[0].readline()
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- import sys,cgi,re,Image,Gnuplot,string,os sys.path+=[os.getcwd()] from types import * from firesocket import * try: form=cgi.FieldStorage() if form.has_key("server"): server=form["server"].value else: server="localhost" if form.has_key("port"): port=int(form["port"].value) else: port=12960 if form.has_key("image"): image=form["image"].value else: image="100.jpg" if form.has_key("feature"): feature=form["feature"].value else: feature="1" s=FIRESocket() s.connect(server,port) s.sendcmd("feature "+image+" "+feature) line=s.getline() suffix=string.split(line)[1] lines=[] line=s.getline() while line!="end": lines+=[line] line=s.getline() s.sendcmd("bye") if suffix.endswith(".histo") or suffix.endswith(".histo.gz") or suffix.endswith("oldhisto") or suffix.endswith("oldhisto.gz"): for l in lines: if l.startswith("data"): tokens=string.split(l) tokens.pop(0) tokens=map(lambda t: float(t),tokens) bins=len(tokens) maximum=max(tokens) g=Gnuplot.Gnuplot() g('set terminal png size 300,200') g('unset xtics') g('unset ytics') g('set data style boxes') print "Content-Type: image/png\n" sys.stdout.flush() g.plot(Gnuplot.Data(tokens)) elif suffix.endswith(".vec.gz") or suffix.endswith(".oldvec.gz") or suffix.endswith(".vec"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: if l.startswith("data"): print l[5:] print "</body></html>\n" elif suffix.endswith(".textID"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body>\n</html>" elif suffix.endswith("txt") or suffix.endswith("txt.gz"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body></html>\n" elif suffix.endswith(".png"): for l in lines: if l.startswith("sizes"): tok=string.split(l) xsize=int(tok[1]) ysize=int(tok[2]) zsize=int(tok[3]) if l.startswith("data"): tok=string.split(l) tok.pop(0) if zsize==1: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): g=int(float(tok.pop(0))*255) i.putpixel((x,y),(g,g,g)) elif zsize==3: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): r=int(float(tok.pop(0))*255) g=int(float(tok.pop(0))*255) b=int(float(tok.pop(0))*255) i.putpixel((x,y),(r,g,b)) print "Content-Type: image/png\n" sys.stdout.flush() i.save(sys.stdout,"png") else: print "Content-Type: text/html\n" sys.stdout.flush() print suffix print "feature not supported: ",suffix for l in lines: print l+"<br>" print "</body></html>\n" except IOError: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Something failed"
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- import sys,cgi,re,Image,Gnuplot,string,os sys.path+=[os.getcwd()] from types import * from firesocket import * try: form=cgi.FieldStorage() if form.has_key("server"): server=form["server"].value else: server="localhost" if form.has_key("port"): port=int(form["port"].value) else: port=12960 if form.has_key("image"): image=form["image"].value else: image="100.jpg" if form.has_key("feature"): feature=form["feature"].value else: feature="1" s=FIRESocket() s.connect(server,port) s.sendcmd("feature "+image+" "+feature) line=s.getline() suffix=string.split(line)[1] lines=[] line=s.getline() while line!="end": lines+=[line] line=s.getline() s.sendcmd("bye") if suffix.endswith(".histo") or suffix.endswith(".histo.gz") or suffix.endswith("oldhisto") or suffix.endswith("oldhisto.gz"): for l in lines: if l.startswith("data"): tokens=string.split(l) tokens.pop(0) tokens=map(lambda t: float(t),tokens) bins=len(tokens) maximum=max(tokens) g=Gnuplot.Gnuplot() g('set terminal png size 300,200') g('unset xtics') g('unset ytics') g('set data style boxes') print "Content-Type: image/png\n" sys.stdout.flush() g.plot(Gnuplot.Data(tokens)) elif suffix.endswith(".vec.gz") or suffix.endswith(".oldvec.gz") or suffix.endswith(".vec"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: if l.startswith("data"): print l[5:] print "</body></html>\n" elif suffix.endswith(".textID"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body>\n</html>" elif suffix.endswith("txt") or suffix.endswith("txt.gz"): print "Content-Type: text/html\n" sys.stdout.flush() print "<html><body>\n" for l in lines: print l print "</body></html>\n" elif suffix.endswith(".png"): for l in lines: if l.startswith("sizes"): tok=string.split(l) xsize=int(tok[1]) ysize=int(tok[2]) zsize=int(tok[3]) if l.startswith("data"): tok=string.split(l) tok.pop(0) if zsize==1: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): g=int(float(tok.pop(0))*255) i.putpixel((x,y),(g,g,g)) elif zsize==3: i=Image.new("RGB",(xsize,ysize)) for x in range(xsize): for y in range(ysize): r=int(float(tok.pop(0))*255) g=int(float(tok.pop(0))*255) b=int(float(tok.pop(0))*255) i.putpixel((x,y),(r,g,b)) print "Content-Type: image/png\n" sys.stdout.flush() i.save(sys.stdout,"png") else: print "Content-Type: text/html\n" sys.stdout.flush() print suffix print "feature not supported: ",suffix for l in lines: print l+"<br>" print "</body></html>\n" except IOError: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Something failed"
Python
#!/usr/bin/python import sys import cgi import re import Image sys.stderr=sys.stdout try: form=cgi.FieldStorage() imagefilename=form["image"].value outWidth=-1 outHeight=-1 maxDim=-1 if(form.has_key("max")): maxDim=int(form["max"].value) if(form.has_key("width")): outWidth=int(form["width"].value) if(form.has_key("height")): outHeight=int(form["height"].value) inImg=Image.open(imagefilename) inWidth=inImg.size[0] inHeight=inImg.size[1] if maxDim!=-1: if inWidth>inHeight: outWidth=maxDim else: outHeight=maxDim if (outWidth==-1 and outHeight==-1): outImg=inImg elif (outWidth==-1): scaleFactor=float(outHeight)/float(inHeight) outWidth=int(scaleFactor*inWidth) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) elif (outHeight==-1): scaleFactor=float(outWidth)/float(inWidth) outHeight=int(scaleFactor*inHeight) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) else: outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) contenttype="image/jpg" print "Content-Type: "+contenttype+"\n" outImg=outImg.convert("RGB") outImg.save(sys.stdout,"jpeg") except: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Access not permitted"
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- #$Header$ # print cgi-header print "Content-Type: text/html\n\n" print #print "<pre style=\"font-family:Fixedsys,Courier,1px;\">" # to have error messages as readable as possible, this # is switched of right before displaying the main part of the page #import lots of stuff import cgi, re, sys, traceback, os, Image #import cgitb; cgitb.enable() from urllib import quote,unquote from types import * # redirect stderr to have error messages on the webpage and not in the # webserver's log sys.stderr=sys.stdout # to be able to find the config sys.path+=[os.getcwd()] #import "my" socket implementation from firesocket import * # ---------------------------------------------------------------------- # import the config # it is assumed there is a file called config in the same file as the cgi. # an example for a valid config: ## settings for i6 #positiveImg="http://www-i6.iatik.rwth-aachen.de/~deselaers/images/positive.png" #negativeImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/negativ.png" #neutralImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/neutral.png" #fireLogo="/u/deselaers/work/src/fire/cgi/fire-logo.png" #i6Logo= "/u/deselaers/work/src/fire/cgi/i6.png" #TemplateFile = "/u/deselaers/work/src/fire/cgi/fire-template.html" #fireServer="deuterium" #firePort=12960 #tempdir="/tmp" #maxSize=1000, 1000 #minSize=200, 200 # ---------------------------------------------------------------------- import config # settings for the linear (standard) scoring algorithm. using this # algorithm the weights can be changed from the web interface class LinearScoring: def __init__(self): self.size=0 self.weights=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) if(tmp=="weight"): idx=status.pop(0) w=status.pop(0) self.weights+=[w] else: print "Cannot parse LinearScoring settings" def getForm(self): result="" result+="<tr><th colspan=3> Settings for LinearScoring</th></tr>" for i in range(len(self.weights)): result+="<tr><td> Weight "+str(i)+"</td>" result+="<td colspan=2><input name=\"weight"+str(i)+"\" type=\"text\" value=\""+self.weights[i]+"\"></td></tr>" return result # settings for maxent scoring algorithm class MaxEntScoring: def __init__(self): self.size=0 self.factor=0 self.offset=0 self.lambdas=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) tmp=status.pop(0) self.factor=status.pop(0) tmp=status.pop(0) self.offset=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) idx=status.pop(0) l=status.pop(0) self.lambdas+=[l] def getForm(self): result="" result+="<tr><th colspan=3> Settings for MaxEntScoring</th></tr>" for i in range(len(self.lambdas)/2): result+="<tr><td> Lambda "+str(i)+"</td>" result+="<td>"+self.lambdas[i]+"</td><td>"+self.lambdas[i+len(self.lambdas)/2]+"</td></tr>" return result # a class to store the settings of fire this classes uses the classes # defined above to manage the settings of the active scoring algorithm class FireSettings: def __init__(self): # variable initilization only. all member variables are defined here. self.fireServer=config.fireServer self.firePort=config.firePort self.dbsize=0 self.scoringname="" self.results=0 self.expansions=0 self.distances=[] self.suffices=[] self.path="" self.scoring="" def get(self,s): # get the settings from the server, i.e. read the string s and parse it. self.distances=[] self.suffices=[] s.sendcmd("info") msg=s.getline() status=re.split(" ",msg) print "<!--"+str(status)+"-->" while(len(status)>0): keyword=status.pop(0) if keyword=="filelist": self.dbsize=status.pop(0) elif keyword=="results": self.results=status.pop(0) elif keyword=="path": self.path=status.pop(0) elif keyword=="extensions": self.expansions=status.pop(0) elif keyword=="scoring": self.scoringname=status.pop(0) if self.scoringname=="linear": self.scoring=LinearScoring() elif self.scoringname=="maxent": self.scoring=MaxEntScoring() self.scoring.get(status) elif keyword=="suffix": no=status.pop(0) suffix=status.pop(0) self.suffices+=[suffix] distname=status.pop(0) self.distances+=[distname] else: print "<!-- Unknown keyword in stream : "+keyword+" -->" def display(self): # display the settings dialog self.get(s) result="<h4>Settings for fire</h4>" result=result+"<form method=\"post\" name=\"settingsForm\">" result=result+"<input type=\"hidden\" name=\"server\" value=\""+str(self.fireServer)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(self.firePort)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"settings\" value=\"1\"/>\n" result=result+"<table border=\"1\">\n" result=result+"<tr><th colspan=3> General Settings</th></tr>" result=result+"<tr><td>Number of images in database</td><td colspan=\"2\">"+str(self.dbsize)+"</td></tr>\n" result=result+"<tr><td>Number of results shown</td><td colspan=\"2\"><input type=\"text\" value=\""+self.results+"\" name=\"results\"/></td></tr>\n" result=result+"<tr><td>Scoring</td><td colspan=\"2\">"+self.getScoringChooser()+"\n" result=result+"<tr><td>Number of Images for Query Expansion</td><td colspan=\"2\"><input type=\"text\" value=\""+self.expansions+"\" name=\"extensions\"/></td></tr>\n" result=result+self.getDistForm() result=result+self.getScoringForm() result=result+"</table>\n" result=result+"Password: <input type=\"password\" name=\"password\">\n" result=result+"<input type=\"submit\" name=\"Save\" value=\"Save\"/>\n" result=result+"</form>" return result def getScoringChooser(self): # select the chooser for the server result="<select name=\"scoring\">\n<option value=\"\">" for scor in ['linear','maxent']: if self.scoringname==scor: result=result+"<option selected value=\""+scor+"\">"+scor+"</option>\n" else: result=result+"<option value=\""+scor+"\">"+scor+"</option>\n" result+="</select>\n" return result def getScoringForm(self): # display the form element to select the scoring algorihtm return self.scoring.getForm() def getDistForm(self): result="" result+="<tr><th colspan=3> Settings for Distance Functions</th></tr>" for no in range(len(self.distances)): result+="<tr><td> Distance "+str(no)+": "+self.suffices[no]+"</td><td>"+self.getDistChooser(no,self.distances[no])+"</td></tr>" return result def getDistChooser(self,no,distName): result="<select name=\"dist"+str(no)+"\">\n<option value=\"\">" s.sendcmd("setdist") distsString=s.getline() dists=re.split(" ",distsString) for d in dists: if d==distName: result=result+"<option selected value=\""+d+"\">"+d+"</option>\n" else: result=result+"<option value=\""+d+"\">"+d+"</option>\n" result=result+"</select>\n" return result def process(self,form): result="<!-- processing settings -->\n" if form.has_key("results"): if form.has_key("password"): password=form["password"].value else: password="" s.sendcmd("password "+password) l=s.getline() result+="<!-- "+l+"-->" if l!="ok": result+="Changing settings denied: Not authorized!" for i in form.keys(): if i.find("dist")==0: no=i[4:] d=form[i].value if d!=self.distances[int(no)]: # only change when changed s.sendcmd("setdist "+no+" "+d) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("weight")==0: no=i[6:] w=float(form[i].value) if self.scoringname=="linear": if(float(self.scoring.weights[int(no)])!=float(w)): s.sendcmd("setweight "+no+" "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" else: print "weights not supported" elif i.find("results")==0: if int(form[i].value)!=int(self.results): s.sendcmd("setresults "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("extensions")==0: if int(self.expansions)!=int(form[i].value): s.sendcmd("setextensions "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("scoring")==0: sn=form[i].value if(sn!=self.scoringname): # only change when changed s.sendcmd("setscoring "+sn) l=s.getline() result=result+"<!-- "+l+" -->\n" self.scoringname=sn else: result=result+"<!-- "+i+"-->\n" result=result+"<!-- settings processed -->\n" return result # ---------------------------------------------------------------------- # Load the template file and display the content in this template file # the string FIRELOGOSTRINGHERE, I6LOGOSTRINGHERE, and "INSERT CONTENT # HERE" are replaced by the configured/generated strings # ---------------------------------------------------------------------- def Display(Content): TemplateHandle = open(config.TemplateFile, "r") # open in read only mode # read the entire file as a string TemplateInput = TemplateHandle.read() TemplateHandle.close() # close the file # this defines an exception string in case our # template file is messed up BadTemplateException = "There was a problem with the HTML template." TemplateInput = re.sub("FIRELOGOSTRINGHERE",config.fireLogo,TemplateInput) TemplateInput = re.sub("I6LOGOSTRINGHERE",config.i6Logo,TemplateInput) SubResult = re.subn("INSERT CONTENT HERE",Content,TemplateInput) if SubResult[1] == 0: raise BadTemplateException print SubResult[0] def sendretrieve(querystring): filterstring="" # if(form.has_key("filter1")): # filterstring+=" -porn2-sorted/009-www.ficken.bz-images-ficken.png" # if(form.has_key("filter2")): # filterstring+=" -porn2-sorted/037-www.free-porn-free-sex.net-free-porn-free-sex-free-sex-sites.png" s.sendcmd("retrieve "+querystring+filterstring) # ---------------------------------------------------------------------- # handle a retrieval request which was generated by clicking a random # image, that is: # 1. process the form # - extract the filename of the image which is used as query # 2. send the query to the server # 3. wait for the servers answer # 4. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def retrieve(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["queryImage"].value sendretrieve("+"+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimage,0) return result # ---------------------------------------------------------------------- # resizes an image while keeping aspect ratio # ---------------------------------------------------------------------- def resizeImage(im, newSize): newX, newY = newSize if(im.size < newSize): xSize, ySize = im.size ratio=float(xSize)/float(ySize) if(ySize < xSize): newSize=(int(newY*ratio),newY) else: newSize=(newX,int(newX*(1/ratio))) out = Image.new("RGB", newSize) out = im.resize(newSize, Image.ANTIALIAS) else: im.thumbnail(newSize, Image.ANTIALIAS) out=im return out # ---------------------------------------------------------------------- # verifies the image file and resizes the image according to # minSize and maxSize parameters in config.py # ---------------------------------------------------------------------- def checkImage(imagefile): maxSize=config.maxSize minSize=config.minSize try: im=Image.open(imagefile) except: return 0 if(im.size<minSize): im=resizeImage(im, minSize) elif(im.size>maxSize): im=resizeImage(im, maxSize) im.save(imagefile) return 1 # ---------------------------------------------------------------------- # handle a serverfile-request # ---------------------------------------------------------------------- def serverFile(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["serverfile"].value checkImage(queryimage) imagename=queryimage[queryimage.rfind("/")+1:len(queryimage)] s.sendcmd("newfile 2 "+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+imagename,0) return result # ---------------------------------------------------------------------- # handle a newfile-request # ---------------------------------------------------------------------- def newFile(form): temporaryFiles=config.tempdir # standard: "/tmp" result="<h3>Retrieval Result</h3>\n" if(save_uploaded_file(form,"absolute_path",temporaryFiles)==0): result=result+"No Retrieval Result available!" return result fileitem = form["absolute_path"] # f=os.popen("ls -l "+ temporaryFiles+"/"+fileitem.filename) # print f.readlines() if(checkImage(temporaryFiles+"/"+fileitem.filename)==0): result=result+"Delivered file was not a valid image!" return result s.sendcmd("newfile 2 "+temporaryFiles+"/"+fileitem.filename+".png") msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+fileitem.filename,0) return result # This saves a file uploaded by an HTML form. # The form_field is the name of the file input field from the form. # For example, the following form_field would be "file_1": # <input name="file_1" type="file"> # The upload_dir is the directory where the file will be written. # If no file was uploaded or if the field does not exist then # this does nothing. # written by Noah Spurrier, modified by Fabian Schwahn def save_uploaded_file(form, form_field, upload_dir): if not form.has_key(form_field): return 0 fileitem = form[form_field] completepath = upload_dir + fileitem.filename if os.path.isdir(completepath): return 0 if not fileitem.file: return 0 fout = open (os.path.join(upload_dir, fileitem.filename), 'wb') while 1: chunk = fileitem.file.read(100000) if not chunk: break fout.write (chunk) fout.close() return 1 # ---------------------------------------------------------------------- # handle a retrieval request which was generated by relevance feedback. # That is: # 1. process the form # - extract the filenames of positive and negative examples # 2. generate the query string # 3. send the query to the server # 4. wait for the servers answer # 5. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def feedbackretrieve(form): print "<!-- feedback retrieve \n" print form print "-->\n" result="<h3>Retrieval Result</h3>\n" queryimages="" for field in form.keys(): if field.startswith("relevance"): imageno=re.sub("relevance","",field) imagename=form["resultImage"+imageno].value relevance=form[field].value if relevance!="0": queryimages=queryimages+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" result=result+"\n<!-- "+queryimages+" -->\n" sendretrieve(queryimages) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimages,0) return result # ---------------------------------------------------------------------- # given the retrieval result string of the server process this answer # and create the part of the html page displaying these results. this # includes the buttons for relevance feedback and the hidden fields # for server settings (e.g.\ which server, which port). also the # buttons for "more results" and "relevance feedback" are generated. # the button for saving relevances is deaktivated as it is not used # ---------------------------------------------------------------------- def displayResults(tokens,querytype,querystring,resultsStep): if(re.search("[0-9]+(\.[0-9]+)?", tokens[0]) == None): result="Could not read retrieval result.\n" s.flush() return result print "<!-- "+str(tokens)+"-->" i=0 result="<form method=\"post\" name=\"resultForm\"><table>\n<tr>\n" result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+querystring+"\"/>\n" result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+quote(querystring)+"\" />\n" result=result+"<input type=\"hidden\" name=\"resultsstep\" value=\""+str(resultsStep)+"\"/>\n" first=True while(len(tokens) > 0): resNo=str(i) img=tokens.pop(0) score=float(tokens.pop(0)) result=result+"<td>\n" result=result+"<a href=\""+config.fireurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&imageinfo="+img+"\" target=\"_blank\">" # support for the select-rectangle tool #------------- # result=result+"<a href=\"save_coord.cgi?to_do=UpdateImage&upload_type=server&port="+str(settings.firePort)+"&image_name="+settings.path+"/"+img+"\" target=\"_top\">" #------------- # shows the image #------------- # result=result+"<a href=\"img.py?image="+settings.path+"/"+img+"\" target=\"_blank\">" #------------ result=result+"<img src=\""+config.imgpyurl+"?max=150&image="+settings.path+"/"+img+"\" title=\""+str(score)+"-"+img+"\" name=\""+str(score)+"-"+img+"\">\n<br>\n" result=result+"</a>" result=result+"<input type=\"hidden\" name=\"resultImage"+resNo+"\" value=\""+img+"\">\n" if first: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\" checked><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\"><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" first=False else: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\"><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\" checked><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" result=result+"</td>\n\n" i=i+1 if i%5==0: result=result+"</tr>\n\n\n<tr>" result=result+"</tr></table>\n" # result+=filterbuttons() result=result+"<button title=\"expandresults\" name=\"expandresults\" type=\"submit\" onClick=\"document.resultForm.feedback.value='expandresults';document.resultForm.submit()\">more results</button>\n" result=result+"<button title=\"requery\" name=\"requery\" type=\"submit\" onClick=\"document.resultForm.feedback.value='requery';document.resultForm.submit()\">requery</button>\n" # result=result+"<button title=\"saverelevances\" name=\"relevancessave\" onClick=\"document.resultForm.feedback.value='saverelevances';document.resultForm.submit()\" \"type=\"submit\">save relevances</button>\n" result=result+"<input type=\"hidden\" name=\"feedback\" value=\"yes\"/>\n" result=result+"</form>\n" return result def filterbuttons(): # display the buttons for the filter result="" result=result+"filter 1: <input type=\"checkbox\" name=\"filter1\" value=\"1\">\n" result=result+"filter 2: <input type=\"checkbox\" name=\"filter2\" value=\"2\">\n<br>\n" return result # ---------------------------------------------------------------------- # ask the server for filenames of random images and create the part of # the html page showing random images. Steps: # 1. send "random" to the server # 2. receive the servers answer # 3. process the answer: # - get the filenames and for each filename create a querybutton # 4. put the "more random images" button, such that we can get a new set # of random images # ---------------------------------------------------------------------- def randomImages(): # display random images s.sendcmd("random") result="<hr><h3> Random Images - Click one to start a query </h3>" result+="""<form method="post" name="queryForm" enctype="multipart/form-data"> <input type="hidden" name="queryImage" value=""> """ result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result+=filterbuttons() res=s.getline() for img in re.split(" ",res): if img != "" and img != "\n": result=result+"<button title=\""+img+"\" name=\"searchButton\" type=\"submit\" onClick=\"document.queryForm.queryImage.value='"+img+"';document.queryForm.submit()\" value=\""+img+"\">\n" result=result+"<img src=\""+config.imgpyurl+"?max=100&image="+settings.path+"/"+img+"\" title=\""+img+"\">\n" result=result+"</button>\n" if form.has_key("demomode"): seconds=form["demomode"].value url="http://" if(os.environ.has_key("HTTP_HOST") and os.environ.has_key("REQUEST_URI")): part1=os.environ["HTTP_HOST"] part2=re.sub("&queryImage=.*$","",os.environ["REQUEST_URI"]) url=url+part1+part2+"&queryImage="+img print "<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result=result+"<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result+="<br><div align=\"right\">\n<button title=\"new random images\" name=\"morerandom\" type=\"submit\">more random images</button>\n</div>\n" return result # ---------------------------------------------------------------------- # displays the newfile-form # ---------------------------------------------------------------------- def newFileForm(): result="<hr><h3> Upload - Use query image from your file system </h3>" result+="""<input type="hidden" name="newFile" value="0">""" result+="""<input name="absolute_path" type="file" size="30" onClick="document.queryForm.newFile.value=1;document.queryForm.submit()">""" result+="\n" return result # ---------------------------------------------------------------------- # generate the text field and the query button for text # queries # ---------------------------------------------------------------------- def textQueryForm(settings): result = "<hr><h3>Query by " if("textfeature" in settings.distances): result += "description" if("metafeature" in settings.distances): result += " or meta information" elif("metafeature" in settings.distances): result += "meta information" result += "</h3>\n" result += "<form method=\"post\" name=\"textQueryForm\">\n" result += "<input type=\"hidden\" name=\"server\" value=\""+str(settings.fireServer)+"\"/>\n" result += "<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" result += "<input type=\"hidden\" name=\"resultsstep\" value=\"0\"/>\n" result += "<input type=\"text\" name=\"textquerystring\" size=\"30\" value=\"\"/>\n" result += "<input type=\"submit\" value=\"query\"/>\n" if("metafeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&metafeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on meta info</a>" if("textfeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&textfeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on description</a>" result += "</form>" return result def displayMetaFeatureInfo(): s.sendcmd("metafeatureinfo") mfi = s.getline() mfil = mfi.split(" ") result = "<h4>Help on queries by meta info</h4>\n" result += """If you want to find images with certain meta information attached, type in a request of the form <h5>key1:val1,key2:val2,...</h5>\n The following meta keys are available in this corpus:<br><br>\n""" #TODO: The table looks ugly! result += "<table>\n" result += "<tr>\n" result += " <th>key</th>\n" result += " <th>example value</th>\n" result += "</tr>\n" for mf in mfil: mfl = mf.split(":") result += "<tr>\n" result += " <td><b>"+mfl[0]+"</b></td>\n" # I know <b> is deprecated, but it still works :-) result += " <td>"+mfl[1]+"</td>\n" result += "</tr>\n" result += "</table>\n" return result def displayTextFeatureInfo(): result = "<h4>Help on queries by description</h4>\n" result += """If you want to find images which have text information attached to them, just enter the query into the textbox. Fire will then use an information retrieval engine to find the images that best match your query.<br><br> If you have text information in multiple languages for each image, you can give a query for every language. For example, if you have german and french text information and you want to search for "hand" in the respective languages, you enter <h5>Ge:"hand" Fr:"mains"</h5> Here, "Ge" has to be the suffix for the german textfiles and "Fr" has to be the suffix for the fench textfiles. Fire will then use both queries and send them to separate information retrieval engines.""" return result # ---------------------------------------------------------------------- # this function makes the server save a relevances logfile # but it is not used at the moment, because the saverelevances button # is deaktivated # ---------------------------------------------------------------------- def saveRelevances(form): querystring=form["querystring"].value relevancestring="" for field in form.keys(): if field.startswith("relevance-"): imagename=re.sub("relevance-","",field) relevance=form[field].value if relevance!="0": relevancestring=relevancestring+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" s.sendcmd("saverelevances Q "+querystring+" R "+relevancestring) res=s.getline(); message="<a href=\"javascript:back()\"> Go back to last query </a>" return message # ---------------------------------------------------------------------- # this is the "getMoreResults" function it basically does the same as # retrieve, uses the same query string as the last query used (this is # gotten from the form) and the calls displayResults # ---------------------------------------------------------------------- def expandQuery(form): resultsstep=int(form["resultsstep"].value) resultsstep=resultsstep+1 if(form.has_key("metaquerystring")): result="<h3>Metatag-based retrieval result</h3>\n" queryfield = "metaquerystring" cmd = "metaexpand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) elif(form.has_key("textquerystring")): result="<h3>Text-based retrieval result</h3>\n" queryfield = "textquerystring" cmd = "textexpand" queryimages = unquote(form["textquerystring"].value) s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) else: result="<h3>Retrieval Result</h3>\n" queryfield = "querystring" cmd = "expand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) msg=s.getline() tokens=re.split(" ",msg) if(tokens[0] == "notextinformation"): result=result+"No images matched your query: "+querystring result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,queryfield,queryimages,resultsstep) return result # ---------------------------------------------------------------------- # process a query using text- or metainformation from the text input # field. The query type is set to metaquery when the search string has # a leading "META " # This works identical as the retrieve function # ---------------------------------------------------------------------- def processTextQuery(form): # Check if it's meta or text # It's meta either if there's only the metafeature or it has a leading "META " hasmeta = "metafeature" in settings.distances hastext = "textfeature" in settings.distances querystring = form["textquerystring"].value if (hasmeta and (not hastext or querystring[:5] == "META ")): if(querystring[:5] == "META "): querystring = querystring[5:] querytype = "metaquerystring" result="<h3>Metatag-based retrieval result</h3>\n" s.sendcmd("metaretrieve +"+querystring) else: querytype = "textquerystring" result="<h3>Text-based retrieval result</h3>\n" s.sendcmd("textretrieve +"+querystring) msg=s.getline() tokens=re.split(" ",msg) if( (tokens[0] == "notextinformation") or (tokens[0] == "nometainformation") ): result=result+"No images matched your query: "+querystring if(querytype == "metaquerystring"): if(hastext): result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'META key1:val1,key2:val2,...'<br><br>\n" else: result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'key1:val1,key2:val2,...'<br><br>\n" result=result+"Also have a look at the help to see which keys are available.<br>\n" if(querytype == "textquerystring"): result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,querytype,querystring,0) return result # ---------------------------------------------------------------------- # create the link for the "settings" at the bottom of the page # ---------------------------------------------------------------------- def adminLink(fireServer, firePort): result="" result=result+"<a name=\"#\"></a>" result=result+"<a href=\"#\" "+\ "onClick=\"window.open('"+config.fireurl+"?server="+ \ fireServer+"&port="+str(firePort)+"&settings=1','newwindow',"+\ "'height=600, width=600')\">settings</a>" return result #<SCRIPT LANGUAGE="javascript"> #<!-- #window.open ('titlepage.html', 'newwindow', config='height=100, #width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no, #location=no, directories=no, status=no') #--> #</SCRIPT> # ---------------------------------------------------------------------- # the main program # ---------------------------------------------------------------------- # get form information in easily accessible manner form=cgi.FieldStorage() # make socket s = FIRESocket() settings=FireSettings() # see what server we have and if the webinterface specifed another one # than the one in the config file if form.has_key("server"): settings.fireServer=form["server"].value if form.has_key("port"): settings.firePort=int(form["port"].value) try: # connect to the server s.connect(settings.fireServer, settings.firePort) except: # if the server is down, give an error message # print "</pre>" message=""" <h2>FIRE Server down</h2> <p> Try again later, complain to <a href="mailto:deselaers@informatik.rwth-aachen.de">deselaers@informatik.rwth-aachen.de</a> or try other servers. """ Display(message) else: # everything is fine, connection to server is ok # try: message="" settings.get(s) # do we want to show the settings window? if(form.has_key("settings")): # see if there have been new settings defined message=settings.process(form) # generate the settings dialog message+=settings.display() # disonnect from server s.sendcmd("bye") print "</pre>" # display the settings dialog Display(message) # do we want to show the metafeatureinfo window? elif(form.has_key("metafeatureinfo")): message+=displayMetaFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) elif(form.has_key("imageinfo")): imagename=form["imageinfo"].value s.sendcmd("image "+imagename) line="" while(line != "end"): line=s.getline() tokens=re.split(" ",line) if tokens[0]=="imagefilename": message+="<img src=\""+config.imgpyurl+"?image="+tokens[1]+"\" alt=\""+tokens[1]+"\"/><br>"+"\n" elif tokens[0]=="class": message+="class: "+tokens[1]+"<br>\n" elif tokens[0]=="description": message+="description: "+tokens[1:]+"<br>\n" elif tokens[0]=="features": features=[] noffeatures=int(tokens[1]) for i in range(noffeatures): line=s.getline() tokens=re.split(" ",line) message+="<h3>"+str(i)+": "+tokens[2]+"</h3>\n<br>\n" if tokens[2].endswith(".histo.gz") \ or tokens[2].endswith(".histo") \ or tokens[2].endswith(".oldhisto.gz") \ or tokens[2].endswith(".png"): message+="<img src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\" alt=\""+tokens[2]+"\"/><br><br>\n" elif tokens[2].endswith(".vec.gz") \ or tokens[2].endswith(".oldvec.gz") \ or tokens[2].endswith(".vec") \ or tokens[2].endswith("txt") \ or tokens[2].endswith("txt.gz") \ or tokens[2].endswith("textID"): message+="<iframe src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\"></iframe><br><br>\n" else: message+="not yet supported<br>\n" line=s.getline() # get end s.sendcmd("bye") Display(message) elif(form.has_key("textfeatureinfo")): message+=displayTextFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) else: # we do not want to show the settings window if(form.has_key("newFile") and form["newFile"].value=="1"): #message+=str(form["newFile"]) message+=newFile(form) elif(form.has_key("serverfile")): message+=serverFile(form) elif(form.has_key("feedback")): # result images have been selected and are part of this query if form["feedback"].value=="requery": # relevance feedback message+=feedbackretrieve(form) elif form["feedback"].value=="expandresults": # more results message+=expandQuery(form) else: # save relevances (this will not happen currently) message=saveRelevances(form) elif(form.has_key("queryImage") and form["queryImage"].value!=""): # no relevance feedback, but just one of the random images was clicked message+=retrieve(form) elif form.has_key('textquerystring'): # no relevance feedback, no query image, but a query string for text queries message+=processTextQuery(form) # now generate the remainder of the website: queryfield for meta information, random images, adminlink if("textfeature" in settings.distances or "metafeature" in settings.distances): message+=textQueryForm(settings) message+=randomImages() message+=newFileForm() message+="<p align=\"right\">"+adminLink(settings.fireServer, settings.firePort)+"</p>" message+="</form>" # disconnect from server s.sendcmd("bye") print "</pre>" # display the generated webpage Display(message) # except Exception, e: # if anything went wrong: # show the error message as readable as possible, # disconnect from the server to keep it alive # and end yourself # print "<pre>" # print "Exception: ",e # s.sendcmd("bye") # print "</pre>"
Python
#default settings positiveImg="images/positive.png" negativeImg="images/negativ.png" neutralImg="images/neutral.png" fireLogo="images/fire-logo.png" i6Logo="images/i6.png" TemplateFile = "fire-template.html" fireServer="localhost" firePort=12960 imgpyurl="img.py" fireurl="fire.py" #tempdir="/tmp" #maxSize=1000, 1000 #minSize=200, 200
Python
#!/usr/bin/python import sys import cgi import re import Image sys.stderr=sys.stdout try: form=cgi.FieldStorage() imagefilename=form["image"].value outWidth=-1 outHeight=-1 maxDim=-1 if(form.has_key("max")): maxDim=int(form["max"].value) if(form.has_key("width")): outWidth=int(form["width"].value) if(form.has_key("height")): outHeight=int(form["height"].value) inImg=Image.open(imagefilename) inWidth=inImg.size[0] inHeight=inImg.size[1] if maxDim!=-1: if inWidth>inHeight: outWidth=maxDim else: outHeight=maxDim if (outWidth==-1 and outHeight==-1): outImg=inImg elif (outWidth==-1): scaleFactor=float(outHeight)/float(inHeight) outWidth=int(scaleFactor*inWidth) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) elif (outHeight==-1): scaleFactor=float(outWidth)/float(inWidth) outHeight=int(scaleFactor*inHeight) outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) else: outImg=inImg.resize((outWidth,outHeight),Image.BILINEAR) contenttype="image/jpg" print "Content-Type: "+contenttype+"\n" outImg=outImg.convert("RGB") outImg.save(sys.stdout,"jpeg") except: contenttype="text/html" print "Content-Type: "+contenttype+"\n" print "Access not permitted"
Python
#!/usr/bin/python # -*- coding: iso-8859-1 -*- #$Header$ # print cgi-header print "Content-Type: text/html\n\n" print #print "<pre style=\"font-family:Fixedsys,Courier,1px;\">" # to have error messages as readable as possible, this # is switched of right before displaying the main part of the page #import lots of stuff import cgi, re, sys, traceback, os, Image #import cgitb; cgitb.enable() from urllib import quote,unquote from types import * # redirect stderr to have error messages on the webpage and not in the # webserver's log sys.stderr=sys.stdout # to be able to find the config sys.path+=[os.getcwd()] #import "my" socket implementation from firesocket import * # ---------------------------------------------------------------------- # import the config # it is assumed there is a file called config in the same file as the cgi. # an example for a valid config: ## settings for i6 #positiveImg="http://www-i6.iatik.rwth-aachen.de/~deselaers/images/positive.png" #negativeImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/negativ.png" #neutralImg="http://www-i6.informatik.rwth-aachen.de/~deselaers/images/neutral.png" #fireLogo="/u/deselaers/work/src/fire/cgi/fire-logo.png" #i6Logo= "/u/deselaers/work/src/fire/cgi/i6.png" #TemplateFile = "/u/deselaers/work/src/fire/cgi/fire-template.html" #fireServer="deuterium" #firePort=12960 #tempdir="/tmp" #maxSize=1000, 1000 #minSize=200, 200 # ---------------------------------------------------------------------- import config # settings for the linear (standard) scoring algorithm. using this # algorithm the weights can be changed from the web interface class LinearScoring: def __init__(self): self.size=0 self.weights=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) if(tmp=="weight"): idx=status.pop(0) w=status.pop(0) self.weights+=[w] else: print "Cannot parse LinearScoring settings" def getForm(self): result="" result+="<tr><th colspan=3> Settings for LinearScoring</th></tr>" for i in range(len(self.weights)): result+="<tr><td> Weight "+str(i)+"</td>" result+="<td colspan=2><input name=\"weight"+str(i)+"\" type=\"text\" value=\""+self.weights[i]+"\"></td></tr>" return result # settings for maxent scoring algorithm class MaxEntScoring: def __init__(self): self.size=0 self.factor=0 self.offset=0 self.lambdas=[] def get(self,status): tmp=status.pop(0) self.size=status.pop(0) tmp=status.pop(0) self.factor=status.pop(0) tmp=status.pop(0) self.offset=status.pop(0) for i in range(int(self.size)): tmp=status.pop(0) idx=status.pop(0) l=status.pop(0) self.lambdas+=[l] def getForm(self): result="" result+="<tr><th colspan=3> Settings for MaxEntScoring</th></tr>" for i in range(len(self.lambdas)/2): result+="<tr><td> Lambda "+str(i)+"</td>" result+="<td>"+self.lambdas[i]+"</td><td>"+self.lambdas[i+len(self.lambdas)/2]+"</td></tr>" return result # a class to store the settings of fire this classes uses the classes # defined above to manage the settings of the active scoring algorithm class FireSettings: def __init__(self): # variable initilization only. all member variables are defined here. self.fireServer=config.fireServer self.firePort=config.firePort self.dbsize=0 self.scoringname="" self.results=0 self.expansions=0 self.distances=[] self.suffices=[] self.path="" self.scoring="" def get(self,s): # get the settings from the server, i.e. read the string s and parse it. self.distances=[] self.suffices=[] s.sendcmd("info") msg=s.getline() status=re.split(" ",msg) print "<!--"+str(status)+"-->" while(len(status)>0): keyword=status.pop(0) if keyword=="filelist": self.dbsize=status.pop(0) elif keyword=="results": self.results=status.pop(0) elif keyword=="path": self.path=status.pop(0) elif keyword=="extensions": self.expansions=status.pop(0) elif keyword=="scoring": self.scoringname=status.pop(0) if self.scoringname=="linear": self.scoring=LinearScoring() elif self.scoringname=="maxent": self.scoring=MaxEntScoring() self.scoring.get(status) elif keyword=="suffix": no=status.pop(0) suffix=status.pop(0) self.suffices+=[suffix] distname=status.pop(0) self.distances+=[distname] else: print "<!-- Unknown keyword in stream : "+keyword+" -->" def display(self): # display the settings dialog self.get(s) result="<h4>Settings for fire</h4>" result=result+"<form method=\"post\" name=\"settingsForm\">" result=result+"<input type=\"hidden\" name=\"server\" value=\""+str(self.fireServer)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(self.firePort)+"\"/>\n" result=result+"<input type=\"hidden\" name=\"settings\" value=\"1\"/>\n" result=result+"<table border=\"1\">\n" result=result+"<tr><th colspan=3> General Settings</th></tr>" result=result+"<tr><td>Number of images in database</td><td colspan=\"2\">"+str(self.dbsize)+"</td></tr>\n" result=result+"<tr><td>Number of results shown</td><td colspan=\"2\"><input type=\"text\" value=\""+self.results+"\" name=\"results\"/></td></tr>\n" result=result+"<tr><td>Scoring</td><td colspan=\"2\">"+self.getScoringChooser()+"\n" result=result+"<tr><td>Number of Images for Query Expansion</td><td colspan=\"2\"><input type=\"text\" value=\""+self.expansions+"\" name=\"extensions\"/></td></tr>\n" result=result+self.getDistForm() result=result+self.getScoringForm() result=result+"</table>\n" result=result+"Password: <input type=\"password\" name=\"password\">\n" result=result+"<input type=\"submit\" name=\"Save\" value=\"Save\"/>\n" result=result+"</form>" return result def getScoringChooser(self): # select the chooser for the server result="<select name=\"scoring\">\n<option value=\"\">" for scor in ['linear','maxent']: if self.scoringname==scor: result=result+"<option selected value=\""+scor+"\">"+scor+"</option>\n" else: result=result+"<option value=\""+scor+"\">"+scor+"</option>\n" result+="</select>\n" return result def getScoringForm(self): # display the form element to select the scoring algorihtm return self.scoring.getForm() def getDistForm(self): result="" result+="<tr><th colspan=3> Settings for Distance Functions</th></tr>" for no in range(len(self.distances)): result+="<tr><td> Distance "+str(no)+": "+self.suffices[no]+"</td><td>"+self.getDistChooser(no,self.distances[no])+"</td></tr>" return result def getDistChooser(self,no,distName): result="<select name=\"dist"+str(no)+"\">\n<option value=\"\">" s.sendcmd("setdist") distsString=s.getline() dists=re.split(" ",distsString) for d in dists: if d==distName: result=result+"<option selected value=\""+d+"\">"+d+"</option>\n" else: result=result+"<option value=\""+d+"\">"+d+"</option>\n" result=result+"</select>\n" return result def process(self,form): result="<!-- processing settings -->\n" if form.has_key("results"): if form.has_key("password"): password=form["password"].value else: password="" s.sendcmd("password "+password) l=s.getline() result+="<!-- "+l+"-->" if l!="ok": result+="Changing settings denied: Not authorized!" for i in form.keys(): if i.find("dist")==0: no=i[4:] d=form[i].value if d!=self.distances[int(no)]: # only change when changed s.sendcmd("setdist "+no+" "+d) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("weight")==0: no=i[6:] w=float(form[i].value) if self.scoringname=="linear": if(float(self.scoring.weights[int(no)])!=float(w)): s.sendcmd("setweight "+no+" "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" else: print "weights not supported" elif i.find("results")==0: if int(form[i].value)!=int(self.results): s.sendcmd("setresults "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("extensions")==0: if int(self.expansions)!=int(form[i].value): s.sendcmd("setextensions "+form[i].value) l=s.getline() result=result+"<!-- "+l+" -->\n" elif i.find("scoring")==0: sn=form[i].value if(sn!=self.scoringname): # only change when changed s.sendcmd("setscoring "+sn) l=s.getline() result=result+"<!-- "+l+" -->\n" self.scoringname=sn else: result=result+"<!-- "+i+"-->\n" result=result+"<!-- settings processed -->\n" return result # ---------------------------------------------------------------------- # Load the template file and display the content in this template file # the string FIRELOGOSTRINGHERE, I6LOGOSTRINGHERE, and "INSERT CONTENT # HERE" are replaced by the configured/generated strings # ---------------------------------------------------------------------- def Display(Content): TemplateHandle = open(config.TemplateFile, "r") # open in read only mode # read the entire file as a string TemplateInput = TemplateHandle.read() TemplateHandle.close() # close the file # this defines an exception string in case our # template file is messed up BadTemplateException = "There was a problem with the HTML template." TemplateInput = re.sub("FIRELOGOSTRINGHERE",config.fireLogo,TemplateInput) TemplateInput = re.sub("I6LOGOSTRINGHERE",config.i6Logo,TemplateInput) SubResult = re.subn("INSERT CONTENT HERE",Content,TemplateInput) if SubResult[1] == 0: raise BadTemplateException print SubResult[0] def sendretrieve(querystring): filterstring="" # if(form.has_key("filter1")): # filterstring+=" -porn2-sorted/009-www.ficken.bz-images-ficken.png" # if(form.has_key("filter2")): # filterstring+=" -porn2-sorted/037-www.free-porn-free-sex.net-free-porn-free-sex-free-sex-sites.png" s.sendcmd("retrieve "+querystring+filterstring) # ---------------------------------------------------------------------- # handle a retrieval request which was generated by clicking a random # image, that is: # 1. process the form # - extract the filename of the image which is used as query # 2. send the query to the server # 3. wait for the servers answer # 4. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def retrieve(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["queryImage"].value sendretrieve("+"+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimage,0) return result # ---------------------------------------------------------------------- # resizes an image while keeping aspect ratio # ---------------------------------------------------------------------- def resizeImage(im, newSize): newX, newY = newSize if(im.size < newSize): xSize, ySize = im.size ratio=float(xSize)/float(ySize) if(ySize < xSize): newSize=(int(newY*ratio),newY) else: newSize=(newX,int(newX*(1/ratio))) out = Image.new("RGB", newSize) out = im.resize(newSize, Image.ANTIALIAS) else: im.thumbnail(newSize, Image.ANTIALIAS) out=im return out # ---------------------------------------------------------------------- # verifies the image file and resizes the image according to # minSize and maxSize parameters in config.py # ---------------------------------------------------------------------- def checkImage(imagefile): maxSize=config.maxSize minSize=config.minSize try: im=Image.open(imagefile) except: return 0 if(im.size<minSize): im=resizeImage(im, minSize) elif(im.size>maxSize): im=resizeImage(im, maxSize) im.save(imagefile) return 1 # ---------------------------------------------------------------------- # handle a serverfile-request # ---------------------------------------------------------------------- def serverFile(form): result="<h3>Retrieval Result</h3>\n" queryimage=form["serverfile"].value checkImage(queryimage) imagename=queryimage[queryimage.rfind("/")+1:len(queryimage)] s.sendcmd("newfile 2 "+queryimage) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+imagename,0) return result # ---------------------------------------------------------------------- # handle a newfile-request # ---------------------------------------------------------------------- def newFile(form): temporaryFiles=config.tempdir # standard: "/tmp" result="<h3>Retrieval Result</h3>\n" if(save_uploaded_file(form,"absolute_path",temporaryFiles)==0): result=result+"No Retrieval Result available!" return result fileitem = form["absolute_path"] # f=os.popen("ls -l "+ temporaryFiles+"/"+fileitem.filename) # print f.readlines() if(checkImage(temporaryFiles+"/"+fileitem.filename)==0): result=result+"Delivered file was not a valid image!" return result s.sendcmd("newfile 2 "+temporaryFiles+"/"+fileitem.filename+".png") msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring","./"+fileitem.filename,0) return result # This saves a file uploaded by an HTML form. # The form_field is the name of the file input field from the form. # For example, the following form_field would be "file_1": # <input name="file_1" type="file"> # The upload_dir is the directory where the file will be written. # If no file was uploaded or if the field does not exist then # this does nothing. # written by Noah Spurrier, modified by Fabian Schwahn def save_uploaded_file(form, form_field, upload_dir): if not form.has_key(form_field): return 0 fileitem = form[form_field] completepath = upload_dir + fileitem.filename if os.path.isdir(completepath): return 0 if not fileitem.file: return 0 fout = open (os.path.join(upload_dir, fileitem.filename), 'wb') while 1: chunk = fileitem.file.read(100000) if not chunk: break fout.write (chunk) fout.close() return 1 # ---------------------------------------------------------------------- # handle a retrieval request which was generated by relevance feedback. # That is: # 1. process the form # - extract the filenames of positive and negative examples # 2. generate the query string # 3. send the query to the server # 4. wait for the servers answer # 5. call displayResults with the servers answer to display the results # ---------------------------------------------------------------------- def feedbackretrieve(form): print "<!-- feedback retrieve \n" print form print "-->\n" result="<h3>Retrieval Result</h3>\n" queryimages="" for field in form.keys(): if field.startswith("relevance"): imageno=re.sub("relevance","",field) imagename=form["resultImage"+imageno].value relevance=form[field].value if relevance!="0": queryimages=queryimages+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" result=result+"\n<!-- "+queryimages+" -->\n" sendretrieve(queryimages) msg=s.getline() tokens=re.split(" ",msg) result=result+displayResults(tokens,"querystring",queryimages,0) return result # ---------------------------------------------------------------------- # given the retrieval result string of the server process this answer # and create the part of the html page displaying these results. this # includes the buttons for relevance feedback and the hidden fields # for server settings (e.g.\ which server, which port). also the # buttons for "more results" and "relevance feedback" are generated. # the button for saving relevances is deaktivated as it is not used # ---------------------------------------------------------------------- def displayResults(tokens,querytype,querystring,resultsStep): if(re.search("[0-9]+(\.[0-9]+)?", tokens[0]) == None): result="Could not read retrieval result.\n" s.flush() return result print "<!-- "+str(tokens)+"-->" i=0 result="<form method=\"post\" name=\"resultForm\"><table>\n<tr>\n" result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+querystring+"\"/>\n" result=result+"<input type=\"hidden\" name=\""+querytype+"\" value=\""+quote(querystring)+"\" />\n" result=result+"<input type=\"hidden\" name=\"resultsstep\" value=\""+str(resultsStep)+"\"/>\n" first=True while(len(tokens) > 0): resNo=str(i) img=tokens.pop(0) score=float(tokens.pop(0)) result=result+"<td>\n" result=result+"<a href=\""+config.fireurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&imageinfo="+img+"\" target=\"_blank\">" # support for the select-rectangle tool #------------- # result=result+"<a href=\"save_coord.cgi?to_do=UpdateImage&upload_type=server&port="+str(settings.firePort)+"&image_name="+settings.path+"/"+img+"\" target=\"_top\">" #------------- # shows the image #------------- # result=result+"<a href=\"img.py?image="+settings.path+"/"+img+"\" target=\"_blank\">" #------------ result=result+"<img src=\""+config.imgpyurl+"?max=150&image="+settings.path+"/"+img+"\" title=\""+str(score)+"-"+img+"\" name=\""+str(score)+"-"+img+"\">\n<br>\n" result=result+"</a>" result=result+"<input type=\"hidden\" name=\"resultImage"+resNo+"\" value=\""+img+"\">\n" if first: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\" checked><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\"><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" first=False else: result=result+"<center><input type=\"radio\" name=\"relevance"+resNo+"\" value=\"+\"><img src=\""+config.positiveImg+"\" alt=\"+\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[0].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"0\" checked><img src=\""+config.neutralImg+"\" alt=\"0\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[1].checked=true;\">&nbsp;\n" result=result+"<input type=\"radio\" name=\"relevance"+resNo+"\" value=\"-\"><img src=\""+config.negativeImg+"\" alt=\"-\" onClick=\"javascript:document.resultForm.relevance"+resNo+"[2].checked=true;\"></center>\n" result=result+"</td>\n\n" i=i+1 if i%5==0: result=result+"</tr>\n\n\n<tr>" result=result+"</tr></table>\n" # result+=filterbuttons() result=result+"<button title=\"expandresults\" name=\"expandresults\" type=\"submit\" onClick=\"document.resultForm.feedback.value='expandresults';document.resultForm.submit()\">more results</button>\n" result=result+"<button title=\"requery\" name=\"requery\" type=\"submit\" onClick=\"document.resultForm.feedback.value='requery';document.resultForm.submit()\">requery</button>\n" # result=result+"<button title=\"saverelevances\" name=\"relevancessave\" onClick=\"document.resultForm.feedback.value='saverelevances';document.resultForm.submit()\" \"type=\"submit\">save relevances</button>\n" result=result+"<input type=\"hidden\" name=\"feedback\" value=\"yes\"/>\n" result=result+"</form>\n" return result def filterbuttons(): # display the buttons for the filter result="" result=result+"filter 1: <input type=\"checkbox\" name=\"filter1\" value=\"1\">\n" result=result+"filter 2: <input type=\"checkbox\" name=\"filter2\" value=\"2\">\n<br>\n" return result # ---------------------------------------------------------------------- # ask the server for filenames of random images and create the part of # the html page showing random images. Steps: # 1. send "random" to the server # 2. receive the servers answer # 3. process the answer: # - get the filenames and for each filename create a querybutton # 4. put the "more random images" button, such that we can get a new set # of random images # ---------------------------------------------------------------------- def randomImages(): # display random images s.sendcmd("random") result="<hr><h3> Random Images - Click one to start a query </h3>" result+="""<form method="post" name="queryForm" enctype="multipart/form-data"> <input type="hidden" name="queryImage" value=""> """ result=result+"<input type=\"hidden\" name=\"server\" value=\""+settings.fireServer+"\"/>\n" result=result+"<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" #result+=filterbuttons() res=s.getline() for img in re.split(" ",res): if img != "" and img != "\n": result=result+"<button title=\""+img+"\" name=\"searchButton\" type=\"submit\" onClick=\"document.queryForm.queryImage.value='"+img+"';document.queryForm.submit()\" value=\""+img+"\">\n" result=result+"<img src=\""+config.imgpyurl+"?max=100&image="+settings.path+"/"+img+"\" title=\""+img+"\">\n" result=result+"</button>\n" if form.has_key("demomode"): seconds=form["demomode"].value url="http://" if(os.environ.has_key("HTTP_HOST") and os.environ.has_key("REQUEST_URI")): part1=os.environ["HTTP_HOST"] part2=re.sub("&queryImage=.*$","",os.environ["REQUEST_URI"]) url=url+part1+part2+"&queryImage="+img print "<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result=result+"<meta http-equiv=\"refresh\" content=\""+seconds+"; URL="+url+"\">\n" result+="<br><div align=\"right\">\n<button title=\"new random images\" name=\"morerandom\" type=\"submit\">more random images</button>\n</div>\n" return result # ---------------------------------------------------------------------- # displays the newfile-form # ---------------------------------------------------------------------- def newFileForm(): result="<hr><h3> Upload - Use query image from your file system </h3>" result+="""<input type="hidden" name="newFile" value="0">""" result+="""<input name="absolute_path" type="file" size="30" onClick="document.queryForm.newFile.value=1;document.queryForm.submit()">""" result+="\n" return result # ---------------------------------------------------------------------- # generate the text field and the query button for text # queries # ---------------------------------------------------------------------- def textQueryForm(settings): result = "<hr><h3>Query by " if("textfeature" in settings.distances): result += "description" if("metafeature" in settings.distances): result += " or meta information" elif("metafeature" in settings.distances): result += "meta information" result += "</h3>\n" result += "<form method=\"post\" name=\"textQueryForm\">\n" result += "<input type=\"hidden\" name=\"server\" value=\""+str(settings.fireServer)+"\"/>\n" result += "<input type=\"hidden\" name=\"port\" value=\""+str(settings.firePort)+"\"/>\n" result += "<input type=\"hidden\" name=\"resultsstep\" value=\"0\"/>\n" result += "<input type=\"text\" name=\"textquerystring\" size=\"30\" value=\"\"/>\n" result += "<input type=\"submit\" value=\"query\"/>\n" if("metafeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&metafeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on meta info</a>" if("textfeature" in settings.distances): result += "<a href=\"#\" onClick=\"window.open('"+config.fireurl+"?server="+ \ settings.fireServer+"&port="+str(settings.firePort)+ \ "&textfeatureinfo=1','newwindow',"+ \ "'height=600, width=600')\">help on description</a>" result += "</form>" return result def displayMetaFeatureInfo(): s.sendcmd("metafeatureinfo") mfi = s.getline() mfil = mfi.split(" ") result = "<h4>Help on queries by meta info</h4>\n" result += """If you want to find images with certain meta information attached, type in a request of the form <h5>key1:val1,key2:val2,...</h5>\n The following meta keys are available in this corpus:<br><br>\n""" #TODO: The table looks ugly! result += "<table>\n" result += "<tr>\n" result += " <th>key</th>\n" result += " <th>example value</th>\n" result += "</tr>\n" for mf in mfil: mfl = mf.split(":") result += "<tr>\n" result += " <td><b>"+mfl[0]+"</b></td>\n" # I know <b> is deprecated, but it still works :-) result += " <td>"+mfl[1]+"</td>\n" result += "</tr>\n" result += "</table>\n" return result def displayTextFeatureInfo(): result = "<h4>Help on queries by description</h4>\n" result += """If you want to find images which have text information attached to them, just enter the query into the textbox. Fire will then use an information retrieval engine to find the images that best match your query.<br><br> If you have text information in multiple languages for each image, you can give a query for every language. For example, if you have german and french text information and you want to search for "hand" in the respective languages, you enter <h5>Ge:"hand" Fr:"mains"</h5> Here, "Ge" has to be the suffix for the german textfiles and "Fr" has to be the suffix for the fench textfiles. Fire will then use both queries and send them to separate information retrieval engines.""" return result # ---------------------------------------------------------------------- # this function makes the server save a relevances logfile # but it is not used at the moment, because the saverelevances button # is deaktivated # ---------------------------------------------------------------------- def saveRelevances(form): querystring=form["querystring"].value relevancestring="" for field in form.keys(): if field.startswith("relevance-"): imagename=re.sub("relevance-","",field) relevance=form[field].value if relevance!="0": relevancestring=relevancestring+" "+relevance+imagename else: print "<!-- field not processed: "+field+" -->" s.sendcmd("saverelevances Q "+querystring+" R "+relevancestring) res=s.getline(); message="<a href=\"javascript:back()\"> Go back to last query </a>" return message # ---------------------------------------------------------------------- # this is the "getMoreResults" function it basically does the same as # retrieve, uses the same query string as the last query used (this is # gotten from the form) and the calls displayResults # ---------------------------------------------------------------------- def expandQuery(form): resultsstep=int(form["resultsstep"].value) resultsstep=resultsstep+1 if(form.has_key("metaquerystring")): result="<h3>Metatag-based retrieval result</h3>\n" queryfield = "metaquerystring" cmd = "metaexpand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) elif(form.has_key("textquerystring")): result="<h3>Text-based retrieval result</h3>\n" queryfield = "textquerystring" cmd = "textexpand" queryimages = unquote(form["textquerystring"].value) s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) else: result="<h3>Retrieval Result</h3>\n" queryfield = "querystring" cmd = "expand" queryimages=form[queryfield].value s.sendcmd(cmd+" "+str(resultsstep)+" "+queryimages) msg=s.getline() tokens=re.split(" ",msg) if(tokens[0] == "notextinformation"): result=result+"No images matched your query: "+querystring result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,queryfield,queryimages,resultsstep) return result # ---------------------------------------------------------------------- # process a query using text- or metainformation from the text input # field. The query type is set to metaquery when the search string has # a leading "META " # This works identical as the retrieve function # ---------------------------------------------------------------------- def processTextQuery(form): # Check if it's meta or text # It's meta either if there's only the metafeature or it has a leading "META " hasmeta = "metafeature" in settings.distances hastext = "textfeature" in settings.distances querystring = form["textquerystring"].value if (hasmeta and (not hastext or querystring[:5] == "META ")): if(querystring[:5] == "META "): querystring = querystring[5:] querytype = "metaquerystring" result="<h3>Metatag-based retrieval result</h3>\n" s.sendcmd("metaretrieve +"+querystring) else: querytype = "textquerystring" result="<h3>Text-based retrieval result</h3>\n" s.sendcmd("textretrieve +"+querystring) msg=s.getline() tokens=re.split(" ",msg) if( (tokens[0] == "notextinformation") or (tokens[0] == "nometainformation") ): result=result+"No images matched your query: "+querystring if(querytype == "metaquerystring"): if(hastext): result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'META key1:val1,key2:val2,...'<br><br>\n" else: result=result+"<br><br>Check if the syntax is correct.<br><br>Example: 'key1:val1,key2:val2,...'<br><br>\n" result=result+"Also have a look at the help to see which keys are available.<br>\n" if(querytype == "textquerystring"): result=result+"<br>This could be an error in your syntax. Check the help for more information.<br><br>\n" else: result=result+displayResults(tokens,querytype,querystring,0) return result # ---------------------------------------------------------------------- # create the link for the "settings" at the bottom of the page # ---------------------------------------------------------------------- def adminLink(fireServer, firePort): result="" result=result+"<a name=\"#\"></a>" result=result+"<a href=\"#\" "+\ "onClick=\"window.open('"+config.fireurl+"?server="+ \ fireServer+"&port="+str(firePort)+"&settings=1','newwindow',"+\ "'height=600, width=600')\">settings</a>" return result #<SCRIPT LANGUAGE="javascript"> #<!-- #window.open ('titlepage.html', 'newwindow', config='height=100, #width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no, #location=no, directories=no, status=no') #--> #</SCRIPT> # ---------------------------------------------------------------------- # the main program # ---------------------------------------------------------------------- # get form information in easily accessible manner form=cgi.FieldStorage() # make socket s = FIRESocket() settings=FireSettings() # see what server we have and if the webinterface specifed another one # than the one in the config file if form.has_key("server"): settings.fireServer=form["server"].value if form.has_key("port"): settings.firePort=int(form["port"].value) try: # connect to the server s.connect(settings.fireServer, settings.firePort) except: # if the server is down, give an error message # print "</pre>" message=""" <h2>FIRE Server down</h2> <p> Try again later, complain to <a href="mailto:deselaers@informatik.rwth-aachen.de">deselaers@informatik.rwth-aachen.de</a> or try other servers. """ Display(message) else: # everything is fine, connection to server is ok # try: message="" settings.get(s) # do we want to show the settings window? if(form.has_key("settings")): # see if there have been new settings defined message=settings.process(form) # generate the settings dialog message+=settings.display() # disonnect from server s.sendcmd("bye") print "</pre>" # display the settings dialog Display(message) # do we want to show the metafeatureinfo window? elif(form.has_key("metafeatureinfo")): message+=displayMetaFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) elif(form.has_key("imageinfo")): imagename=form["imageinfo"].value s.sendcmd("image "+imagename) line="" while(line != "end"): line=s.getline() tokens=re.split(" ",line) if tokens[0]=="imagefilename": message+="<img src=\""+config.imgpyurl+"?image="+tokens[1]+"\" alt=\""+tokens[1]+"\"/><br>"+"\n" elif tokens[0]=="class": message+="class: "+tokens[1]+"<br>\n" elif tokens[0]=="description": message+="description: "+tokens[1:]+"<br>\n" elif tokens[0]=="features": features=[] noffeatures=int(tokens[1]) for i in range(noffeatures): line=s.getline() tokens=re.split(" ",line) message+="<h3>"+str(i)+": "+tokens[2]+"</h3>\n<br>\n" if tokens[2].endswith(".histo.gz") \ or tokens[2].endswith(".histo") \ or tokens[2].endswith(".oldhisto.gz") \ or tokens[2].endswith(".png"): message+="<img src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\" alt=\""+tokens[2]+"\"/><br><br>\n" elif tokens[2].endswith(".vec.gz") \ or tokens[2].endswith(".oldvec.gz") \ or tokens[2].endswith(".vec") \ or tokens[2].endswith("txt") \ or tokens[2].endswith("txt.gz") \ or tokens[2].endswith("textID"): message+="<iframe src=\""+config.featureurl+"?server="+settings.fireServer+"&port="+str(settings.firePort)+"&image="+imagename+"&feature="+str(i)+"\"></iframe><br><br>\n" else: message+="not yet supported<br>\n" line=s.getline() # get end s.sendcmd("bye") Display(message) elif(form.has_key("textfeatureinfo")): message+=displayTextFeatureInfo() s.sendcmd("bye") print "</pre>" Display(message) else: # we do not want to show the settings window if(form.has_key("newFile") and form["newFile"].value=="1"): #message+=str(form["newFile"]) message+=newFile(form) elif(form.has_key("serverfile")): message+=serverFile(form) elif(form.has_key("feedback")): # result images have been selected and are part of this query if form["feedback"].value=="requery": # relevance feedback message+=feedbackretrieve(form) elif form["feedback"].value=="expandresults": # more results message+=expandQuery(form) else: # save relevances (this will not happen currently) message=saveRelevances(form) elif(form.has_key("queryImage") and form["queryImage"].value!=""): # no relevance feedback, but just one of the random images was clicked message+=retrieve(form) elif form.has_key('textquerystring'): # no relevance feedback, no query image, but a query string for text queries message+=processTextQuery(form) # now generate the remainder of the website: queryfield for meta information, random images, adminlink if("textfeature" in settings.distances or "metafeature" in settings.distances): message+=textQueryForm(settings) message+=randomImages() message+=newFileForm() message+="<p align=\"right\">"+adminLink(settings.fireServer, settings.firePort)+"</p>" message+="</form>" # disconnect from server s.sendcmd("bye") print "</pre>" # display the generated webpage Display(message) # except Exception, e: # if anything went wrong: # show the error message as readable as possible, # disconnect from the server to keep it alive # and end yourself # print "<pre>" # print "Exception: ",e # s.sendcmd("bye") # print "</pre>"
Python
#!/usr/bin/python import sys,re import filelist filelist=filelist.FileList() filelist.load(sys.argv[1]) for i in filelist: cls=i[1] fname=i[0] print fname, for j in filelist: if j[1]==cls and j[0]!=fname: print j[0], print #print filelist
Python
import re,sys,string,os class FileList: def __init__(self): self.files=[] self.classes=False self.featuredirectories=False self.descriptions=False self.path="" self.rawpath="" self.suffices=[] self.filename2idx={} def __str__(self): result="" result+="Suffices: "+str(self.suffices) result+="Files: "+str(self.files) return result def __getitem__(self,i): return self.files[i] def __getslice__(self,i): return self.files[i] def index(self,filename): if self.filename2idx.has_key(filename): return self.filename2idx[filename] else: print >>sys.stderr,filename,"not in database, returning -1" #print >>sys.stderr,self.filename2idx #print >>sys.stderr,self.files return -1 #result=-1 #for i in range(len(self.files)): # if self.files[i][0]==filename: # result=i #if result==-1: # print "filelist.py: file",filename,"not in database" #return result def load(self, filename): fl=open(filename,"r") lines=fl.readlines() for l in lines: l=re.sub("\n","",l) tokens=string.split(l) if tokens[0] == "file": f=tokens[1] if self.classes==True: cls=int(tokens[2]) if self.descriptions: desc=tokens[3:] self.files+=[[f,cls,desc]] else: self.files+=[[f,cls]] elif self.descriptions: desc=tokens[2:] self.files+=[[f,0,desc]] else: self.files+=[[f,]] elif tokens[0] == "classes": if tokens[1]=="yes": self.classes=True elif tokens[0] == "descriptions" or tokens[0] == "description": if tokens[1]=="yes": self.descriptions=True elif tokens[0] == "featuredirectories": if tokens[1]=="yes": self.featuredirectories=True elif tokens[0] == "path": self.rawpath=tokens[1] self.path=self.rawpath if self.path.startswith("this"): self.path=self.path.replace("this+","") offs=os.path.dirname(filename) cwd=os.path.realpath(os.path.curdir) self.path=offs+"/"+self.path+"/" elif tokens[0] == "suffix": self.suffices+=[tokens[1]] self.initMap() def add(self, filename, class_=0, description=""): if description == "": assert(self.descriptions == False) self.files.append([filename, class_, description]) else: assert(self.descriptions == True) self.files.append([filename, class_]) def save(self, filename): if filename=="-": f=sys.stdout else: f=open(filename,"w") print >>f,"FIRE_filelist" if self.classes: print >>f,"classes yes" if self.descriptions: print >>f,"descriptions yes" if self.featuredirectories: print >>f,"featuredirectories yes" print >>f,"path",self.rawpath for s in self.suffices: print >>f,"suffix",s for fi in self.files: print >>f, "file %s" % " ".join(map(lambda x: str(x), fi)) def initMap(self): self.filename2idx={} for i in range(len(self.files)): self.filename2idx[self.files[i][0]]=i def basenameify(self): for i in range(len(self.files)): if len(self.files[i])==3: self.files[i]=(os.path.basename(self.files[i][0]),self.files[i][1], self.files[i][2]) if len(self.files[i])==2: self.files[i]=(os.path.basename(self.files[i][0]),self.files[i][1]) if len(self.files[i])==1: self.files[i]=(os.path.basename(self.files[i][0]),) def nameWithSuffix(self, item, suffix): assert item < len(self.files) assert suffix < len(self.suffices) return self.files[item][0] + "." + self.suffices[suffix] # generator for images with full path def fullpaths(self): for image in self.files: yield os.path.join(self.rawpath, image[0]) def get_full_path_for_item(self, item, suffixidx=-1): name = os.path.join(self.rawpath, self.files[item][0]) if suffixidx > -1 and len(self.suffices) > 0: name += "." + self.suffices[suffixidx] return name
Python
#!/usr/bin/python import sys, socket, re, os, string, time sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist #----------------------------------------------------------------- s=firesocket.FIRESocket() try: if len(sys.argv) < 5: print """USAGE: makedistfiles.py <querylist> <server> <port> <suffix> [-q] """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) suffix=sys.argv[4] try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." lines=ql.readlines() lines=map(lambda line: re.sub("\n","",line), lines) ql.close() i=0 for line in lines: print i,"/",len(lines) i+=1 tokens=re.split(" ",line) file=tokens[0] cmd="savedistances "+file+" "+file+"."+suffix print "SENDING: ",cmd s.sendcmd(cmd) res=s.getline() print res sys.stdout.flush() sys.stdout.flush() if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer filelist=filelist.FileList() filelist.load(sys.argv[1]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in filelist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class SparseHistogramFeature: def __init__(self): self.bins={} self.data={} self.steps=[] self.stepSize=[] self.min=[] self.max=[] self.dim=0 self.numberofBins=0 self.counter=0 self.filename="" def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_sparse_histogram" print >>f,"# sparse histogram file for FireV2" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps",reduce(lambda x,y: str(x)+" "+str(y),self.steps) print >>f,"min",reduce(lambda x,y: str(x)+" "+str(y),self.min) print >>f,"max",reduce(lambda x,y: str(x)+" "+str(y),self.max) print >>f,"bins",len(self.bins) for i in self.bins: print >>f,"data",i,self.bins[i] f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_sparse_histogram": fine=True elif line[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="bins": self.numberofBins=int(toks[1]) elif toks[0]=="data": self.bins[toks[1]]=int(toks[2]) self.data[toks[1]]=float(toks[2])/float(self.counter) else: print "Unparsed line: '"+line+"'."
Python
#------------------------------------------------------------------------------ # proxyserver implementation for communication with the web frontend and fire # server system # server must be reachable via network sockets in order to be of any use # #------------------------------------------------------------------------------ __author__ = "Jens Forster <jens.forster@rwth-aachen.de>" __version__= "0.1" from SocketServer import * from firesocket import * # Needed for stringhandling # re provides regular expressions and methods import re import string # Needed for suitable choosing of random images # hence each retrieval server will only have access to unique # part of the database import random # Needed for logging import logging #from logging.handlers import TimedRotatingFileHandler import sys import os import os.path __all__ =["FIREProxyServer", "FIREProxyHandler"] class FIREProxyServer(TCPServer): request_queque_size = 1 allow_reuse_address = True def __init__(self,server_address, retr_addrs, RequestHandlerClass,logDestination=None): TCPServer.__init__(self,server_address,RequestHandlerClass) if len(retr_addrs) == 0: raise RuntimeError, "no retrieval servers spezified" else: self.retr_addrs = retr_addrs self.retr_sock = [] # initializing loggin system self.log = self._server_log(logDestination) self.log.log(logging.INFO,'Initializing proxyserver') self.log.log(logging.DEBUG,'Logging system and retrieval servers list ready') # initializing boolean values for request and server termination # and user authorization self.notBye = True # true -> web interface didn't quit yet self.notQuit = True # true -> proxy and retrieval servers still running self.notProxyquit = True # false -> proxy going down, retrieval servers will remain online self.auth = False self.sendErrorsFrom = [] # a list which will contain retrieval servers which crashed or aren't reachable anymore self.results = 0 # given results per retrieval server self.log.log(logging.INFO,"Proxyserver running on "+str(server_address)) def sendToRetrievers(self,cmd,upperBound=None): if upperBound != None: if upperBound < 0: raise RuntimeError, "no retrieval servers specified for sending, Proxyserver: method sendToRetrievers: upperBound "+str(upperBound) relevantRetr = zip(self.retr_sock,range(upperBound)) for sock,idx in relevantRetr: try: sock.sendcmd(cmd) self.log.log(logging.getLevelName("SEND "+str(self.retr_addrs[idx])),cmd) except: # iff no socket error occured until now name,port = self.retr_addrs[idx] if self.sendErrorsFrom == []: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str((name,port))+" did break" ) raise RuntimeError, "socket connection to retrieval server "+str((name,port))+" did break" elif str(name) in self.sendErrorsFrom: pass else: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str((name,port))+" did break") else: for sock,addr in zip(self.retr_sock,self.retr_addrs): try: sock.sendcmd(cmd) self.log.log(logging.getLevelName("SEND "+str(addr)),cmd) except: name,port = addr self.log.log(logging.INFO,"sendErrorsFrom: "+str(self.sendErrorsFrom)) if self.sendErrorsFrom == []: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str(addr)+" did break") raise RuntimeError, "socket connection to retrieval server "+str(addr)+" did break" elif str(name) in self.sendErrorsFrom: self.log.log(logging.DEBUG,"error in socket communication for retrieval server "+str(name)+" already known") else: self.sendErrorsFrom.append(str(name)) self.log.log(logging.CRITICAL,"socket connection to retrieval server "+str(addr)+" did break") def getFromRetrievers(self): answer = [] for sock,addr in zip(self.retr_sock,self.retr_addrs): try: ans = sock.getline() except: self.log.log(logging.CRITICAL,"retrieval server "+str(addr)+" doesn't respond") name,port = addr self.sendErrorsFrom.append(str(name)) raise RuntimeError, "retrieval server "+str(addr)+" didn't respond in method getFromRetrievers" answer.append(ans) self.log.log(logging.getLevelName("RECV "+str(addr)),ans) return answer def handle_request(self): """Handle one request in terms of one connection possibly containing several actions, possibly blocking.""" errorCode = 0 try: request, client_address = self.get_request() self.log.log(logging.INFO,"client "+str(client_address)+" connected") except: self.notQuit = False self.log.log(logging.ERROR,"an error occured during client's connection attempt") self.log.log(logging.ERROR,"maybe the socket/pipe did break or there are network problems") self.log.log(logging.ERROR,"proxyserver shutting down (retrieval server system may still be online)") try: request.close() self.socket.close() except: pass errorCode = 1 return errorCode else: try: for serverNum in range(len(self.retr_addrs)): serverNum_sock = FIRESocket() self.retr_sock.append(serverNum_sock) except: self.notQuit = False self.log.log(logging.ERROR,"couldn't create necessary network sockets for communication with retrieval servers") self.log.log(logging.ERROR,"proxyserver shutting down (retrieval server system may still be online)") request.close() self.socket.close() while self.retr_sock != []: firesock = self.retr_sock.pop(0) firesock.sock.close() del firesock errorCode = 2 return errorCode else: self.log.log(logging.DEBUG,"network sockets for communication with retrieval servers created") if self.verify_request(request, client_address): try: self.process_request(request, client_address) return errorCode except RuntimeError, msg: self.handle_error(request,msg) errorCode = 3 return errorCode except: self.handle_error(request,"an error involving networksockets or an unknown error occured") errorCode = 3 return errorCode def process_request(self , request, client_addr): self.finish_request(request, client_addr) try: self.close_request(request) except: pass def close_request(self, client): client.close() self.log.log(logging.INFO,"client disconnected") self.auth = False # the network sockets designated for communication with retrieval servers # will only be closed if bye, quit or an error are encountered if self.notQuit: self.sendToRetrievers("bye") while self.retr_sock != []: firesock = self.retr_sock.pop(0) firesock.sock.close() del firesock def serve(self): self.log.log(logging.INFO,"proxy handling requests") # iff the error code is True no error occured while handling errorCode = 0 while self.notQuit and self.notProxyquit : errorCode = self.handle_request() self.log.log(logging.DEBUG,"errorCode "+str(errorCode)) if errorCode == 0: self.server_close() else: logging.shutdown() def server_close(self): # no auth necessary due to prior authentification if self.notProxyquit: self.log.log(logging.INFO,"sending shutdown signal to retrieval servers") self.sendToRetrievers("quit") self.socket.close() # closing and deleting network sockets while self.retr_sock != []: sock = self.retr_sock.pop(0) sock.sock.close() del sock if self.notProxyquit: self.log.log(logging.INFO,"proxyserver and retrieval servers stopped") else: self.log.log(logging.INFO,"proxyserver stopped, retrieval servers running") self.log.log(logging.DEBUG,"shutting logging system down") logging.shutdown() # printing the error message in to the logging file, closing connection to all retrieval servers # and shutting down def handle_error(self,request,msg): self.notQuit = False self.log.log(logging.ERROR,"an error occured while handling requests") self.log.log(logging.ERROR,"for further information view the log file") self.log.log(logging.DEBUG,msg) self.log.log(logging.ERROR,"shutting proxyserver down") request.close() self.sendToRetrievers("bye") self.socket.close() while self.retr_sock != []: sock = self.retr_sock.pop(0) sock.sock.close() del sock del self.retr_sock # logging.shutdown() # Note that _server_log will always return a logger which will always log global statements to stdout # and if intended will log everything to a file depending on the message's importance level def _server_log(self,logDestination): if logDestination == None: location = None else: # exists is only needed if in future an other file logger should be used # that doesn't check fileexistance location, exists = self._logFilehandling(logDestination) # Setting up the logging System # The root logger shall log to stdout, all debug msg will be found in the files # Adding new message levels to the logging system # DEBUG (10) and NOTSET (0) needn't to be altered logging.addLevelName(1020,"CRITICAL") logging.addLevelName(1010,"ERROR") logging.addLevelName(1005,"WARNING") logging.addLevelName(1000,"INFO") logging.addLevelName(11,"RECV (Web/Bash)") logging.addLevelName(12,"SEND (Web/Bash)") logging.INFO = 1000 logging.ERROR = 1010 logging.CRITICAL = 1020 logging.WARNING = 1005 # so the levels 13 up to 999 are free for retrieval servers # because every server needs two numbers this logging system is capable of 493 retrieval servers # now levels for the retrieval servers are added # they are formated as SEND/RECV (IP-Address/Name) level = 13 for addrs in self.retr_addrs: logging.addLevelName(level,"SEND "+str(addrs)) logging.addLevelName(level+1,"RECV "+str(addrs)) level += 2 # now configurating the root logger which will log only to stdout sys.stdout = sys.stderr root = logging.getLogger('') root.setLevel(logging.DEBUG) console = logging.StreamHandler(sys.stdout) console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)-10s %(message)s','%a, %d-%m-%Y %H:%M:%S') console.setFormatter(formatter) root.addHandler(console) # setting up the main file logger if location != None: # when = 'midnight' # filesPerDay = 1 # backUpCount = 7 # file = TimedRotatingFileHandler(location,when,filesPerDay,backUpCount) if exists: file = logging.FileHandler(location,'a') else: file = logging.FileHandler(location,'w') file.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(levelname)-6s %(message)s','%a, %d-%m-%Y %H:%M:%S') file.setFormatter(formatter) root.addHandler(file) return root def _logFilehandling(self,logDestination): if logDestination == "default": cwd = os.getcwd() # determinating whether mac, unix/linux or windows if os.name in ["mac","nt","posix"]: if os.name == "nt": # windows os osPathTag = "\\" else: # unix/linux os or macintosch osPathTag = "/" try: # checking whether dir exists location = cwd+osPathTag+"fireproxylogs" exist = os.path.isdir(location) if not exist: os.mkdir(location) location += osPathTag+"proxylog" del exist del osPathTag except: raise RuntimeError, "error initalizing logging system (default logging location)" else: raise RuntimeError, "OS not supported for logging" del cwd # iff the user specified a storing location # outer if-clause else: # if only a directory is given (logDestination must be terminated by the os's # path separator (e.g / on linux \ on windows os)) default logfile name will be used head,tail = os.path.split(logDestination) osType = os.name if osType in ["mac","posix"]: osPathTag = "/" elif osType == "nt": osPathTag = "\\" else: raise RuntimeError, "OS not supported for logging" # checking whether a path name is given if head != "": # checking whether the user set all path separators' right head = os.path.normcase(head) head = os.path.normpath(head) # figuring out whether the supplied directories exist and # if not which have to be created if not os.path.isdir(head): dirToCreate = [head] newHead, newTail = os.path.split(head) while newTail != "" and (not os.path.isdir(newHead)): dirToCreate.append(newHead) newHead, newTail = os.path.split(newHead) while dirToCreate != []: os.mkdir(dirToCreate.pop()) del newHead del newTail # path is valid now checking if a filename was supplied if tail != "": location = logDestination else: location = logDestination+osPathTag+"proxylog" del dirToCreate # no path given by the user # tail must be != "" in this case otherwise it would be the default case else: # assuming current workdirectory was intended cwd = os.getcwd() location = cwd+osPathTag+tail del osPathTag del osType del head del tail # Outer If Clause ends here # testing if the file exist or not exists = True try: file = open(location,'r+') except IOError: exists = False else: file.close() return (location,exists) # Overidden to be useless, because this proxy shall quit when all retrievers quit def serve_forever(self): pass class FIREProxyHandler(StreamRequestHandler): def __init__(self, request, client_addr, server): StreamRequestHandler.__init__(self,request, client_addr, server) def sendToWeb(self,msg): self.wfile.write(msg+"\r\n") self.server.log.log(logging.getLevelName("SEND (Web/Bash)"),msg) def _validateSettings(self,settings): self.server.log.log(logging.DEBUG,"valSet Argu:"+repr(settings)) leng = len(settings) self.server.log.log(logging.DEBUG,"len: "+repr(leng)) if leng: if settings[0][0] != "filelist": retur = (False,"Settingsstream starts with wrong keyword") else: retur = (True, "") if leng > 1: lenSingle = map(lambda single: len(single),settings) boolList = map(lambda single: single == lenSingle[0],lenSingle) if not (reduce(lambda fst,snd: fst == snd,boolList)): retur = (False,"At least one retrieval server didn't send complete settings") # Fine all retrieval servers did send there complete settings # or all made the same mistake :D lenSetting = lenSingle[0] # deleting helper variables del boolList # checking rest for idx in range(lenSetting): if (idx != 1): for jdx in range(leng): if (settings[0][idx] != settings[jdx][idx]): # settings differ and singaling it return (False,"settings of servers "+str(0)+" and "+str(jdx)+" differ in "+ settings[0][idx]+" "+settings[jdx][idx]) else: retur = (True,"") return retur else: return (False,"no info information at all received") def setup(self): StreamRequestHandler.setup(self) error = False try: for retr, addr in zip(self.server.retr_sock,self.server.retr_addrs): name, port = addr try: retr.connect(name,port) self.server.log.log(logging.DEBUG,"connection to retrival server "+str(addr)+" established") except: # sending error message to web frontend self.sendToWeb("failure "+str(name)+" down") self.server.sendErrorsFrom.append(str(name)) # closing error = True self.server.log.log(logging.CRITICAL,"retrieval server "+str(addr)+" not reachable") except: pass else: if error: self.finish() raise RuntimeError, "some of the retrieval servers arent't reachable via network" else: self.server.notBye = True # signal: connection to retrieval servers established # currently unix specific linefeed self.server.log.log(logging.INFO,"connection to retrieval server system established") def handle(self): retrieveAndMetaCommands = ["retrieve","expand","retrieveandsaveranks","metaretrieve","metaexpand","textretrieve","textexpand"] # handling actions until "bye", "quit" or doomsday while self.server.notBye and self.server.notQuit: webMsg = self.rfile.readline() self.server.log.log(logging.DEBUG,webMsg) webMsg = re.sub("[\r\n\t\v\f]","",webMsg) self.server.log.log(logging.getLevelName("RECV (Web/Bash)"),webMsg) webKeyS = string.split(webMsg) keyWord = webKeyS.pop(0) # grabbing the very first element if keyWord == "info": self.server.sendToRetrievers("info") answer = self.server.getFromRetrievers() # convert list of single strings in usable format # e.g ["hello world","how do you do?"] becomes # [['hello','world'],['how','do','you','do?']] settings = map(lambda strin: string.split(strin),answer) bool, comment = self._validateSettings(settings) if bool: sum = 0 # summing up total databank size for idx in range(len(settings)): sum += int(settings[idx][1]) settings[0][1] = sum self.server.results = int(settings[0][3]) self.sendToWeb(re.sub("[[,'\]]","",str(settings[0]))) # deleting helper variables del bool del answer del comment del settings else: self.finish() raise RuntimeError, "handle():"+comment elif keyWord == "password": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) bool = True idx = 0 while bool and idx < len(answer): if tokens[idx][0] != "ok": bool = False idx += 1 if not bool: self.sendToWeb(answer[idx-1]) self.server.auth = False else: self.sendToWeb("ok") self.server.auth = True # deleting helper variables del answer del tokens del idx del bool elif keyWord == "bye": self.server.notBye = False elif keyWord == "quit": self.server.notBye = False if self.server.auth: self.server.notQuit = False else: self.server.sendToRetrievers("bye") elif keyWord in retrieveAndMetaCommands: self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() self.server.log.log(logging.DEBUG,"answer(handle()): "+repr(answer)) # converting retrieval servers' answers from strings to list of # strings like above and afterwards merging all such lists into # one if keyWord in ["metaretrieve","metaexpand","textretrieve","textexpand"]: listed = map(lambda string: re.split("[ :]",string),answer) else: listed = map(lambda strin: string.split(strin),answer) listed = reduce(lambda fst,snd: fst+snd,listed) if "nometainformation" in listed: self.sendToWeb("nometainformation") elif "notextinformation" in listed: self.sendToWeb("notextinformation") elif "" in listed: self.server.log.log(logging.INFO,"at least one retrival server answered with an empty string") self.server.log.log(logging.ERROR,"retrival aborted") elif not self.server.results == 0: # for sorting purposes changing data structure to a list of tupels # consistent of distance as a float and filename as a string toSort = [(float(listed[i+1]),listed[i]) for i in range(0,len(listed),2)] toSort.sort() toSort.reverse() retrievalString = "" for tup in toSort[:self.server.results]: dist, name = tup if keyWord in ["metaretrieve","metaexpand","textretrieve","textexpand"]: retrievalString += name+":"+str(dist) else: retrievalString += name+" "+str(dist) retrievalString += " " # removing trailing blank retrievalString = re.sub(" $","",retrievalString) self.sendToWeb(retrievalString) #deleting helper variables del toSort del retrievalString else: self.server.log.log(logging.INFO,"Proxyserver assumes that settings for results equals 0") self.server.log.log(logging.INFO,"Please use setresults to set results to an usefull value") self.server.log.log(logging.DEBUG,"possible mismath between retrieval servers settings and proxyserver") self.server.log.log(logging.ERROR,"retrieval aborted") # deleting helper variables del answer del listed elif keyWord == "help": self.server.sendToRetrievers(webMsg,1) answer = self.server.retr_sock[0].getline() ans = string.split(answer) try: ans.remove("filelist") except: pass answer = "proxy only: quitproxy ||normal fire commands: " for cmd in ans: answer += cmd answer += " " answer += "||not supported in proxy mode: filelist" self.sendToWeb(answer) del answer elif keyWord == "savedistances": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() fst = answer[0] bool = True for name in answer: if name != fst: bool = False if not bool: self.finish() raise RuntimeError,"distance filenames differ" self.sendToWeb(fst) del answer del bool del fst elif keyWord == "random": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) tokenList = reduce(lambda fst,snd:fst+snd,tokens) # choosing randomly images from all random images # because every retrieval server only accesses an unique database # subset randomImg = random.sample(tokenList,self.server.results) self.sendToWeb(re.sub("[[',\]]","",str(randomImg))) # deleting helper variables del answer del tokens del tokenList del randomImg elif keyWord == "saverelevances": self.server.sendToRetrievers(webMsg) elif keyWord in ["setscoring","setresults","setextensions","setdist","setweight"]: self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) keyToken = re.sub("set","",keyWord) # checking if all retrieval servers accepted new settings # first checking keyword boolList = map(lambda list: list[0] == keyToken,tokens) boolAll = reduce(lambda fst,snd:fst == snd,boolList) # checking iff snd argument must be checked # in case it will be "=" testing is omitted if keyToken in ["weight","dist"]: sndArg = tokens[0][1] boolList = map(lambda list: list[1] == sndArg,tokens) boolSnd = reduce(lambda fst,snd: fst == snd,boolList) boolAll = boolAll and boolSnd del boolSnd # checking third argument trdArg = tokens[0][2] boolList = map(lambda list: list[2] == trdArg,tokens) boolTrd = reduce(lambda fst,snd:fst == snd,boolList) boolAll = boolAll and boolTrd if boolAll: self.sendToWeb(answer[0]) if keyToken == "results" and tokens[0][0] != "Invalid": self.server.results = int(tokens[0][2]) else: self.server.sendToRetrievers(keyWord,1) alterMsg = self.server.retr_sock[0].getline() self.sendToWeb(alterMsg) del alterMsg del boolAll del boolTrd del boolList del answer del tokens elif keyWord == "listfiles": self.server.sendToRetrievers(webMsg) answer = self.server.getFromRetrievers() result = "" for idx in range(len(answer)): result += answer[idx] result += " " # deleting trailing blank result = re.sub(" $","",result) self.sendToWeb(result) del answer del result elif keyWord == "class": self.server.sendToRetrievers(webMsg) self.server.log.log(logging.INFO,webMsg+" send") answer = self.server.getFromRetrievers() tokens = map(lambda strin: string.split(strin),answer) tokens = reduce(lambda fst,snd: fst+snd,tokens) # since retrieval servers will only return a single value # it is only neccessary to destinguish the three possible modes of the class command # for error handling # do all retrieval servers have classes or don't they if "yes" in tokens: for item in tokens: if "yes" != item: self.finish() raise RuntimeError, "not all retrieval servers do have classes" self.sendToWeb("yes") elif "no" in tokens: for item in tokens: if "no" != item: self.finish() raise RuntimeError, "not all retrieval servers don't have classes" self.sendToWeb("no") else: try: intList = [] for item in tokens: intItem = int(item) if intItem >= 0: intList.append(intItem) except: self.finish() raise RuntimeError, "neiter yes/no nor numbers were returned for classes" else: boolList = map(lambda it: intList[0]==it,intList) booL = reduce(lambda fst, snd: fst and snd,boolList) if booL: self.sendToWeb(str(intList[0])) else: self.finish() raise RuntimeError, "retrieval servers classes differ" del boolList del booL del tokens del answer elif keyWord == "metafeatureinfo": self.server.sendToRetrievers(webMsg) self.server.log.log(logging.INFO,webMsg+" send") answer = self.server.getFromRetrievers() answer = map(lambda string: re.sub(" $","",string),answer) returnstring = "" for strings in answer: returnstring += strings returnstring += " " self.sendToWeb(re.sub(" $","",returnstring)) del answer del returnstring # Note that the commands filelist is dumped on purpose # because every retrieval server accesses it's own databade subset # The interactor command is dumped too. elif keyWord in ["filelist","interactor"]: self.sendToWeb(keyWord+" is not avaible since fireproxy is in use") elif keyWord == "quitproxy": self.server.notBye = False self.server.notProxyquit = False else: self.sendToWeb("Unknown command: "+webMsg) del retrieveAndMetaCommands del webKeyS del webMsg
Python
#!/usr/bin/python from string import split, lower, strip from random import shuffle import sys import os from os.path import join, getsize ARCH=os.environ["ARCH"] # returns the string after a certain option string def getStringAfter(name, array, default): for i in range(len(array)): if array[i] == name: if (len(array) == i+1): return default else: return array[i+1] return default def usage(commandline): print "note: before you use this program make \"make all\" in the firedirectory. " print commandline[0], "(-np|-npfromdb|-ndb|-ndbfromp|-showf|-e|-h) [options]" print print "mandatory options (choose exactly one of them):" print " -h shows this help" print " -showf show all possible features that can be extracted" print " -e extracts features. options: -limages -ldb -ld -selectf " print " -p -db -d -c -f -q -n" print " -np creates a new purefiles file using the filenames of the " print " files in the directory. options: -d -p" print " -npfromdb creates a new purefiles file from the data of the dbfile." print " options: -d -db -p" print " -ndb creates a new database file using the filenames of the " print " files in the directory. options: -d -db" print " -ndbfromp creates a new database file from the data of the purefiles " print " file. options: -d -p -db" print print "options:" print " -d dir directory of where the files are. default: ." print " -p path path of an [existing] purefiles file. default: purefiles" print " -db path path of an [existing] database file. default: list" print " -c path configfile that shall be used. " print " default:", os.path.dirname(sys.argv[0]) + "/features.conf" print " -f dir directory where fire resides. " print " default:", os.path.dirname(sys.argv[0]) + "../../bin/"+ARCH+"/" print " -q (day|week)" print " put all jobs into the queuingsystem. default: no queuing" print " -n name of the jobs in the queue. default: extractor" print " -selectf feature1 [feature2 [... [featureN]]" print " extracts only feature1 ... featureN of the config file" print " -v verbose" print " -limages image1 [image2 [... [imageN]]" print " extracts features of image1 ... imageN only" print " -ldb extracts the images from the dbfile" print " (hint: it is smarter to create a db file first, using" print " -ndb or -ndbfromp)" print " -ld extracts the images of the directory" print " (hint: it is smarter to create a purefiles file first," print " using -np or -npfromdb)" class Extractor: def __init__(self): self.datadir = "." self.purefiles = "purefiles" self.dbfile = "list" self.progdir = os.path.dirname(sys.argv[0]) # path of the tool self.firedir = self.progdir + "/../../bin/"+ARCH+"/" self.config = "features.conf" self.extensionlist = ["jpg", "png", "gif", "jpeg", "tif", "tiff"] self.images = [] self.features = {} self.selectedFeatures = [] self.queue = None self.name = "extractor" # gets for the attributes def setPurefiles(self, new): self.purefiles = new def setDBFile(self, new): self.dbfile = new def setDatadir(self, new): self.datadir = new def setFiredir(self, new): self.firedir = new def setConfigfile(self, new): self.config = new def setExtensionlist(self, newl): self.extensionlist = newl def setQueue(self, new): self.queue = new def setName(self, new): self.name = new # printing def printInfo(self): print "config info of extractor" print "datadir", self.datadir print "purefiles", self.purefiles print "dbfile", self.dbfile print "progdir", self.progdir print "firedir", self.firedir print "configfile", self.config print "extensionlist", self.extensionlist # prints available features def printFeatures(self): for feature in self.features.keys(): print feature, self.features[feature] def printImages(self): if self.images == []: print "error: no images loaded." else: print "images:" for image in self.images: print image # loading # load images from the directory def loadImagesFromDir(self): print "loading images from directory." self.images = [] for root, dirs, files in os.walk(self.datadir): for file in files: if self.checkExtension(file): if (root == self.datadir): self.images.append(file) else: self.images.append(root[len(self.datadir)+1:] + "/" + file) if self.images == []: print "error: no images found." # loads images from database file # (does not consider path information of the db file yet) def loadImagesFromDB(self): print "loading images from dbfile." f = open(self.dbfile, "r") lines = f.readlines() f.close() for line in lines: if strip(split(line)[0]) == "file": self.images.append(strip(split(line)[1])) #print "file:", strip(split(line)[1]) if self.images == []: print "error: no images found." # loads features from the config file def loadFeatures(self): print "loading features file." try: f = open(self.config, "r") except IOError: print "warning: no specific config file found. I try the one in the tooldir." f = open(self.progdir + "/features.conf") lines = f.readlines() f.close() for line in lines: if line[0] == "#": #print "comment: ", line pass elif len(strip(line)) < 1: pass else: key = strip(split(line)[0]) #print "key", key feature = strip(line)[len(key)+1:] #print "feature", feature self.features[key] = feature # loads an existing purefiles list def loadImagesFromPurefiles(self): print "loading images from purefiles." self.images = [] file = open(self.purefiles, 'r') lines = file.readlines() file.close() num = len(lines) print "info: number of images =", num for line in lines: self.images.append(strip(line)) # loads images from commandline def loadImagesFromCommandline(self, argv): self.images = [] print "loading images from commandline." catch = False for command in argv: #print "command:", command if command == "-limages": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: self.images.append(command) if self.images == []: print "error: no images found" def loadSelectedFeaturesFromCommandline(self, argv): self.selectedFeatures = [] print "loading selected features from commandline." catch = False for command in argv: #print "command:", command if command == "-selectf": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: #print "added", command self.selectedFeatures.append(command) if self.selectedFeatures == []: print "error: no features found" # checking # check if image file has a correct extension def checkExtension(self, filename): extension = split(filename, ".")[-1] if lower(extension) in self.extensionlist: return True return False def pureFileExists(self): try: f = open(self.purefiles, "r") except IOError: return False else: return True # writing # writes the purefilesfile def writePurefiles(self): print "writing purefiles file." if self.images == []: print "error: cannot write a purefiles file, because image list is empty." else: f = open(self.purefiles, "w") for image in self.images: f.write(image) f.write("\n") f.close() # creates the database file def writeDBFile(self): # possible feature: dbfiles with feature directories? # possible feature: non recursive traversion print "writing dbfile." f = open(self.dbfile, "w") f.write("FIRE_filelist\n") f.write("classes no\n") f.write("descriptions no\n") f.write("featuredirectories no\n") f.write("path this\n") for file in self.images: f.write("file ") f.write(file) f.write("\n") f.close() # selection # selects features def selectFeatures(self): if self.selectedFeatures == []: print "error: there are no features to select" print "hint: maybe wrong spelling?" temp = {} for key in self.features.keys(): #print "key", key if key in self.selectedFeatures: temp[key] = self.features[key] self.features = temp # extraction # extracts all features for all images def extractFeatures(self): for key in self.features.keys(): self.extractFeature(key) # extracts one feature for all images def extractFeature(self, feature): if self.images != []: commandline = self.firedir + self.features[feature] + " --images" for image in self.images: commandline = commandline + " " + image else: if not self.pureFileExists(): print "error: purefiles file not existing" print "hint: create with -np a new file or use -limage, -ldb or -ld to load images" return False else: #self.printInfo() #print "self.features[feature]", self.features[feature] #self.printFeatures() commandline = self.firedir + self.features[feature] + " --filelist " + self.purefiles print "commandline:", commandline if self.queue == "day": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 8:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) elif self.queue == "week": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 24:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) else: os.system(commandline) if __name__ == "__main__": if "-h" in sys.argv: usage(sys.argv) else: e = Extractor() # adjusting file locations if "-p" in sys.argv: e.setPurefiles(getStringAfter("-p", sys.argv, None)) if "-db" in sys.argv: e.setDBFile(getStringAfter("-db", sys.argv, None)) if "-d" in sys.argv: e.setDatadir(getStringAfter("-d", sys.argv, None)) if "-c" in sys.argv: e.setConfigfile(getStringAfter("-c", sys.argv, None)) if "-f" in sys.argv: e.setFiredir(getStringAfter("-f", sys.argv, None)) if "-q" in sys.argv: e.setQueue(getStringAfter("-q", sys.argv, None)) if "-n" in sys.argv: e.setName(getStringAfter("-n", sys.argv, None)) ## maybe later # if "-el" in sys.argv # e.setExtensionlist(...) if "-v" in sys.argv: e.printInfo() if "-np" in sys.argv: e.loadImagesFromDir() e.writePurefiles() elif "-npfromdb" in sys.argv: e.loadImagesFromDB() e.writePurefiles() elif "-ndb" in sys.argv: e.loadImagesFromDir() e.writeDBFile() elif "-ndbfromp" in sys.argv: e.loadImagesFromPurefiles() e.writeDBFile() elif "-showf" in sys.argv: e.loadFeatures() e.printFeatures() elif "-e" in sys.argv: # loading the images (if no purefiles file is used) if "-limages" in sys.argv: e.loadImagesFromCommandline(sys.argv) if "-v" in sys.argv: e.printImages() elif "-ldb" in sys.argv: e.loadImagesFromDBFile() elif "-ld" in sys.argv: e.loadImagesFromDatadir() else: pass e.loadFeatures() if "-selectf" in sys.argv: e.loadSelectedFeaturesFromCommandline(sys.argv) e.selectFeatures() if "-v" in sys.argv: print "selected features:" e.printFeatures() e.extractFeatures() else: print "wrong usage. use -h for help."
Python
#!/usr/bin/python from string import split, lower, strip from random import shuffle import sys import os from os.path import join, getsize ARCH=os.environ["ARCH"] # returns the string after a certain option string def getStringAfter(name, array, default): for i in range(len(array)): if array[i] == name: if (len(array) == i+1): return default else: return array[i+1] return default def usage(commandline): print "note: before you use this program make \"make all\" in the firedirectory. " print commandline[0], "(-np|-npfromdb|-ndb|-ndbfromp|-showf|-e|-h) [options]" print print "mandatory options (choose exactly one of them):" print " -h shows this help" print " -showf show all possible features that can be extracted" print " -e extracts features. options: -limages -ldb -ld -selectf " print " -p -db -d -c -f -q -n" print " -np creates a new purefiles file using the filenames of the " print " files in the directory. options: -d -p" print " -npfromdb creates a new purefiles file from the data of the dbfile." print " options: -d -db -p" print " -ndb creates a new database file using the filenames of the " print " files in the directory. options: -d -db" print " -ndbfromp creates a new database file from the data of the purefiles " print " file. options: -d -p -db" print print "options:" print " -d dir directory of where the files are. default: ." print " -p path path of an [existing] purefiles file. default: purefiles" print " -db path path of an [existing] database file. default: list" print " -c path configfile that shall be used. " print " default:", os.path.dirname(sys.argv[0]) + "/features.conf" print " -f dir directory where fire resides. " print " default:", os.path.dirname(sys.argv[0]) + "../../bin/"+ARCH+"/" print " -q (day|week)" print " put all jobs into the queuingsystem. default: no queuing" print " -n name of the jobs in the queue. default: extractor" print " -selectf feature1 [feature2 [... [featureN]]" print " extracts only feature1 ... featureN of the config file" print " -v verbose" print " -limages image1 [image2 [... [imageN]]" print " extracts features of image1 ... imageN only" print " -ldb extracts the images from the dbfile" print " (hint: it is smarter to create a db file first, using" print " -ndb or -ndbfromp)" print " -ld extracts the images of the directory" print " (hint: it is smarter to create a purefiles file first," print " using -np or -npfromdb)" class Extractor: def __init__(self): self.datadir = "." self.purefiles = "purefiles" self.dbfile = "list" self.progdir = os.path.dirname(sys.argv[0]) # path of the tool self.firedir = self.progdir + "/../../bin/"+ARCH+"/" self.config = "features.conf" self.extensionlist = ["jpg", "png", "gif", "jpeg", "tif", "tiff"] self.images = [] self.features = {} self.selectedFeatures = [] self.queue = None self.name = "extractor" # gets for the attributes def setPurefiles(self, new): self.purefiles = new def setDBFile(self, new): self.dbfile = new def setDatadir(self, new): self.datadir = new def setFiredir(self, new): self.firedir = new def setConfigfile(self, new): self.config = new def setExtensionlist(self, newl): self.extensionlist = newl def setQueue(self, new): self.queue = new def setName(self, new): self.name = new # printing def printInfo(self): print "config info of extractor" print "datadir", self.datadir print "purefiles", self.purefiles print "dbfile", self.dbfile print "progdir", self.progdir print "firedir", self.firedir print "configfile", self.config print "extensionlist", self.extensionlist # prints available features def printFeatures(self): for feature in self.features.keys(): print feature, self.features[feature] def printImages(self): if self.images == []: print "error: no images loaded." else: print "images:" for image in self.images: print image # loading # load images from the directory def loadImagesFromDir(self): print "loading images from directory." self.images = [] for root, dirs, files in os.walk(self.datadir): for file in files: if self.checkExtension(file): if (root == self.datadir): self.images.append(file) else: self.images.append(root[len(self.datadir)+1:] + "/" + file) if self.images == []: print "error: no images found." # loads images from database file # (does not consider path information of the db file yet) def loadImagesFromDB(self): print "loading images from dbfile." f = open(self.dbfile, "r") lines = f.readlines() f.close() for line in lines: if strip(split(line)[0]) == "file": self.images.append(strip(split(line)[1])) #print "file:", strip(split(line)[1]) if self.images == []: print "error: no images found." # loads features from the config file def loadFeatures(self): print "loading features file." try: f = open(self.config, "r") except IOError: print "warning: no specific config file found. I try the one in the tooldir." f = open(self.progdir + "/features.conf") lines = f.readlines() f.close() for line in lines: if line[0] == "#": #print "comment: ", line pass elif len(strip(line)) < 1: pass else: key = strip(split(line)[0]) #print "key", key feature = strip(line)[len(key)+1:] #print "feature", feature self.features[key] = feature # loads an existing purefiles list def loadImagesFromPurefiles(self): print "loading images from purefiles." self.images = [] file = open(self.purefiles, 'r') lines = file.readlines() file.close() num = len(lines) print "info: number of images =", num for line in lines: self.images.append(strip(line)) # loads images from commandline def loadImagesFromCommandline(self, argv): self.images = [] print "loading images from commandline." catch = False for command in argv: #print "command:", command if command == "-limages": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: self.images.append(command) if self.images == []: print "error: no images found" def loadSelectedFeaturesFromCommandline(self, argv): self.selectedFeatures = [] print "loading selected features from commandline." catch = False for command in argv: #print "command:", command if command == "-selectf": #print "image tag found." catch = True elif command[0] == "-": #print "end tag found." catch = False else: if catch: #print "added", command self.selectedFeatures.append(command) if self.selectedFeatures == []: print "error: no features found" # checking # check if image file has a correct extension def checkExtension(self, filename): extension = split(filename, ".")[-1] if lower(extension) in self.extensionlist: return True return False def pureFileExists(self): try: f = open(self.purefiles, "r") except IOError: return False else: return True # writing # writes the purefilesfile def writePurefiles(self): print "writing purefiles file." if self.images == []: print "error: cannot write a purefiles file, because image list is empty." else: f = open(self.purefiles, "w") for image in self.images: f.write(image) f.write("\n") f.close() # creates the database file def writeDBFile(self): # possible feature: dbfiles with feature directories? # possible feature: non recursive traversion print "writing dbfile." f = open(self.dbfile, "w") f.write("FIRE_filelist\n") f.write("classes no\n") f.write("descriptions no\n") f.write("featuredirectories no\n") f.write("path this\n") for file in self.images: f.write("file ") f.write(file) f.write("\n") f.close() # selection # selects features def selectFeatures(self): if self.selectedFeatures == []: print "error: there are no features to select" print "hint: maybe wrong spelling?" temp = {} for key in self.features.keys(): #print "key", key if key in self.selectedFeatures: temp[key] = self.features[key] self.features = temp # extraction # extracts all features for all images def extractFeatures(self): for key in self.features.keys(): self.extractFeature(key) # extracts one feature for all images def extractFeature(self, feature): if self.images != []: commandline = self.firedir + self.features[feature] + " --images" for image in self.images: commandline = commandline + " " + image else: if not self.pureFileExists(): print "error: purefiles file not existing" print "hint: create with -np a new file or use -limage, -ldb or -ld to load images" return False else: #self.printInfo() #print "self.features[feature]", self.features[feature] #self.printFeatures() commandline = self.firedir + self.features[feature] + " --filelist " + self.purefiles print "commandline:", commandline if self.queue == "day": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 8:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) elif self.queue == "week": queueline = "qsubmit -n " + self.name + "." + feature + " -m 0.4 -t 24:00:00 -bash " print "job", queueline + commandline os.system(queueline + commandline) else: os.system(commandline) if __name__ == "__main__": if "-h" in sys.argv: usage(sys.argv) else: e = Extractor() # adjusting file locations if "-p" in sys.argv: e.setPurefiles(getStringAfter("-p", sys.argv, None)) if "-db" in sys.argv: e.setDBFile(getStringAfter("-db", sys.argv, None)) if "-d" in sys.argv: e.setDatadir(getStringAfter("-d", sys.argv, None)) if "-c" in sys.argv: e.setConfigfile(getStringAfter("-c", sys.argv, None)) if "-f" in sys.argv: e.setFiredir(getStringAfter("-f", sys.argv, None)) if "-q" in sys.argv: e.setQueue(getStringAfter("-q", sys.argv, None)) if "-n" in sys.argv: e.setName(getStringAfter("-n", sys.argv, None)) ## maybe later # if "-el" in sys.argv # e.setExtensionlist(...) if "-v" in sys.argv: e.printInfo() if "-np" in sys.argv: e.loadImagesFromDir() e.writePurefiles() elif "-npfromdb" in sys.argv: e.loadImagesFromDB() e.writePurefiles() elif "-ndb" in sys.argv: e.loadImagesFromDir() e.writeDBFile() elif "-ndbfromp" in sys.argv: e.loadImagesFromPurefiles() e.writeDBFile() elif "-showf" in sys.argv: e.loadFeatures() e.printFeatures() elif "-e" in sys.argv: # loading the images (if no purefiles file is used) if "-limages" in sys.argv: e.loadImagesFromCommandline(sys.argv) if "-v" in sys.argv: e.printImages() elif "-ldb" in sys.argv: e.loadImagesFromDBFile() elif "-ld" in sys.argv: e.loadImagesFromDatadir() else: pass e.loadFeatures() if "-selectf" in sys.argv: e.loadSelectedFeaturesFromCommandline(sys.argv) e.selectFeatures() if "-v" in sys.argv: print "selected features:" e.printFeatures() e.extractFeatures() else: print "wrong usage. use -h for help."
Python
#!/usr/bin/env python import sys,gzip class Feature: def __init__(self): self.posx=0 self.posy=0 self.scale=0 self.vec=[] class LocalFeatures: def __init__(self): self.winsize=0 self.dim=0 self.subsampling=0 self.padding=0 self.numberOfFeatures=0 self.varthreshold=0 self.zsize=0 self.filename="" self.imagesize=(0,0) self.features=[] self.selffilename="" def __getitem__(self,i): return self.features[i] def load(self,filename): f=gzip.GzipFile(filename) self.selffilename=filename for l in f: toks=l.split() if toks[0]=="FIRE_localfeatures": fine=True elif toks[0]=="winsize": self.winsize=int(toks[1]) elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="subsampling": self.subsampling=int(toks[1]) elif toks[0]=="padding": self.padding=int(toks[1]) elif toks[0]=="numberOfFeatures": self.numberOfFeatures=int(toks[1]) elif toks[0]=="varthreshold": self.varthreshold=float(toks[1]) elif toks[0]=="zsize": self.zsize=int(toks[1]) elif toks[0]=="filename": self.filename=toks[1] elif toks[0]=="imagesize": self.imagesize=(int(toks[1]),int(toks[2])) elif toks[0]=="features": if self.numberOfFeatures!=int(toks[1]): print "Weird... inconsistent number of Features and features expected in the file" elif toks[0]=="feature": f=Feature() toks.pop(0) f.posx=float(toks.pop(0)) f.posy=float(toks.pop(0)) f.scale=float(toks.pop(0)) f.vec=map(lambda x: float(x), toks) self.features+=[f] else: print "'%s' is an unknown keyword... ignoring and continuiing nonetheless."%(toks[0]) def save(self,filename): f=gzip.GzipFile(filename,"w") f.write("FIRE_localfeatures\n") f.write("winsize %d\ndim %d\nsubsampling %d\npadding %d\nnumberOfFeatures %d\nvarthreshold %d\nzsize %d\nfilename %s\nimagesize %d %d\nfeatures %d\n" % (self.winsize,self.dim,self.subsampling,self.padding,self.numberOfFeatures,self.varthreshold,self.zsize,self.filename,self.imagesize[0],self.imagesize[1],len(self.features))) for lf in self.features: f.write("feature %d %d %d " % (lf.posx,lf.posy,lf.scale)) for v in lf.vec: f.write(str(v)+" ") f.write("\n") f.close()
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class HistogramFeature: def __init__(self): self.steps=[] self.bins=[] self.min=[] self.max=[] self.stepsize=[] self.dim=0 self.counter=0 self.filename="" self.data=[] def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_histogram" print >>f,"# created with histogramfeature.py" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps"," ".join(map(lambda x: str(x),self.steps)) print >>f,"min"," ".join(map(lambda x: str(x), self.min)) print >>f,"max"," ".join(map(lambda x: str(x), self.max)) print >>f,"data"," ".join(map(lambda x: str(x), self.data)) f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_histogram": fine=True elif toks[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="data": self.bins=map(lambda x: int(x),toks[1:]) try: self.data=map(lambda x: float(x)/float(self.counter), self.bins) except: print "Error reading file:", filename,"probably division by zero, continuing anyway." else: print "Unparsed line: '"+line+"'."
Python
#!/usr/bin/python import sys #this script merges fire distance files. # # as command line parameters, arbitrary many distance files are given and # the merged distance file is printed. infiles=[] line=[] for i in sys.argv[1:]: infiles.append(open(i,"r")) line.append("") line[0]=infiles[0].readline() count=0 while(line[0]): for i in range(1,len(infiles)): line[i]=infiles[i].readline() if line[0].startswith("nofdistances"): nDist=0 nImg=0 for l in line: toks=l.split() nDist+=int(toks[2]) nImg=int(toks[1]) print "nofdistances",nImg,nDist elif not line[0].startswith("#"): print count, for l in line: toks=l.split() for i in range(1,len(toks)): print float(toks[i]), print count+=1 line[0]=infiles[0].readline()
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer querylist=filelist.FileList() filelist=filelist.FileList() filelist.load(sys.argv[1]) querylist.load(sys.argv[2]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in querylist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: if len(sys.argv) != 4: print """USAGE: querylistwqueryexpansion.py <querylist> <server> <port> """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." files=ql.readlines() ql.close() s.sendcmd("setresults 10") s.sendcmd("setextensions 2") for file in files: file=re.sub('\n','',file) cmd="retrieveandsaveranks 1030 "+file+".ranks "+file s.sendcmd(cmd) res=s.getline() print res s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback,numarray import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-f": database=sys.argv.pop(0) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-l1o": l1o=True elif argv=="-x": quit=True else: print "Unknown option:",argv print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o if database=="" or querybase=="" and not l1o: print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o sys.stdout.flush() f=filelist.FileList() f.load(database) q=filelist.FileList() if not l1o: q.load(querybase) else: q=f if not f.classes: print "Need classes in database file" sys.exit(10) if not l1o and not q.classes: print "Need classes in querybase file" sys.exit(10) s=firesocket.FIRESocket() s.connect(server,port) try: s.sendcmd("info") res=s.getline() status=re.split(" ",res) keyword=status.pop(0) dbSize=int(status.pop(0)) if dbSize!=len(f.files): print "database in retriever and database loaded are of different size:", dbSize,"!=",len(f.files) s.sendcmd("bye") time.sleep(1) sys.exit(10) print "database has",dbSize,"images." if not l1o: s.sendcmd("setresults 1"); res=s.getline() else: s.sendcmd("setresults 2"); res=s.getline() classified=0; errors=0; correct=0 no_classes=0 for qf in q.files: if qf[1]>no_classes: no_classes=qf[1] for df in f.files: if df[1]>no_classes: no_classes=df[1] no_classes+=1 print no_classes,"classes." confusionmatrix=numarray.zeros((no_classes,no_classes),numarray.Int) counter=0 for qf in q.files: counter+=1 qname=qf[0] qcls=qf[1] s.sendcmd("retrieve "+qname) res=s.getline() res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) if not l1o: if len(results)!=2: print "expected 2 tokens, got",len(results) sys.exit(10) else: if len(results)!=4: print "expected 4 tokens, got",len(results) sys.exit(10) results.pop(0) results.pop(0) returnedimage=results.pop(0) score=float(results.pop(0)) for df in f.files: if not l1o: if df[0]==returnedimage: dcls=df[1] break else: if df[0]==returnedimage and df[0]!=qname: dcls=df[1] break classified+=1 if dcls==qcls: correct+=1 else: errors+=1 confusionmatrix[dcls][qcls]+=1 print "Query "+str(counter)+"/"+str(len(q.files))+":",qname,"("+str(qcls)+") NN:",returnedimage,"("+str(dcls)+")","ER:",float(errors)/float(classified)*100 sys.stdout.flush() print "RESULT: ER:",float(errors)/float(classified)*100 print confusionmatrix time.sleep(1) if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) useX="-x" in sys.argv verbose="-v" in sys.argv try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." fileprefix="" if len(sys.argv)>4: if sys.argv[4]!="-q" and sys.argv[4]!="-x" and sys.argv[4]!="-v": fileprefix=sys.argv[4] lines=ql.readlines() # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); ql.close() classified=0 ###query images and evaluate results for line in lines: line=re.sub('\n','',line) relevant=re.split(" ",line) query=fileprefix+relevant[0] # this is the name of the query image relevant=relevant[1:] # this are the names of the images relevant to the query image cmd="retrieve +"+query s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimage=re.sub(fileprefix,"",returnedimage) returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] if verbose: print "results:",returnedimages[0],"->0", sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize param["useX"] = useX param["verbose"] = verbose def calculate(param): data = param["data"] dbSize = param["dbSize"] useX = param["useX"] verbose = param["verbose"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] if useX: g=Gnuplot.Gnuplot() g.title('PR graph') g('set data style linespoints') g('set xrange [0.0:1.0]') g('set yrange [0.0:1.0]') data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 if verbose: print returnedimages[Ri],"->",Ri, print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] if useX: g.plot(Gnuplot.Data(PRgraph,title="PRgraph current query"),Gnuplot.Data(tmpAPRgraph,title="PRgraph average")) print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [<fileprefix>] [-q] [-x] -q: quit the server after finished eval -x: show PR graph after each query on X display -v: verbose <fileprefix> should not be necessary """ else: param = {} retrieveData(param) calculate(param)
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: host=sys.argv[1] if len(sys.argv) >=3: port=int(sys.argv[2]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." s.sendcmd("listfiles") fileline=s.getline() files=string.split(fileline," ") s.sendcmd("setresults 2") s.getline() classified=0 correct=0 error=0 for file in files: if len(file)>0: cmd="retrieve +"+file s.sendcmd(cmd) res=s.getline() parts=string.split(res," ") result=parts[2] print res #get classes s.sendcmd("class "+file) qclass=s.getline() s.sendcmd("class "+result) rclass=s.getline() qc=int(qclass) rc=int(rclass) if(rc==qc): correct=correct+1 else: error=error+1 classified=classified+1 er=float(error)/float(classified)*100.0 print file+" wrong="+str(error)+" correct="+str(correct)+" classified="+str(classified)+" ER="+str(er) s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer filelist=filelist.FileList() filelist.load(sys.argv[1]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in filelist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class SparseHistogramFeature: def __init__(self): self.bins={} self.data={} self.steps=[] self.stepSize=[] self.min=[] self.max=[] self.dim=0 self.numberofBins=0 self.counter=0 self.filename="" def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_sparse_histogram" print >>f,"# sparse histogram file for FireV2" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps",reduce(lambda x,y: str(x)+" "+str(y),self.steps) print >>f,"min",reduce(lambda x,y: str(x)+" "+str(y),self.min) print >>f,"max",reduce(lambda x,y: str(x)+" "+str(y),self.max) print >>f,"bins",len(self.bins) for i in self.bins: print >>f,"data",i,self.bins[i] f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_sparse_histogram": fine=True elif line[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="bins": self.numberofBins=int(toks[1]) elif toks[0]=="data": self.bins[toks[1]]=int(toks[2]) self.data[toks[1]]=float(toks[2])/float(self.counter) else: print "Unparsed line: '"+line+"'."
Python
#!/usr/bin/python import sys, socket, re, os, string, time sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist #----------------------------------------------------------------- s=firesocket.FIRESocket() try: if len(sys.argv) < 5: print """USAGE: makedistfiles.py <querylist> <server> <port> <suffix> [-q] """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) suffix=sys.argv[4] try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." lines=ql.readlines() lines=map(lambda line: re.sub("\n","",line), lines) ql.close() i=0 for line in lines: print i,"/",len(lines) i+=1 tokens=re.split(" ",line) file=tokens[0] cmd="savedistances "+file+" "+file+"."+suffix print "SENDING: ",cmd s.sendcmd(cmd) res=s.getline() print res sys.stdout.flush() sys.stdout.flush() if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); classified=0 ###query images and evaluate results for line in ql: [query,relevant]=line.split('#') relevant=relevant.strip() query=query.strip() cmd="retrieve "+query relevant=relevant.split() print "SEND:'"+cmd+"'." s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize def calculate(param): data = param["data"] dbSize = param["dbSize"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [-q] -q: quit the server after finished eval """ else: param = {} # do the queries retrieveData(param) # querying finished, now evaluated the gathered data calculate(param)
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback #sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False start=-1 stop=-1 while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-x": quit=True elif argv=="-S": suffix=sys.argv.pop(0) elif argv=="-start": start=int(sys.argv.pop(0)) elif argv=="-stop": stop=int(sys.argv.pop(0)) else: print "Unknown option:",argv print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist, -1 for full database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"querybase=",querybase if querybase=="": print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist -x exit after having finished """ sys.exit(10) sys.stdout.flush() q=filelist.FileList() q.load(querybase) s=firesocket.FIRESocket() s.connect(server,port) if start==-1: start=0 if stop==-1: stop=len(q.files) try: for qf in q.files[start:stop]: cmd="savedistances "+qf[0]+" "+qf[0]+"."+suffix s.sendcmd(cmd) res=s.getline() print res if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/python import sys,re import filelist filelist=filelist.FileList() filelist.load(sys.argv[1]) for i in filelist: cls=i[1] fname=i[0] print fname, for j in filelist: if j[1]==cls and j[0]!=fname: print j[0], print #print filelist
Python
#!/usr/bin/python import sys,re,filelist if len(sys.argv)<3: print """USAGE filelistquery2querylist.py <querylist> <dblist>""" sys.exit(5) qlist=filelist.FileList() qlist.load(sys.argv[1]) dblist=filelist.FileList() dblist.load(sys.argv[2]) for i in qlist: cls=i[1] fname=i[0] print fname, for j in dblist: if j[1]==cls: print j[0], print
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) useX="-x" in sys.argv verbose="-v" in sys.argv try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." fileprefix="" if len(sys.argv)>4: if sys.argv[4]!="-q" and sys.argv[4]!="-x" and sys.argv[4]!="-v": fileprefix=sys.argv[4] lines=ql.readlines() # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); ql.close() classified=0 ###query images and evaluate results for line in lines: line=re.sub('\n','',line) relevant=re.split(" ",line) query=fileprefix+relevant[0] # this is the name of the query image relevant=relevant[1:] # this are the names of the images relevant to the query image cmd="retrieve +"+query s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimage=re.sub(fileprefix,"",returnedimage) returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] if verbose: print "results:",returnedimages[0],"->0", sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize param["useX"] = useX param["verbose"] = verbose def calculate(param): data = param["data"] dbSize = param["dbSize"] useX = param["useX"] verbose = param["verbose"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] if useX: g=Gnuplot.Gnuplot() g.title('PR graph') g('set data style linespoints') g('set xrange [0.0:1.0]') g('set yrange [0.0:1.0]') data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 if verbose: print returnedimages[Ri],"->",Ri, print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] if useX: g.plot(Gnuplot.Data(PRgraph,title="PRgraph current query"),Gnuplot.Data(tmpAPRgraph,title="PRgraph average")) print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [<fileprefix>] [-q] [-x] -q: quit the server after finished eval -x: show PR graph after each query on X display -v: verbose <fileprefix> should not be necessary """ else: param = {} retrieveData(param) calculate(param)
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: host=sys.argv[1] if len(sys.argv) >=3: port=int(sys.argv[2]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." s.sendcmd("listfiles") fileline=s.getline() files=string.split(fileline," ") s.sendcmd("setresults 2") s.getline() classified=0 correct=0 error=0 for file in files: if len(file)>0: cmd="retrieve +"+file s.sendcmd(cmd) res=s.getline() parts=string.split(res," ") result=parts[2] print res #get classes s.sendcmd("class "+file) qclass=s.getline() s.sendcmd("class "+result) rclass=s.getline() qc=int(qclass) rc=int(rclass) if(rc==qc): correct=correct+1 else: error=error+1 classified=classified+1 er=float(error)/float(classified)*100.0 print file+" wrong="+str(error)+" correct="+str(correct)+" classified="+str(classified)+" ER="+str(er) s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys, socket, re, os, string, time class mysocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk != '\n': msg=msg+chunk return msg #----------------------------------------------------------------- s=mysocket() try: if len(sys.argv) != 4: print """USAGE: querylistwqueryexpansion.py <querylist> <server> <port> """ else: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." files=ql.readlines() ql.close() s.sendcmd("setresults 10") s.sendcmd("setextensions 2") for file in files: file=re.sub('\n','',file) cmd="retrieveandsaveranks 1030 "+file+".ranks "+file s.sendcmd(cmd) res=s.getline() print res s.sendcmd("bye") except Exception, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast
Python
#!/usr/bin/python import sys,re,filelist if len(sys.argv)<3: print """USAGE filelistquery2querylist.py <querylist> <dblist>""" sys.exit(5) qlist=filelist.FileList() qlist.load(sys.argv[1]) dblist=filelist.FileList() dblist.load(sys.argv[2]) for i in qlist: cls=i[1] fname=i[0] print fname, for j in dblist: if j[1]==cls: print j[0], print
Python
import socket, os, sys,re # ---------------------------------------------------------------------- # socket implementation for comunication with the server system # running on any computer which is reachable via network sockets # here we need mainly the functions # * connect # * sendcmd # * getline # * close # for the communication # ---------------------------------------------------------------------- class FIRESocket: '''Socket stolen somewhere from the net''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock #self.sock.settimeout(10.0) def connect(self,host, port): self.sock.connect((host, port)) def send(self,msg): #print "PUT:",msg; sys.stdout.flush() totalsent = 0 MSGLEN=len(msg) while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent def sendcmd(self,cmd): cmd = cmd + "\r\n" self.send(cmd) def getResult(self): result="" line="" while line[0:3] != "end": line=self.getline() if line[0:3] != "end": result=result+line #print "GOTR:",result; sys.stdout.flush() return result def receive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError, "socket connection broken" msg = msg + chunk return msg def getline(self): msg='' chunk='a' while chunk != '\n': chunk=self.sock.recv(1) if chunk == '': raise RuntimeError, "socket connection broken" if chunk!= '\r' and chunk != '\n': msg=msg+chunk msg=re.sub("[ ]$","",msg) #print "GOTL:",msg; sys.stdout.flush() return msg def flush(self): chunk=self.sock.recv(5000) return
Python
#!/usr/bin/python import sys,re import filelist,porterstemmer querylist=filelist.FileList() filelist=filelist.FileList() filelist.load(sys.argv[1]) querylist.load(sys.argv[2]) stemmer=porterstemmer.PorterStemmer() if not filelist.descriptions: print "no descriptions, this program is not appropriate" sys.exit(10) for i in querylist: cls=i[1] desc=[] #print "Before stemming: ",i[2] for w in i[2]: w=stemmer.stem(w,0,len(w)-1) desc+=[w] #print "After stemming:",desc rels={} for j in filelist: desc2=[] for w in j[2]: w=stemmer.stem(w,0,len(w)-1) if w in desc: rels[j[0]]=1 print i[0], for f in rels: print f, print #print filelist
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback #sys.path.append("/u/deselaers/work/src/fire/python") import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False start=-1 stop=-1 while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-x": quit=True elif argv=="-S": suffix=sys.argv.pop(0) elif argv=="-start": start=int(sys.argv.pop(0)) elif argv=="-stop": stop=int(sys.argv.pop(0)) else: print "Unknown option:",argv print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist, -1 for full database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"querybase=",querybase if querybase=="": print """ USAGE: makedistfilesforfilelist.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -q database for query -S suffix -start <n>, -stop <n> to process a subset of the querylist -x exit after having finished """ sys.exit(10) sys.stdout.flush() q=filelist.FileList() q.load(querybase) s=firesocket.FIRESocket() s.connect(server,port) if start==-1: start=0 if stop==-1: stop=len(q.files) try: for qf in q.files[start:stop]: cmd="savedistances "+qf[0]+" "+qf[0]+"."+suffix s.sendcmd(cmd) res=s.getline() print res if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/env python import gzip # class for FIRE histogramfeatures class HistogramFeature: def __init__(self): self.steps=[] self.bins=[] self.min=[] self.max=[] self.stepsize=[] self.dim=0 self.counter=0 self.filename="" self.data=[] def save(self,filename): f=gzip.GzipFile(filename,"w") print >>f,"FIRE_histogram" print >>f,"# created with histogramfeature.py" print >>f,"dim",self.dim print >>f,"counter",self.counter print >>f,"steps"," ".join(map(lambda x: str(x),self.steps)) print >>f,"min"," ".join(map(lambda x: str(x), self.min)) print >>f,"max"," ".join(map(lambda x: str(x), self.max)) print >>f,"data"," ".join(map(lambda x: str(x), self.data)) f.close() def load(self,filename): f=gzip.GzipFile(filename) self.filename=filename for line in f: toks=line.split() if toks[0]=="FIRE_histogram": fine=True elif toks[0]=="#": fine=True elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="counter": self.counter=int(toks[1]) elif toks[0]=="steps": self.steps=map(lambda x: int(x), toks[1:]) elif toks[0]=="min": self.min=map(lambda x: float(x),toks[1:]) elif toks[0]=="max": self.max=map(lambda x: float(x),toks[1:]) elif toks[0]=="data": self.bins=map(lambda x: int(x),toks[1:]) try: self.data=map(lambda x: float(x)/float(self.counter), self.bins) except: print "Error reading file:", filename,"probably division by zero, continuing anyway." else: print "Unparsed line: '"+line+"'."
Python
#!/usr/bin/python import sys, socket, re, os, string, time, traceback #sys.path.append("../python") import firesocket def retrieveData(param): data = {} s=firesocket.FIRESocket() try: ql=open(sys.argv[1],"r") host=sys.argv[2] port=int(sys.argv[3]) try: time.sleep(1) #don't kill the server by exiting tooo fast s.connect(host,port) except: print "Connecting to server "+host+" on port "+str(port)+" failed." # get number of files in retriever s.sendcmd("info") res=s.getline() status=re.split(" ",res) status.reverse() keyword=status.pop() dbSize=int(status.pop()) print "database has",dbSize,"images." s.sendcmd("setresults "+str(dbSize)); res=s.getline(); classified=0 ###query images and evaluate results for line in ql: [query,relevant]=line.split('#') relevant=relevant.strip() query=query.strip() cmd="retrieve "+query relevant=relevant.split() print "SEND:'"+cmd+"'." s.sendcmd(cmd) res=s.getline() # get the results from the retriever res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) results.reverse() returnedimages=[] while len(results)>0: returnedimage=results.pop() score=results.pop() returnedimages=returnedimages+[returnedimage] # -------------------------------------------------------------- # performance evaluation # -------------------------------------------------------------- classified=classified+1 if returnedimages[0] != query: # if the query image is not the first returned, we assume that it is # not part of the database, and thus we have to start with the first # returned image for query evaluation. This is a workaround, usually we start # at position 1, to keep this valid we insert a new one on position 0 # this makes the old position 0 to position 1 and everything hereafter # stays valid returnedimages.insert(0,"DUMMYIMAGE") key = classified data[key] = [query, relevant, returnedimages] #print "key", key, "data", data[key] print "query:", query, "image no.:", classified, "of", dbSize, "relevant:", relevant[:5], "returnedimages:", returnedimages[:5] sys.stdout.flush() s.sendcmd("info") res=s.getline() print "SETTINGS:",res sys.stdout.flush() time.sleep(1) if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if "-q" in sys.argv: s.sendcmd("quit") else: s.sendcmd("bye") traceback.print_exc(file=sys.stdout) # t=sys.last_traceback # traceback.print_tb(t) print e time.sleep(1) #don't kill the server by exiting tooo fast param["data"] = data param["dbSize"] = dbSize def calculate(param): data = param["data"] dbSize = param["dbSize"] # init variables for quantitative comparison classified=0; correct=0; error=0; AMP=0.0; ARE=0.0; ARP05=0.0;APRP=0.0; MAP=0.0 AP1=0; AP20=0; AP50=0; APNrel=0; AR100=0; ARank1=0; ARanktilde=0; APRarea=0.0; APRgraph=[(0.0,0),(0.1,0),(0.2,0),(0.3,0),(0.4,0),(0.5,0),(0.6,0),(0.7,0),(0.8,0),(0.9,0),(1.0,0)] data.keys().sort() for j in data.keys(): #print "j", j relevant = data[j][1] returnedimages = data[j][2] # calculate performance measures: Error rate classified=classified+1 if returnedimages[1] in relevant: correct=correct+1 else: error=error+1 # calculate performance measures: ARE, AMP, Rank1, Ranktilde MPQ=0.0; REQ=0.0; MPQ_div=0.0; REQ_div=0.0; i=1; RP05=-1.0; PRP=-1.0; AvPr=0.0; for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: AvPr+=(float(i)/float(Ri)) MPQ+=float(dbSize-Ri)/float(dbSize-(i)) REQ+=float(Ri); REQ_div+=float(i) #print "i:", i if i==1: Rank1=Ri i+=1 print Ranktilde=float(REQ-((len(relevant)*(len(relevant)-1))/2))/float(dbSize*len(relevant)) MPQ*=float(100)/float(len(relevant)) if REQ_div!=0: REQ/=REQ_div AMP+=MPQ ARE+=REQ AvPr*=float(100)/float(len(relevant)) # calculate performance measures: P,R, PR-graph Nrelret=0; PR=[] for Ri in range(1,len(returnedimages)): if returnedimages[Ri] in relevant: Nrelret+=1 P=float(Nrelret)/float(Ri) R=float(Nrelret)/float(len(relevant)) PR+=[(P,R)] # smoothing Ris=range(1,len(returnedimages)-1) Ris.reverse() maxP=0 for Ri in Ris: if PR[Ri][0]>maxP: maxP=PR[Ri][0] else: PR[Ri]=(maxP,PR[Ri][1]) if PR[Ri][0]>0.5 and RP05<0: RP05=PR[Ri][1] if PR[Ri][0]>PR[Ri][1] and PRP<0: PRP=PR[Ri][0] if RP05<0: RP05=0 if PRP<0: PRP=0 # pick the eleven values R=0.0,0.1,...,1.0 from the PR values for the PRgraph i=0 PRgraph=[] for r in range(11): R=float(r)/float(10) while i<len(PR) and PR[i][1] < R: i+=1 if i>len(PR)-1: i=len(PR)-1 P=PR[i][0] PRgraph+=[(R,P)] if PRgraph[0][1] < PRgraph[1][1]: PRgraph[0]=(PRgraph[0][0],PRgraph[1][1]) PRarea=0.0 for i in PRgraph[1:-1]: PRarea+=i[1] PRarea+=0.5*(PRgraph[0][1]+PRgraph[-1][1]) PRarea*=0.1 P1=PR[0][0] P20=0 if len(PR)>20: P20=PR[20][0] P50=0 if len(PR)>50: P50=PR[50][0] PNrel=PR[len(relevant)][0] if len(PR)>100: R100=PR[100][1] else: R100=1 AP1 +=P1 AP20 +=P20 AP50 +=P50 APNrel+=PNrel AR100 +=R100 ARank1+=Rank1 ARanktilde+=Ranktilde APRarea+=PRarea ARP05+=RP05 APRP+=PRP MAP+=AvPr for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]+PRgraph[i][1]) tmpAPRgraph=[] for i in range(len(APRgraph)): tmpAPRgraph+=[(APRgraph[i][0],APRgraph[i][1]/float(classified))] print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), #print "PRgraph: ",PRgraph print "classfied: %i" % (classified) for i in range(len(APRgraph)): APRgraph[i]=(APRgraph[i][0],APRgraph[i][1]/float(classified)) print "RESULT:", print " AMP: %1.2f" % (float(AMP)/float(classified)), print "ARE: %1.2f" % (float(ARE)/float(classified)), print "MAP: %1.2f" % (float(MAP)/float(classified)), print "ER: %1.2f:" % (float(error)*100/float(classified)), print "P1: %1.2f" % (float(AP1)/float(classified)), print "P20: %1.2f" % ( float(AP20)/float(classified)), print "P50: %1.2f" % ( float(AP50)/float(classified)), print "PNrel: %1.2f" % ( float(APNrel)/float(classified)), print "R100: %1.2f" % (float(AR100)/float(classified)), print "Rank1: %1.2f" % (float(ARank1)/float(classified)), print "Ranktilde: %1.2f" % (float(ARanktilde)/float(classified)), print "PRarea: %1.2f" % (float(APRarea)/float(classified)), print "R(P=0.5): %1.2f" % (float(ARP05)/float(classified)), print "P(R=P): %1.2f" % (float(APRP)/float(classified)), print "classfied: %i" % (classified) print "PRgraph: ",APRgraph if __name__ == "__main__": if len(sys.argv) < 4: print """USAGE: querylist.py <querylist> <server> <port> [-q] -q: quit the server after finished eval """ else: param = {} # do the queries retrieveData(param) # querying finished, now evaluated the gathered data calculate(param)
Python
#!/usr/bin/python # easy script for automatic batches with fire # takes database files for queries # calculates error rate only import sys, socket, re, os, string, time, traceback,numarray import firesocket,filelist # forget own name in commandline options sys.argv.pop(0) server="localhost" port=12960 database="" querybase="" l1o=False quit=False while len(sys.argv)>0: argv=sys.argv.pop(0) if argv=="-s": server=sys.argv.pop(0) elif argv=="-p": port=int(sys.argv.pop(0)) elif argv=="-f": database=sys.argv.pop(0) elif argv=="-q": querybase=sys.argv.pop(0) elif argv=="-l1o": l1o=True elif argv=="-x": quit=True else: print "Unknown option:",argv print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o if database=="" or querybase=="" and not l1o: print """ USAGE: queryfilelistwcls.py <options> -h show this help -s server (default: localhost) -p port (default: 12960) -f database -q database for query -l1o make leaving one out with database -x exit after having finished """ sys.exit(10) print "SETTINGS: server=",server,"port=",port,"database=",database,"querybase=",querybase,"l1o=",l1o sys.stdout.flush() f=filelist.FileList() f.load(database) q=filelist.FileList() if not l1o: q.load(querybase) else: q=f if not f.classes: print "Need classes in database file" sys.exit(10) if not l1o and not q.classes: print "Need classes in querybase file" sys.exit(10) s=firesocket.FIRESocket() s.connect(server,port) try: s.sendcmd("info") res=s.getline() status=re.split(" ",res) keyword=status.pop(0) dbSize=int(status.pop(0)) if dbSize!=len(f.files): print "database in retriever and database loaded are of different size:", dbSize,"!=",len(f.files) s.sendcmd("bye") time.sleep(1) sys.exit(10) print "database has",dbSize,"images." if not l1o: s.sendcmd("setresults 1"); res=s.getline() else: s.sendcmd("setresults 2"); res=s.getline() classified=0; errors=0; correct=0 no_classes=0 for qf in q.files: if qf[1]>no_classes: no_classes=qf[1] for df in f.files: if df[1]>no_classes: no_classes=df[1] no_classes+=1 print no_classes,"classes." confusionmatrix=numarray.zeros((no_classes,no_classes),numarray.Int) counter=0 for qf in q.files: counter+=1 qname=qf[0] qcls=qf[1] s.sendcmd("retrieve "+qname) res=s.getline() res=re.sub('[ ]*$','',res) # and parse the results results=re.split(" ",res) if not l1o: if len(results)!=2: print "expected 2 tokens, got",len(results) sys.exit(10) else: if len(results)!=4: print "expected 4 tokens, got",len(results) sys.exit(10) results.pop(0) results.pop(0) returnedimage=results.pop(0) score=float(results.pop(0)) for df in f.files: if not l1o: if df[0]==returnedimage: dcls=df[1] break else: if df[0]==returnedimage and df[0]!=qname: dcls=df[1] break classified+=1 if dcls==qcls: correct+=1 else: errors+=1 confusionmatrix[dcls][qcls]+=1 print "Query "+str(counter)+"/"+str(len(q.files))+":",qname,"("+str(qcls)+") NN:",returnedimage,"("+str(dcls)+")","ER:",float(errors)/float(classified)*100 sys.stdout.flush() print "RESULT: ER:",float(errors)/float(classified)*100 print confusionmatrix time.sleep(1) if quit: s.sendcmd("quit") else: s.sendcmd("bye") time.sleep(1) #don't kill the server by exiting tooo fast except KeyboardInterrupt, e: s.sendcmd("bye") print e time.sleep(1) #don't kill the server by exiting tooo fast except Exception, e: if quit: s.sendcmd("quit") else: s.sendcmd("bye") print e time.sleep(1)
Python
#!/usr/bin/env python import sys,gzip class Feature: def __init__(self): self.posx=0 self.posy=0 self.scale=0 self.vec=[] class LocalFeatures: def __init__(self): self.winsize=0 self.dim=0 self.subsampling=0 self.padding=0 self.numberOfFeatures=0 self.varthreshold=0 self.zsize=0 self.filename="" self.imagesize=(0,0) self.features=[] self.selffilename="" def __getitem__(self,i): return self.features[i] def load(self,filename): f=gzip.GzipFile(filename) self.selffilename=filename for l in f: toks=l.split() if toks[0]=="FIRE_localfeatures": fine=True elif toks[0]=="winsize": self.winsize=int(toks[1]) elif toks[0]=="dim": self.dim=int(toks[1]) elif toks[0]=="subsampling": self.subsampling=int(toks[1]) elif toks[0]=="padding": self.padding=int(toks[1]) elif toks[0]=="numberOfFeatures": self.numberOfFeatures=int(toks[1]) elif toks[0]=="varthreshold": self.varthreshold=float(toks[1]) elif toks[0]=="zsize": self.zsize=int(toks[1]) elif toks[0]=="filename": self.filename=toks[1] elif toks[0]=="imagesize": self.imagesize=(int(toks[1]),int(toks[2])) elif toks[0]=="features": if self.numberOfFeatures!=int(toks[1]): print "Weird... inconsistent number of Features and features expected in the file" elif toks[0]=="feature": f=Feature() toks.pop(0) f.posx=float(toks.pop(0)) f.posy=float(toks.pop(0)) f.scale=float(toks.pop(0)) f.vec=map(lambda x: float(x), toks) self.features+=[f] else: print "'%s' is an unknown keyword... ignoring and continuiing nonetheless."%(toks[0]) def save(self,filename): f=gzip.GzipFile(filename,"w") f.write("FIRE_localfeatures\n") f.write("winsize %d\ndim %d\nsubsampling %d\npadding %d\nnumberOfFeatures %d\nvarthreshold %d\nzsize %d\nfilename %s\nimagesize %d %d\nfeatures %d\n" % (self.winsize,self.dim,self.subsampling,self.padding,self.numberOfFeatures,self.varthreshold,self.zsize,self.filename,self.imagesize[0],self.imagesize[1],len(self.features))) for lf in self.features: f.write("feature %d %d %d " % (lf.posx,lf.posy,lf.scale)) for v in lf.vec: f.write(str(v)+" ") f.write("\n") f.close()
Python
#!/usr/bin/python import sys #this script merges fire distance files. # # as command line parameters, arbitrary many distance files are given and # the merged distance file is printed. infiles=[] line=[] for i in sys.argv[1:]: infiles.append(open(i,"r")) line.append("") line[0]=infiles[0].readline() count=0 while(line[0]): for i in range(1,len(infiles)): line[i]=infiles[i].readline() if line[0].startswith("nofdistances"): nDist=0 nImg=0 for l in line: toks=l.split() nDist+=int(toks[2]) nImg=int(toks[1]) print "nofdistances",nImg,nDist elif not line[0].startswith("#"): print count, for l in line: toks=l.split() for i in range(1,len(toks)): print float(toks[i]), print count+=1 line[0]=infiles[0].readline()
Python
# # jython examples for jas. from jas import Module from jas import SubModule # module example r = Module( "Rat(u,v,l) L", cols=4 ); print "Module: " + str(r); print; G = r.gens(); print "gens() = ", [str(e) for e in G]; L = [ e.elem.val for e in G ] print "gens() = ", [str(e) for e in L]; M = r.submodul( list=L ); print "M = ", M; P = M.mset.getPolynomialList(); print "P = ", P.toScript(); print "M.isGB(): ", M.isGB();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, DD # polynomial examples: ideal primary decomposition #r = Ring( "Rat(x) L" ); #r = Ring( "Q(x) L" ); r = PolyRing(QQ(),"x,y,z",PolyRing.lex); print "Ring: " + str(r); print; [one,x,y,z] = r.gens(); f1 = (x**2 - 5)**2; f2 = (y**2 - x)**2; f3 = z**2 - x ; #print "f1 = ", f1; print "f2 = ", f2; print "f3 = ", f3; print; F = r.ideal( list=[f2,f3] ); print "F = ", F; print; startLog(); t = System.currentTimeMillis(); Q = F.primaryDecomp(); t = System.currentTimeMillis() - t; print "Q = ", Q; print; print "primary decomp time =", t, "milliseconds"; print; print "F = ", F; print; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring, PolyRing, Ideal, QQ, ZZ, GF, ZM, CC from jas import startLog, terminate # trinks 6/7 example # QQ = rational numbers, ZZ = integers, CC = complex rational numbers, GF = finite field #QQ = QQ(); ZZ = ZZ(); CC = CC(); #r = PolyRing( GF(19),"B,S,T,Z,P,W", PolyRing.lex); #r = PolyRing( GF(1152921504606846883),"B,S,T,Z,P,W", PolyRing.lex); # 2^60-93 #r = PolyRing( GF(2**60-93),"B,S,T,Z,P,W", PolyRing.lex); #r = PolyRing( CC(),"B,S,T,Z,P,W", PolyRing.lex); #r = PolyRing( ZZ(),"B,S,T,Z,P,W", PolyRing.lex); # not for parallel r = PolyRing( QQ(),"B,S,T,Z,P,W", PolyRing.lex); print "Ring: " + str(r); print; # sage like: with generators for the polynomial ring #[one,I,B,S,T,Z,P,W] = r.gens(); # is automaticaly included #[one,B,S,T,Z,P,W] = r.gens(); # is automaticaly included f1 = 45 * P + 35 * S - 165 * B - 36; f2 = 35 * P + 40 * Z + 25 * T - 27 * S; f3 = 15 * W + 25 * S * P + 30 * Z - 18 * T - 165 * B**2; f4 = - 9 * W + 15 * T * P + 20 * S * Z; f5 = P * W + 2 * T * Z - 11 * B**3; f6 = 99 * W - 11 *B * S + 3 * B**2; f7 = 10000 * B**2 + 6600 * B + 2673; F = [ f1, f2, f3, f4, f5, f6, f7 ]; # smaller, faster #F = [ f1, f2, f3, f4, f5, f6 ]; # bigger, needs more time #print "F = ", [ str(f) for f in F ]; #print; I = r.ideal( "", list=F ); print "Ideal: " + str(I); print; rg = I.GB(); print "seq Output:", rg; print; #startLog(); rg = I.parGB(2); #print "par Output:", rg; #print; #sys.exit(); # if using ZZ coefficients I.distClient(); # starts in background rg = I.distGB(2); #print "dist Output:", rg; #print; I.distClientStop(); # stops them terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import PolyRing, QQ, RF from jas import Ideal from jas import startLog from jas import terminate # Montes JSC 2002, 33, 183-208, example 11.1 # integral function coefficients r = PolyRing( PolyRing(QQ(),"c, b, a",PolyRing.lex), "z,y,x", PolyRing.lex ); print "Ring: " + str(r); print; [one,c,b,a,z,y,x] = r.gens(); print "gens: ", [ str(f) for f in r.gens() ]; print; f1 = x + c * y + b * z + a; f2 = c * x + y + a * z + b; f3 = b * x + a * y + z + c; F = [f1,f2,f3]; print "F: ", [ str(f) for f in F ]; print; #startLog(); If = r.paramideal( "", list = F ); print "ParamIdeal: " + str(If); print; ## G = If.GB(); ## print "GB: " + str(G); ## print; ## sys.exit(); GS = If.CGBsystem(); GS = If.CGBsystem(); GS = If.CGBsystem(); print "CGBsystem: " + str(GS); print; bg = GS.isCGBsystem(); if bg: print "isCGBsystem: true"; else: print "isCGBsystem: false"; print; terminate(); sys.exit(); CG = If.CGB(); print "CGB: " + str(CG); print; bg = CG.isCGB(); if bg: print "isCGB: true"; else: print "isCGB: false"; print; terminate(); #------------------------------------------ #sys.exit();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import SolvableRing, SolvPolyRing, PolyRing from jas import QQ, startLog, SRC, SRF # Ore extension solvable polynomial example, Gomez-Torrecillas, 2003 pcz = PolyRing(QQ(),"x,y,z"); #is automatic: [one,x,y,z] = pcz.gens(); zrelations = [z, y, y * z + x ]; print "zrelations: = " + str([ str(f) for f in zrelations ]); print; pz = SolvPolyRing(QQ(), "x,y,z", PolyRing.lex, zrelations); print "SolvPolyRing: " + str(pz); print; pzq = SRF(pz); print "SolvableQuotientRing: " + str(pzq.ring.toScript()); # + ", assoz: " + str(pzq.ring.isAssociative()); #print "gens =" + str([ str(f) for f in pzq.ring.generators() ]); print; pct = PolyRing(pzq,"t"); #is automatic: [one,x,y,z,t] = p.gens(); trelations = [t, y, y * t + y, t, z, z * t - z ]; print "relations: = " + str([ str(f) for f in trelations ]); print; pt = SolvPolyRing(pzq, "t", PolyRing.lex, trelations); print "SolvPolyRing: " + str(pt); print; print "gens =", [ str(f) for f in pt.gens() ]; #print "t = " + str(t); #print "z = " + str(z); zi = 1 / z; yi = 1 / y; xi = 1 / x; #startLog(); a = ( t * zi ) * y; b = t * ( zi * y ); c = a - b; print "t * 1/z * y: "; print "a = " +str(a); print "b = " +str(b); print "a-b = " +str(c); print #bm = b.monic() #print "monic(b) = " +str(bm); #print #exit(0); f1 = x**2 + y**2 + z**2 + t**2 + 1; print "f1 = ", f1; f2 = t * x * f1; print "f2 = ", f2; F = [ f1, f2 ]; print "F =", [ str(f) for f in F ]; print I = pt.ideal( list=F ); print "SolvableIdeal: " + str(I); print; #exit(0); rgl = I.leftGB(); print "seq left GB:" + str(rgl); print "isLeftGB: " + str(rgl.isLeftGB()); print; #rgr = I.rightGB(); #print "seq right GB:" + str(rgr); #print "isRightGB: " + str(rgr.isRightGB()); #print; #startLog(); rgt = I.twosidedGB(); print "seq twosided GB:" + str(rgt); print "isTwosidedGB: " + str(rgt.isTwosidedGB()); print; #exit(0); #startLog(); rgi = rgl.intersect(rgt); print "leftGB intersect twosidedGB:" + str(rgi); print; #terminate();
Python
# jython examples for jas. # $Id$ # import sys from java.lang import System from jas import Ring, RF, QQ, PolyRing from jas import terminate from jas import startLog # elementary integration atan examples r = PolyRing(QQ(),"x",PolyRing.lex); print "r = " + str(r); rf = RF(r); print "rf = " + str(rf.factory()); [one,x] = rf.gens(); print "one = " + str(one); print "x = " + str(x); print; #f = 1 / ( 1 + x**2 ); #f = 1 / ( x**2 - 2 ); #f = 1 / ( x**3 - 2 ); #f = ( x + 3 ) / ( x**2- 3 * x - 40 ); f = ( x**7 - 24 * x**4 - 4 * x**2 + 8 * x - 8 ) / ( x**8 + 6 * x**6 + 12 * x**4 + 8 * x**2 ); print "f = ", f; print; #sys.exit(); #startLog(); t = System.currentTimeMillis(); e1 = r.integrate(f); t = System.currentTimeMillis() - t; print "e1 = ", e1; print "integration time =", t, "milliseconds"; print t = System.currentTimeMillis(); e2 = f.integrate(); t = System.currentTimeMillis() - t; print "e2 = ", e2; print "integration time =", t, "milliseconds"; print #startLog(); terminate(); #sys.exit();
Python
# # jython examples for jas. # $Id$ # from java.lang import System from java.lang import Integer from jas import Ring, PolyRing from jas import terminate from jas import startLog from jas import QQ, DD # polynomial examples: real roots over Q #r = Ring( "Rat(x) L" ); #r = Ring( "Q(x) L" ); r = PolyRing(QQ(),"x",PolyRing.lex); print "Ring: " + str(r); print; [one,x] = r.gens(); f1 = x * ( x - 1 ) * ( x - 2 ) * ( x - 3 ) * ( x - 4 ) * ( x - 5 ) * ( x - 6 ) * ( x - 7 ) ; f2 = ( x - (1,2) ) * ( x - (1,3) ) * ( x - (1,4) ) * ( x - (1,5) ) * ( x - (1,6) ) * ( x - (1,7) ) ; f3 = ( x - (1,2**2) ) * ( x - (1,2**3) ) * ( x - (1,2**4) ) * ( x - (1,2**5) ) * ( x - (1,2**6) ) * ( x - (1,2**7) ) ; #f = f1 * f2 * f3; f = f1 * f2; #f = f1 * f3; #f = f2 * f3; #f = f3; #f = ( x**2 - 2 ); print "f = ", f; print; startLog(); t = System.currentTimeMillis(); R = r.realRoots(f); t = System.currentTimeMillis() - t; #print "R = ", R; print "R = ", [ a.elem.ring.getRoot() for a in R ]; print "real roots time =", t, "milliseconds"; eps = QQ(1,10) ** (DD().elem.DEFAULT_PRECISION-3); print "eps = ", eps; t = System.currentTimeMillis(); R = r.realRoots(f,eps); t = System.currentTimeMillis() - t; #print "R = ", [ str(r) for r in R ]; print "R = ", [ a.elem.decimalMagnitude() for a in R ]; print "real roots time =", t, "milliseconds"; #startLog(); terminate();
Python
# # jython examples for jas. # $Id$ # import sys; from jas import Ring from jas import Ideal from jas import startLog from jas import terminate # ? example #r = Ring( "Rat(t,x,y,z) L" ); #r = Ring( "Z(t,x,y,z) L" ); #r = Ring( "Mod 11(t,x,y,z) L" ); r = Ring( "Rat(t,x,y) L" ); print "Ring: " + str(r); print; ps = """ ( ( t - x - 2 y ), ( x^4 + 4 ), ( y^4 + 4 ) ) """; # ( y^4 + 4 x y^3 - 2 y^3 - 6 x y^2 + 1 y^2 + 6 x y + 2 y - 2 x + 3 ), # ( x^2 + 1 ), # ( y^3 - 1 ) # ( y^2 + 2 x y + 2 y + 2 x + 1 ), # ( y^4 + 4 x - 2 y^3 - 6 x + 1 y^2 + 6 x + 2 y - 2 x + 3 ), # ( t - x - 2 y ), # ( 786361/784 y^2 + 557267/392 y + 432049/784 ), # ( x^7 + 3 y x^4 + 27/8 x^4 + 2 y x^3 + 51/7 x^3 + 801/28 y + 1041/56 ) # ( x**2 + 1 ), # ( y**2 + 1 ) f = r.ideal( ps ); print "Ideal: " + str(f); print; #startLog(); rg = f.GB(); print "seq Output:", rg; print; terminate();
Python