Speach Recognition speachtest1.py << speachtest1 declarations >> class SpeechRecognition << class SpeechRecognition declarations >> __init__ say class ContextEvents << class ContextEvents declarations >> OnRecognition SpeechGui.py << SpeechGui declarations >> say sendKeys start browseTo message getMondrianData getMondrianBitmap getMondrianImage class ContextEvents OnRecognition class MyApp << class MyApp declarations >> setItems InitSpeech SetWords SetUpTaskbar OnInit OnExitFrame OnIconize OnAddClick OnDeleteClick OnListBoxSelect OnTestClick OnTextEntered OnTaskBarActivate OnTaskBarMenu OnTaskBarClose displayTextBox executeItemInList resetItemsList OnTurnOnClick OnTurnOffClick turnOn turnOff new speach gui << newspeach declarations >> PILToPy sorted PILToWX WXToPIL say sendKeys start browseTo message class TileCache __init__ get_tile make_space class PanTool __init__ activate deactivate on_mouse class InspectTool __init__ activate deactivate on_mouse class InspectWindow __init__ set_position on_paint class ZoomTool __init__ activate deactivate on_mouse zoom_in zoom_out class RedTool __init__ activate deactivate class GreenTool __init__ activate deactivate class BlueTool __init__ activate deactivate class SharpTool __init__ activate deactivate on_mouse sharp_in sharp_out class ColorTool __init__ activate deactivate on_mouse color_in color_out class BrightTool __init__ activate deactivate on_mouse bright_in bright_out class RestoreTool __init__ activate deactivate class ContTool __init__ activate deactivate on_mouse cont_in cont_out class ImageView __init__ set_image get_image get_image_window get_toolbar get_tool_id __set_tool set_zoom get_zoom get_sharp get_color get_bright get_contrast set_sharp set_rgb set_color set_bright set_contrast set_origin get_origin __set_constraints __on_tool __on_scroll window_to_image image_to_window __on_size __on_paint __set_scrollbars __get_scrollbars class CameraFrame __init__ OnTimer OnCloseWindow OnGoClick OnStopClick class PythonSTC __init__ OnKeyPressed OnUpdateUI OnMarginClick FoldAll Expand SetValue class ContextEvents OnRecognition class MyFrame __init__ SetWords GetStory OnAddClick OnDeleteClick OnListBoxSelect OnTestClick OnTextEntered OnSaveAsData OnClearData OnToolClick OnCodelClick OnToolRClick OnToolEnter OnLoadData OnSaveData OnCloseWindow OnTurnOnClick OnTurnOffClick class MyApp OnInit @path c:\python22\tom @root speachtest1.py << speachtest1 declarations >> << speachtest1 methods >> if __name__=='__main__': wordsToAdd = ["computer" , "turn on tee vee", "channel forty", "channel forty two", "channel forty four", "channel sixteen", "close program", "check mail", "channel thirty eight", "channel thirty six", "channel thirty four", "channel seven"] speechReco = SpeechRecognition(wordsToAdd) while 1: pythoncom.PumpWaitingMessages() @code from win32com.client import constants import win32com.client import pythoncom import sys """Sample code for using the Microsoft Speech SDK 5.1 via COM in Python. Requires that the SDK be installed; it's a free download from http://microsoft.com/speech and that MakePy has been used on it (in PythonWin, select Tools | COM MakePy Utility | Microsoft Speech Object Library 5.1). After running this, then saying "One", "Two", "Three" or "Four" should display "You said One" etc on the console. The recognition can be a bit shaky at first until you've trained it (via the Speech entry in the Windows Control Panel.""" << speachtest1 methods >>= class SpeechRecognition: << class SpeechRecognition declarations >> << class SpeechRecognition methods >> @code """ Initialize the speech recognition with the passed in list of words """ << class SpeechRecognition methods >>= def __init__(self, wordsToAdd): # For text-to-speech self.speaker = win32com.client.Dispatch("SAPI.SpVoice") # For speech recognition - first create a listener self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer") # Then a recognition context self.context = self.listener.CreateRecoContext() # which has an associated grammar self.grammar = self.context.CreateGrammar() # Do not allow free word recognition - only command and control # recognizing the words in the grammar only self.grammar.DictationSetState(0) # Create a new rule for the grammar, that is top level (so it begins # a recognition) and dynamic (ie we can change it at runtime) self.wordsRule = self.grammar.Rules.Add("wordsRule",33, 0)#constants.SRATopLevel + constants.SRADynamic # Clear the rule (not necessary first time, but if we're changing it # dynamically then it's useful) self.wordsRule.Clear() # And go through the list of words, adding each to the rule [ self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd ] # Set the wordsRule to be active self.grammar.Rules.Commit() self.grammar.CmdSetRuleState("wordsRule", 1) # Commit the changes to the grammar self.grammar.Rules.Commit() # And add an event handler that's called back when recognition occurs self.eventHandler = ContextEvents(self.context) # Announce we've started using speech synthesis self.say("Started successfully") << class SpeechRecognition methods >>= """Speak a word or phrase""" def say(self, phrase): self.speaker.Speak(phrase) << speachtest1 methods >>= """The callback class that handles the events raised by the speech object. See "Automation | SpSharedRecoContext (Events)" in the MS Speech SDK online help for documentation of the other events supported. """ class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")): << class ContextEvents declarations >> << class ContextEvents methods >> @code """Called when a word/phrase is successfully recognized - ie it is found in a currently open grammar with a sufficiently high confidence""" << class ContextEvents methods >>= def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): newResult = win32com.client.Dispatch(Result) speaker = win32com.client.Dispatch("SAPI.SpVoice") shell = win32com.client.Dispatch("WScript.Shell") if newResult.PhraseInfo.GetText() == "computer": speaker.Speak('working') elif newResult.PhraseInfo.GetText() == "turn on tee vee": shell.SendKeys("^(%z)") elif newResult.PhraseInfo.GetText() == "channel thirty eight": shell.SendKeys("38") elif newResult.PhraseInfo.GetText() == "channel thirty six": shell.SendKeys("36") elif newResult.PhraseInfo.GetText() == "channel thirty four": shell.SendKeys("34") elif newResult.PhraseInfo.GetText() == "channel seven": shell.SendKeys("7") elif newResult.PhraseInfo.GetText() == "channel forty": shell.SendKeys("40") elif newResult.PhraseInfo.GetText() == "channel forty two": shell.SendKeys("42") elif newResult.PhraseInfo.GetText() == "channel sixteen": shell.SendKeys("16") elif newResult.PhraseInfo.GetText() == "channel forty four": shell.SendKeys("44") elif newResult.PhraseInfo.GetText() == "close program": shell.SendKeys("%( )c") elif newResult.PhraseInfo.GetText() == "check mail": pass print "You said: ",newResult.PhraseInfo.GetText() @root SpeechGui.py << SpeechGui declarations >> << SpeechGui methods >> app = MyApp(0) app.MainLoop() @code # A simple speech recognition program for Windows # When speech is recognized, Python macros are executed. # This requires: # That the wxPython library is installed (obtain from http://www.wxpython.org/) # That the MS Speech API 5 is installed (obtain from http://microsoft.com/speech/) # That MakePy has been run on the MS Speech API (in PythonWin, select Tools | # COM MakePy Utility | Microsoft Speech Object Library 5.1) # Copyright (C) 2001 Inigo Surguy, inigosurguy@hotmail.com # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # or download it from http://www.gnu.org/licenses/gpl.txt from wxPython.wx import * import sys, time, math, string, win32com.client,win32event,pythoncom from win32com.client import constants import win32con import cPickle, zlib import string import pickle import win32api import win32com.client import traceback # Handy methods that make the code included inside the macro area simpler speaker = win32com.client.Dispatch("SAPI.SpVoice") """Say the text via the MS Speech API""" << SpeechGui methods >>= def say(text): speaker.Speak(text) << SpeechGui methods >>= shell = win32com.client.Dispatch("WScript.Shell") """Use the Windows Scripting Host sendKeys function to send keystrokes to the currently focused application. See help on the Microsoft site for values that represent special keys: common ones I use are %{TAB} for Alt-Tab, and {PGDN} and {PGUP} for page down and up, and %{F4} for Alt-F4.""" def sendKeys(keystrokes): shell.SendKeys(keystrokes) << SpeechGui methods >>= """Launch a command via the Windows Scripting Host""" def start(command): shell.Run(command) << SpeechGui methods >>= """Launch Internet Explorer, and navigate to a given URL""" def browseTo(location): ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 ie.Navigate(location) << SpeechGui methods >>= """Display a message box with the given message and title""" def message(message, title="Message"): dlg = wxMessageDialog(app.frame, message, title, wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() << SpeechGui methods >>= # Taken from wxPython demo - generated with wxPython\demo\encode_bitmaps.py """Get the Mondrian picture (from the wxPython demo) that's used as an application icon""" def getMondrianData(): return cPickle.loads(zlib.decompress( 'x\332\323\310)0\344\012V76R\000"3\005Cu\256\304`u\005\205d\005\247\234\304\ \344l0/\002\310Sv\003\0030?\037\3047\000\002(_\017"\017\022\001\363\265!\362\ NnP\276?L?\224\257@\000@\024\351\201\201B\004v0"\024\021\025NP\035X\014\311\ \007\202!\251\210(\337!\205\323\250"\222\024a\001\230\212\374\221\200\2026\ \010\014\013E\204\263\224\036\000\277\004Z\355' )) << SpeechGui methods >>= def getMondrianBitmap(): return wxBitmapFromXPMData(getMondrianData()) << SpeechGui methods >>= def getMondrianImage(): return wxImageFromBitmap(getMondrianBitmap()) << SpeechGui methods >>= """The event handler for speech events""" class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")): << class ContextEvents methods >> << class ContextEvents methods >>= def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): newResult = win32com.client.Dispatch(Result) try: # Exec the appropriate listbox entry exec app.items[newResult.PhraseInfo.GetText()] except: # If execution fails, display a messagebox with error and cause etype, value, tb = sys.exc_info() message = (str(etype)+":"+str(value)+ "\nat line "+`tb.tb_next.tb_lineno`+ "for text '"+newResult.PhraseInfo.GetText()+"'") dlg = wxMessageDialog(app.frame, message, 'Exception: '+str(etype), wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() << SpeechGui methods >>= """Windows speech recognition application""" class MyApp(wxApp): << class MyApp declarations >> << class MyApp methods >> @code ADD_BUTTON_ID = 10 DELETE_BUTTON_ID = 20 LISTBOX_ID = 30 EDITOR_ID = 40 TEST_BUTTON_ID = 50 TURNON_BUTTON_ID = 60 TURNOFF_BUTTON_ID = 70 SAVE_FILENAME = "save.p" << class MyApp methods >>= def setItems(self): try: self.items = pickle.load(open(self.SAVE_FILENAME)) except IOError: self.items = {u'turn on tee vee': u'sendKeys("^(%z)")', u'channel forty two': u'sendKeys("42")', u'close program now': u'sendKeys("%( )c")', u'channel thirty six': u'sendKeys("36")', u'play woman rock': u"say('please stand by')\nbrowseTo('http://release.theplatform.com/deliverable.select?pid=Mf5zobHmqTDt6bze2ThXCugPnEUpJQQh&UserID=choiceradio')", u'channel sixteen': u'sendKeys("16")', u'open tee vee guide': u"browseTo('http://tv.yahoo.com/grid?lineup=us_AZ02423&dur=&.intl=us&startdate=0&starthour=0&genres=0')", u'channel thirty four': u'sendKeys("34")', u'channel forty four': u'sendKeys("44")', u'play raggae': u"say('please stand by')\nbrowseTo('http://www.totallyradio.com/asx/live/reggae.asx')", u'computer': u"say('working')", u'channel forty': u'sendKeys("40")', u'channel thirty eight': u'sendKeys("38")', u'stop music': u'sendKeys("^(s)")', u'play mellow yellow': u"say('please stand by')\nbrowseTo('http://radio.player.loudeye.com/LoudSE/radio.jsp?anID=22&aID=1874&dsoID=4')", u'channel seven': u'sendKeys("7")', u'channel two': u'sendKeys("2")', u'play new age': u"say('please stand by')\nbrowseTo('http://release.theplatform.com/deliverable.select?pid=tXSTT6E-SWIv_678ayYHCdIp51IFHhLb&UserID=choiceradio')"} << class MyApp methods >>= def InitSpeech(self): listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer") self.context = listener.CreateRecoContext() self.grammar = self.context.CreateGrammar() self.grammar.DictationSetState(0) self.ListItemsRule = self.grammar.Rules.Add("ListItemsRule", 33, 0) events = ContextEvents(self.context) self.turnedOn = true self.SetWords() << class MyApp methods >>= def SetWords(self): self.ListItemsRule.Clear() if self.turnedOn: print "Setting words - turned on" [ self.ListItemsRule.InitialState.AddWordTransition(None, word) for word in self.items.keys() ] else: print "Setting words - OFF" self.ListItemsRule.InitialState.AddWordTransition(None, "Turn on") self.grammar.Rules.Commit() self.grammar.CmdSetRuleState("ListItemsRule", 1) self.grammar.Rules.Commit() << class MyApp methods >>= def SetUpTaskbar(self): # setup a taskbar icon, and catch some events from it self.tbicon = wxTaskBarIcon() icon = wxIconFromXPMData(getMondrianData()) self.tbicon.SetIcon(icon, "Speech recognition") EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate) EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu) EVT_MENU(self.tbicon, self.TBMENU_RESTORE, self.OnTaskBarActivate) EVT_MENU(self.tbicon, self.TBMENU_CLOSE, self.OnTaskBarClose) << class MyApp methods >>= def OnInit(self): self.setItems() self.InitSpeech() self.frame = wxFrame(NULL, -1, "Speech tester", wxPoint(10,10), wxSize(770,300)) self.listBox = wxListBox(self.frame, self.LISTBOX_ID, wxPoint(10, 10), wxSize(120, 200), self.items.keys(), wxLB_SINGLE) self.addButton = wxButton(self.frame, self.ADD_BUTTON_ID, "Add", wxPoint(10,230), wxSize(50, 30)) self.deleteButton = wxButton(self.frame, self.DELETE_BUTTON_ID, "Delete", wxPoint(80, 230), wxSize(50, 30)) self.editor = wxTextCtrl(self.frame, self.EDITOR_ID, "", wxPoint(140,10), wxSize(600,200), style=wxSUNKEN_BORDER+wxTE_MULTILINE+wxTE_PROCESS_TAB) self.testButton = wxButton(self.frame, self.TEST_BUTTON_ID, "Test", wxPoint(140, 230), wxSize(50, 30)) self.turnonButton = wxButton(self.frame, self.TURNON_BUTTON_ID, "On", wxPoint(210, 230), wxSize(50, 30)) self.turnoffButton = wxButton(self.frame, self.TURNOFF_BUTTON_ID, "Off", wxPoint(280, 230), wxSize(50, 30)) self.SetUpTaskbar() EVT_LISTBOX(self, self.LISTBOX_ID, self.OnListBoxSelect) EVT_BUTTON(self, self.ADD_BUTTON_ID, self.OnAddClick) EVT_BUTTON(self, self.DELETE_BUTTON_ID, self.OnDeleteClick) EVT_BUTTON(self, self.TEST_BUTTON_ID, self.OnTestClick) EVT_BUTTON(self, self.TURNON_BUTTON_ID, self.OnTurnOnClick) EVT_BUTTON(self, self.TURNOFF_BUTTON_ID, self.OnTurnOffClick) EVT_TEXT(self, self.EDITOR_ID, self.OnTextEntered) EVT_ICONIZE(self.frame, self.OnIconize) EVT_CLOSE(self.frame, self.OnExitFrame) self.listBox.SetSelection(0) self.displayTextBox() self.frame.Show(true) self.SetTopWindow(self.frame) return true << class MyApp methods >>= def OnExitFrame(self, event): pickle.dump(self.items, open(self.SAVE_FILENAME, 'w')) if hasattr(self, "tbicon"): del self.tbicon self.frame.Destroy() << class MyApp methods >>= def OnIconize(self, event): self.frame.Show(false) << class MyApp methods >>= def OnAddClick(self,event): dlg = wxTextEntryDialog(self.frame, 'Text to recognize', "New item") if dlg.ShowModal() == wxID_OK: self.items[dlg.GetValue()] = "" self.resetItemsList() self.listBox.SetStringSelection(dlg.GetValue()) self.displayTextBox() self.SetWords() dlg.Destroy() << class MyApp methods >>= def OnDeleteClick(self,event): del self.items[ self.listBox.GetStringSelection() ] self.resetItemsList() self.listBox.SetSelection(0) self.displayTextBox() self.SetWords() << class MyApp methods >>= def OnListBoxSelect(self,event): self.displayTextBox() << class MyApp methods >>= def OnTestClick(self, event): self.executeItemInList(self.listBox.GetStringSelection()) << class MyApp methods >>= def OnTextEntered(self, event): self.items[self.listBox.GetStringSelection()] = event.GetString() << class MyApp methods >>= #--------------------------------------------- # This is code to use the system tray taken from the wxPython demo TBMENU_RESTORE = 1000 TBMENU_CLOSE = 1001 def OnTaskBarActivate(self, evt): if self.frame.IsIconized(): self.frame.Iconize(false) if not self.frame.IsShown(): self.frame.Show(true) self.frame.Raise() << class MyApp methods >>= def OnTaskBarMenu(self, evt): menu = wxMenu() menu.Append(self.TBMENU_RESTORE, "Restore wxPython Demo") menu.Append(self.TBMENU_CLOSE, "Close") self.tbicon.PopupMenu(menu) menu.Destroy() << class MyApp methods >>= def OnTaskBarClose(self, evt): self.frame.Close() # because of the way wxTaskBarIcon.PopupMenu is implemented we have to # prod the main idle handler a bit to get the window to actually close wxGetApp().ProcessIdle() << class MyApp methods >>= #--------------------------------------------- def displayTextBox(self): self.editor.SetValue( self.items[self.listBox.GetStringSelection()] ) << class MyApp methods >>= def executeItemInList(self,itemName): codeToExecute = self.items[itemName] try: exec codeToExecute except: etype, value, tb = sys.exc_info() message = (str(etype)+":"+str(value)+ "\nat line "+`tb.tb_next.tb_lineno`) dlg = wxMessageDialog(self.frame, message, 'Exception: '+str(etype), wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() << class MyApp methods >>= def resetItemsList(self): self.listBox.Set(self.items.keys()) << class MyApp methods >>= def OnTurnOnClick(self, event): self.turnOn() << class MyApp methods >>= def OnTurnOffClick(self, event): self.turnOff() << class MyApp methods >>= def turnOn(self): if not self.turnedOn: self.turnedOn = true self.SetWords() << class MyApp methods >>= def turnOff(self): if (self.turnedOn): self.turnedOn = false self.SetWords() @root newspeech.py << newspeach declarations >> <<newspeach methods >> app = MyApp(0) # Create an instance of the application class app.MainLoop() # Tell it to start processing events @code import urllib2 from wxPython.wx import * import Image import ImageChops import ImageStat import ImageEnhance from VideoCapture import Device import sys, time, math, string, win32event, pythoncom from win32com.client import constants import win32con import string import pickle import win32api import win32com.client #import traceback from wxPython.stc import * import keyword from wxPython.iewin import * speaker = win32com.client.Dispatch("SAPI.SpVoice") shell = win32com.client.Dispatch("WScript.Shell") faces = { 'times': 'Times New Roman', 'mono' : 'Courier New', 'helv' : 'Arial', 'other': 'Comic Sans MS', 'size' : 10, 'size2': 8, } try: items = pickle.load(open('save.p')) except IOError: items = {u'turn on tee vee': u'sendKeys("^(%z)")', u'channel forty two': u'sendKeys("42")', u'close program now': u'sendKeys("%( )c")', u'channel thirty six': u'sendKeys("36")', u'play woman rock': u"say('please stand by')\nbrowseTo('http://release.theplatform.com/deliverable.select?pid=Mf5zobHmqTDt6bze2ThXCugPnEUpJQQh&UserID=choiceradio')", u'channel sixteen': u'sendKeys("16")', u'open tee vee guide': u"browseTo('http://tv.yahoo.com/grid?lineup=us_AZ02423&dur=&.intl=us&startdate=0&starthour=0&genres=0')", u'channel thirty four': u'sendKeys("34")', u'channel forty four': u'sendKeys("44")', u'play raggae': u"say('please stand by')\nbrowseTo('http://www.totallyradio.com/asx/live/reggae.asx')", u'computer': u"say('working')", u'channel forty': u'sendKeys("40")', u'channel thirty eight': u'sendKeys("38")', u'stop music': u'sendKeys("^(s)")', u'play mellow yellow': u"say('please stand by')\nbrowseTo('http://radio.player.loudeye.com/LoudSE/radio.jsp?anID=22&aID=1874&dsoID=4')", u'channel seven': u'sendKeys("7")', u'channel two': u'sendKeys("2")', u'play new age': u"say('please stand by')\nbrowseTo('http://release.theplatform.com/deliverable.select?pid=tXSTT6E-SWIv_678ayYHCdIp51IFHhLb&UserID=choiceradio')"} hand_tool_mode = 'RGBA' hand_tool_size = (16, 16) hand_tool_data = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\xd4\x00\x00\x00\xbb\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xd4\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' hand_tool_img = Image.fromstring(hand_tool_mode, hand_tool_size, hand_tool_data) zoom_tool_mode = 'RGBA' zoom_tool_size = (16, 16) zoom_tool_data = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' zoom_tool_img = Image.fromstring(zoom_tool_mode, zoom_tool_size, zoom_tool_data) inspect_tool_mode = 'RGBA' inspect_tool_size = (16, 16) inspect_tool_data = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' inspect_tool_img = Image.fromstring(inspect_tool_mode, inspect_tool_size, inspect_tool_data) sharp_tool_mode = 'RGBA' sharp_tool_size = (16, 16) sharp_tool_img = Image.fromstring(inspect_tool_mode, inspect_tool_size, inspect_tool_data) <<newspeach methods >>= def PILToPy(image): ret = "import Image\n" ret += "\n" ret += "mode = %s\n" % repr(image.mode) ret += "size = %s\n" % repr(image.size) ret += "data = %s\n" % repr(image.tostring()) ret += "img = Image.fromstring(mode, size, data)\n" return ret <<newspeach methods >>= def sorted(x): x.sort() return x <<newspeach methods >>= def PILToWX(image): "convert a PIL image to a wxImage" if (image.mode == 'RGBA'): bk = Image.new("RGB", image.size, (255, 250, 255)) image = Image.composite(image, bk, image) if (image.mode != 'RGB'): image = image.convert('RGB') imageData = image.tostring('raw', 'RGB') imageWx = wxEmptyImage(image.size[0], image.size[1]) imageWx.SetData(imageData) imageWx.SetMaskColour(255, 250, 255) return imageWx <<newspeach methods >>= def WXToPIL(image, mode = 'RGBA'): "convert a wxImage to a PIL RGBA image" imageData = image.GetData() size = (image.GetWidth(), image.GetHeight()) imagePIL = Image.fromstring('RGB', size, imageData) if mode != 'RGB': imagePIL = imagePIL.convert(mode) return imagePIL <<newspeach methods >>= def say(text): global speaker,shell,items speaker.Speak(text) <<newspeach methods >>= """Use the Windows Scripting Host sendKeys function to send keystrokes to the currently focused application. See help on the Microsoft site for values that represent special keys: common ones I use are %{TAB} for Alt-Tab, and {PGDN} and {PGUP} for page down and up, and %{F4} for Alt-F4.""" def sendKeys(keystrokes): global speaker,shell,items shell.SendKeys(keystrokes) <<newspeach methods >>= """Launch a command via the Windows Scripting Host""" def start(command): global speaker,shell shell.Run(command) <<newspeach methods >>= """Launch Internet Explorer, and navigate to a given URL""" def browseTo(location): global speaker,shell,items ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 ie.Navigate(location) <<newspeach methods >>= """Display a message box with the given message and title""" def message(message, title="Message"): dlg = wxMessageDialog(app.frame, message, title, wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() <<newspeach methods >>= class TileCache: << class TileCache methods >> << class TileCache methods >>= def __init__(self, image, megapixel_limit = 1.0): self.image = image self.limit = int(megapixel_limit * 1024 * 1024) self.used = 0 self.cache = [] << class TileCache methods >>= def get_tile(self, pos, size, zoom): key = (pos, size, zoom) for (k, v) in self.cache: if key == k: self.cache.remove((k, v)) self.cache.append((k, v)) return v self.make_space(size[0] * size[1]) end = [pos[0] + size[0], pos[1] + size[1]] if end[0] > self.image.size[0]: end[0] = self.image.size[0] if end[1] > self.image.size[1]: end[1] = self.image.size[1] img = self.image.crop((pos[0], pos[1], end[0], end[1])) img = img.resize((int(img.size[0] * zoom), int(img.size[1] * zoom))) img = PILToWX(img) img_bmp = wxBitmapFromImage(img) self.used += size[0] * size[1] self.cache.append((key, img_bmp)) return img_bmp << class TileCache methods >>= def make_space(self, size): while self.used + size > self.limit and self.cache: self.used -= self.cache[0][0][1][0] * self.cache[0][0][1][1] self.cache.remove(self.cache[0]) <<newspeach methods >>= ## # A standard ImageView tool for panning around the image. class PanTool: << class PanTool methods >> << class PanTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = hand_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id self.__dragging = 0 self.__last_pos = (0, 0) image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Pan") << class PanTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): win = self.__image_view.get_image_window() cursor = wxStockCursor(wxCURSOR_HAND) win.SetCursor(cursor) win.Connect(-1, -1, wxEVT_LEFT_DOWN, self.on_mouse) win.Connect(-1, -1, wxEVT_LEFT_UP, self.on_mouse) win.Connect(-1, -1, wxEVT_MOTION, self.on_mouse) << class PanTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): win = self.__image_view.get_image_window() win.SetCursor(wxSTANDARD_CURSOR) win.Disconnect(-1, -1, wxEVT_LEFT_DOWN) win.Disconnect(-1, -1, wxEVT_LEFT_UP) win.Disconnect(-1, -1, wxEVT_MOTION) << class PanTool methods >>= def on_mouse(self, evt): pos = (evt.m_x, evt.m_y) win = self.__image_view.get_image_window() if evt.GetEventType() == wxEVT_MOTION: if not self.__dragging: return diff = (pos[0] - self.__last_pos[0], pos[1] - self.__last_pos[1]) self.__last_pos = pos origin = self.__image_view.get_origin() self.__image_view.set_origin((origin[0] - diff[0], origin[1] - diff[1])) elif evt.GetEventType() == wxEVT_LEFT_DOWN: win.CaptureMouse() self.__last_pos = pos self.__dragging = 1 elif evt.GetEventType() == wxEVT_LEFT_UP: win.ReleaseMouse() self.__dragging = 0 <<newspeach methods >>= ## # A standard ImageView tool for inspecting colors in the image. class InspectTool: << class InspectTool methods >> << class InspectTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = inspect_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Inspect") self.__id = id self.__dragging = 0 self.__win = None << class InspectTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): win = self.__image_view.get_image_window() cursor = wxStockCursor(wxCURSOR_CROSS) win.SetCursor(cursor) win.Connect(-1, -1, wxEVT_LEFT_DOWN, self.on_mouse) win.Connect(-1, -1, wxEVT_LEFT_UP, self.on_mouse) win.Connect(-1, -1, wxEVT_MOTION, self.on_mouse) << class InspectTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): win = self.__image_view.get_image_window() win.SetCursor(wxSTANDARD_CURSOR) win.Disconnect(-1, -1, wxEVT_LEFT_DOWN) win.Disconnect(-1, -1, wxEVT_LEFT_UP) win.Disconnect(-1, -1, wxEVT_MOTION) << class InspectTool methods >>= def on_mouse(self, evt): pos = (evt.m_x, evt.m_y) win = self.__image_view.get_image_window() if evt.GetEventType() == wxEVT_MOTION: if not self.__dragging: return if self.__image_view.get_image() != None: self.__win.set_position(self.__image_view.window_to_image(pos)) elif evt.GetEventType() == wxEVT_LEFT_DOWN: win.CaptureMouse() self.__win = InspectWindow(self.__image_view) self.__win.Show() self.__dragging = 1 elif evt.GetEventType() == wxEVT_LEFT_UP: win.ReleaseMouse() if self.__win: self.__win.Close() self.__win = None self.__dragging = 0 <<newspeach methods >>= class InspectWindow (wxFrame): << class InspectWindow methods >> << class InspectWindow methods >>= def __init__(self, image_view): wxFrame.__init__(self, None, -1, "Color inspector", style = wxFRAME_TOOL_WINDOW | wxDEFAULT_FRAME_STYLE) display_size = wxDisplaySize() self.SetBackgroundColour(wxSystemSettings_GetSystemColour(wxSYS_COLOUR_BTNFACE)) self.color_view = wxWindow(self, -1, style = wxSUNKEN_BORDER) self.color_view.SetClientSize((80, 80)) m = (96 - self.color_view.GetSize()[0]) / 2 self.color_view.SetPosition((m, m)) self.color_view.SetBackgroundColour(wxColour(0, 0, 0)) base = (m, m + self.color_view.GetSize()[1] + m) across = self.color_view.GetSize()[0] self.red_text = wxStaticText(self, -1, "-", (base[0], base[1]), size = (across / 3, 24), style = wxALIGN_CENTRE | wxST_NO_AUTORESIZE) self.grn_text = wxStaticText(self, -1, "-", (base[0] + across / 3, base[1]), size = (across / 3, 24), style = wxALIGN_CENTRE | wxST_NO_AUTORESIZE) self.blu_text = wxStaticText(self, -1, "-", (base[0] + 2 * across / 3, base[1]), size = (across / 3, 24), style = wxALIGN_CENTRE | wxST_NO_AUTORESIZE) self.SetClientSize((96, base[1] + 16 + m)) size = self.GetSize() self.SetPosition((display_size[0] - size[0] - 32, display_size[1] - size[1] - 32)) EVT_PAINT(self.color_view, self.on_paint) self.image_view = image_view self.pos = (0, 0) << class InspectWindow methods >>= def set_position(self, pos): self.pos = (int(pos[0]), int(pos[1])) img = self.image_view.get_image() try: if img == None: raise IndexError rgb = img.getpixel(self.pos) self.red_text.SetLabel(str(rgb[0])) self.grn_text.SetLabel(str(rgb[1])) self.blu_text.SetLabel(str(rgb[2])) except IndexError: self.red_text.SetLabel("-") self.grn_text.SetLabel("-") self.blu_text.SetLabel("-") self.color_view.Refresh(0) << class InspectWindow methods >>= def on_paint(self, evt): dc = wxPaintDC(self.color_view) img = self.image_view.get_image() if img == None: return for y in range(-2, 3): for x in range(-2, 3): try: rgb = img.getpixel((self.pos[0] + x, self.pos[1] + y)) except IndexError: rgb = (0, 0, 0) if x == 0 and y == 0: dc.SetPen(wxBLACK_PEN) else: dc.SetPen(wxTRANSPARENT_PEN) dc.SetBrush(wxBrush(wxColour(rgb[0], rgb[1], rgb[2]))) dc.DrawRectangle((x + 2) * 16, (y + 2) * 16, 16, 16) <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class ZoomTool: << class ZoomTool methods >> << class ZoomTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = zoom_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Zoom") << class ZoomTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): win = self.__image_view.get_image_window() cursor = wxStockCursor(wxCURSOR_MAGNIFIER) win.SetCursor(cursor) win.Connect(-1, -1, wxEVT_LEFT_UP, self.on_mouse) win.Connect(-1, -1, wxEVT_RIGHT_UP, self.on_mouse) << class ZoomTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): win = self.__image_view.get_image_window() win.SetCursor(wxSTANDARD_CURSOR) win.Disconnect(-1, -1, wxEVT_LEFT_UP) win.Disconnect(-1, -1, wxEVT_RIGHT_UP) << class ZoomTool methods >>= def on_mouse(self, evt): if evt.GetEventType() == wxEVT_LEFT_UP: if evt.ControlDown() or evt.ShiftDown(): self.zoom_out() else: self.zoom_in() elif evt.GetEventType() == wxEVT_RIGHT_UP: self.zoom_out() << class ZoomTool methods >>= def zoom_in(self): zoom = self.__image_view.get_zoom() if zoom >= 1.0: self.__image_view.set_zoom(zoom + 1.0) else: self.__image_view.set_zoom(1.0 / (1.0 / zoom - 1.0)) << class ZoomTool methods >>= def zoom_out(self): zoom = self.__image_view.get_zoom() if zoom > 1.0: self.__image_view.set_zoom(zoom - 1.0) else: self.__image_view.set_zoom(1.0 / (1.0 / zoom + 1.0)) <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class RedTool: << class RedTool methods >> << class RedTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = zoom_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Red") << class RedTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): self.__image_view.set_rgb(1) << class RedTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): self.__image_view.set_rgb(0) <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class GreenTool: << class GreenTool methods >> << class GreenTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = zoom_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Green") << class GreenTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): self.__image_view.set_rgb(2) << class GreenTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): self.__image_view.set_rgb(0) <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class BlueTool: << class BlueTool methods >> << class BlueTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = zoom_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Blue") << class BlueTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): self.__image_view.set_rgb(3) << class BlueTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): self.__image_view.set_rgb(0) <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class SharpTool: << class SharpTool methods >> << class SharpTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = sharp_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Sharpness") << class SharpTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): win = self.__image_view.get_image_window() cursor = wxStockCursor(wxCURSOR_BULLSEYE) win.SetCursor(cursor) win.Connect(-1, -1, wxEVT_LEFT_UP, self.on_mouse) win.Connect(-1, -1, wxEVT_RIGHT_UP, self.on_mouse) << class SharpTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): win = self.__image_view.get_image_window() win.SetCursor(wxSTANDARD_CURSOR) win.Disconnect(-1, -1, wxEVT_LEFT_UP) win.Disconnect(-1, -1, wxEVT_RIGHT_UP) << class SharpTool methods >>= def on_mouse(self, evt): if evt.GetEventType() == wxEVT_LEFT_UP: if evt.ControlDown() or evt.ShiftDown(): self.sharp_out() else: self.sharp_in() elif evt.GetEventType() == wxEVT_RIGHT_UP: self.sharp_out() << class SharpTool methods >>= def sharp_in(self): sharpness = self.__image_view.get_sharp() if sharpness > 4.9: sharpness = 5.0 self.__image_view.set_sharp(sharpness) else: sharpness = sharpness + .1 self.__image_view.set_sharp(sharpness) print sharpness << class SharpTool methods >>= def sharp_out(self): sharpness = self.__image_view.get_sharp() if sharpness < 0.1: sharpness = 0.0 self.__image_view.set_sharp(sharpness) else: sharpness = sharpness - .1 self.__image_view.set_sharp(sharpness) print sharpness <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class ColorTool: << class ColorTool methods >> << class ColorTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = sharp_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Color") << class ColorTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): win = self.__image_view.get_image_window() cursor = wxStockCursor(wxCURSOR_PENCIL) win.SetCursor(cursor) win.Connect(-1, -1, wxEVT_LEFT_UP, self.on_mouse) win.Connect(-1, -1, wxEVT_RIGHT_UP, self.on_mouse) << class ColorTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): win = self.__image_view.get_image_window() win.SetCursor(wxSTANDARD_CURSOR) win.Disconnect(-1, -1, wxEVT_LEFT_UP) win.Disconnect(-1, -1, wxEVT_RIGHT_UP) << class ColorTool methods >>= def on_mouse(self, evt): if evt.GetEventType() == wxEVT_LEFT_UP: if evt.ControlDown() or evt.ShiftDown(): self.color_out() else: self.color_in() elif evt.GetEventType() == wxEVT_RIGHT_UP: self.color_out() << class ColorTool methods >>= def color_in(self): color = self.__image_view.get_color() if color > 4.9: color = 5.0 self.__image_view.set_color(color) else: color = color + .1 self.__image_view.set_color(color) print color << class ColorTool methods >>= def color_out(self): color = self.__image_view.get_color() if color < 0.1: color = 0.0 self.__image_view.set_color(color) else: color = color - .1 self.__image_view.set_color(color) print color <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class BrightTool: << class BrightTool methods >> << class BrightTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = sharp_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Brightness") << class BrightTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): win = self.__image_view.get_image_window() cursor = wxStockCursor(wxCURSOR_SPRAYCAN) win.SetCursor(cursor) win.Connect(-1, -1, wxEVT_LEFT_UP, self.on_mouse) win.Connect(-1, -1, wxEVT_RIGHT_UP, self.on_mouse) << class BrightTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): win = self.__image_view.get_image_window() win.SetCursor(wxSTANDARD_CURSOR) win.Disconnect(-1, -1, wxEVT_LEFT_UP) win.Disconnect(-1, -1, wxEVT_RIGHT_UP) << class BrightTool methods >>= def on_mouse(self, evt): if evt.GetEventType() == wxEVT_LEFT_UP: if evt.ControlDown() or evt.ShiftDown(): self.bright_out() else: self.bright_in() elif evt.GetEventType() == wxEVT_RIGHT_UP: self.bright_out() << class BrightTool methods >>= def bright_in(self): bright = self.__image_view.get_bright() if bright > 4.9: bright = 5.0 self.__image_view.set_bright(bright) else: bright = bright + .1 self.__image_view.set_bright(bright) print bright << class BrightTool methods >>= def bright_out(self): bright = self.__image_view.get_bright() if bright < 0.1: bright = 0.0 self.__image_view.set_bright(bright) else: bright = bright - .1 self.__image_view.set_bright(bright) print bright <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class RestoreTool: << class RestoreTool methods >> << class RestoreTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = sharp_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddSeparator() image_view.get_toolbar().AddSimpleTool(id, bmp, 'Restore all Enhancement Tools', "Restore") image_view.get_toolbar().AddSeparator() << class RestoreTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): self.__image_view.set_sharp(1.0) self.__image_view.set_bright(1.0) self.__image_view.set_color(1.0) self.__image_view.set_contrast(1.0) self.__image_view.set_zoom(1.0) self.__image_view.set_rgb(0) << class RestoreTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): pass <<newspeach methods >>= ## # A standard ImageView tool for zooming in and out of the image. class ContTool: << class ContTool methods >> << class ContTool methods >>= def __init__(self, image_view): self.__image_view = image_view img = sharp_tool_img img = PILToWX(img) bmp = wxBitmapFromImage(img) id = image_view.get_tool_id(self) self.__id = id image_view.get_toolbar().AddTool(id, bmp, isToggle = 1, shortHelpString = "Contrast") << class ContTool methods >>= ## # Called by the ImageView when the tool is activated. def activate(self, id): win = self.__image_view.get_image_window() cursor = wxStockCursor(wxCURSOR_PAINT_BRUSH) win.SetCursor(cursor) win.Connect(-1, -1, wxEVT_LEFT_UP, self.on_mouse) win.Connect(-1, -1, wxEVT_RIGHT_UP, self.on_mouse) << class ContTool methods >>= ## # Called by the ImageView when the tool is deactivated. def deactivate(self, id): win = self.__image_view.get_image_window() win.SetCursor(wxSTANDARD_CURSOR) win.Disconnect(-1, -1, wxEVT_LEFT_UP) win.Disconnect(-1, -1, wxEVT_RIGHT_UP) << class ContTool methods >>= def on_mouse(self, evt): if evt.GetEventType() == wxEVT_LEFT_UP: if evt.ControlDown() or evt.ShiftDown(): self.cont_out() else: self.cont_in() elif evt.GetEventType() == wxEVT_RIGHT_UP: self.cont_out() << class ContTool methods >>= def cont_in(self): contrast = self.__image_view.get_contrast() if contrast > 4.9: contrast = 5.0 self.__image_view.set_contrast(contrast) else: contrast = contrast + .1 self.__image_view.set_contrast(contrast) print contrast << class ContTool methods >>= def cont_out(self): contrast = self.__image_view.get_contrast() if contrast < 0.1: contrast = 0.0 self.__image_view.set_contrast(contrast) else: contrast = contrast - .1 self.__image_view.set_contrast(contrast) print contrast <<newspeach methods >>= ## # A wxPython window used for viewing an image with pan, zoom and inspect # tools built in. # # Note that if you are writing your own tools to use with the <code>ImageView</code> window, you must provide an # <code>__init__</code> method which takes a reference to the <code>ImageView</code> window, an <code>activate</code> # method which is called when the tool is activated and is passed the tool button id, and a <code>deactivate</code> # method which is called when the tool is deactivated and is also passed the tool button id. # # <p> # <code>tools</code> is a list of tools used for constructing the toolbar and <code>image</code> is the initial # image to be viewed. <code>image</code> can be a PIL image or a wxPython Image. class ImageView(wxWindow): << class ImageView methods >> << class ImageView methods >>= def __init__(self, parent, id, tools = [ PanTool, ZoomTool, InspectTool , SharpTool , ColorTool , BrightTool , ContTool , RestoreTool , RedTool , GreenTool , BlueTool], image = None, pos=(-1, -1), size=(-1, -1), style=0, name='ImageView'): wxWindow.__init__(self, parent, id, pos = pos, size = size, style = style, name = name) self.__rgb = 0 self.__image = None self.__cache = None self.__tools = tools self.__tool_id = 20 - 1 self.__tool_ids = {} self.__active_tool = None self.__origin = [0, 0] self.__zoom = 1.0 self.__sharp = 1.0 self.__color = 1.0 self.__bright = 1.0 self.__contrast = 1.0 self.__image_win = wxWindow(self, -1, style = wxSUNKEN_BORDER) self.__toolbar = wxToolBar(self, -1) self.set_image(image) for tool in self.__tools: tool(self) if 20 in self.__tool_ids: self.__set_tool(20) self.__toolbar.Realize() self.__set_constraints() EVT_SIZE(self, self.__on_size) EVT_TOOL(self.__toolbar, -1, self.__on_tool) EVT_PAINT(self.__image_win, self.__on_paint) EVT_SCROLLWIN(self.__image_win, self.__on_scroll) self.__image_win.SetBackgroundColour(wxColour(128, 128, 128)) << class ImageView methods >>= ## # Sets the image being viewed. def set_image(self, image): #if isinstance(image, wxImage): # image = WXToPIL(image) self.__image = image if self.__rgb > 0: colors = self.__image.split() self.__image = colors[self.__rgb - 1] if self.__sharp <> 1.0: sharper = ImageEnhance.Sharpness(self.__image) self.__image = sharper.enhance(self.__sharp) if self.__color <> 1.0: sharper = ImageEnhance.Color(self.__image) self.__image = sharper.enhance(self.__color) if self.__bright <> 1.0: sharper = ImageEnhance.Brightness(self.__image) self.__image = sharper.enhance(self.__bright) if self.__contrast <> 1.0: sharper = ImageEnhance.Contrast(self.__image) self.__image = sharper.enhance(self.__contrast) self.__cache = TileCache(self.__image) self.__image_win.Refresh(0) << class ImageView methods >>= ## # Returns the viewed image. def get_image(self): return self.__image << class ImageView methods >>= ## # Returns the wxPython window displaying the image. This is used by custom tool implementations to # add event handlers or change the cursor when the tool is active. def get_image_window(self): return self.__image_win << class ImageView methods >>= ## # Returns the toolbar window. This is used by custom tool implementations to add tool buttons to the # toolbar. def get_toolbar(self): return self.__toolbar << class ImageView methods >>= ## # Returns a unique tool id for use in the toolbar. This is used by custom tool implementations when they # add tools to the toolbar to ensure that their tool ids don't conflict with those used by other tools. # The custom tool is responsible for adding the tool to the toolbar, but it doesn't need to set up any # event handlers because the ImageView window will call the <code>activate</code> and <code>deactivate</code> # methods of the tool automatically when a tool with the id returned is activated. def get_tool_id(self, tool): self.__tool_id += 1 self.__tool_ids[self.__tool_id] = tool return self.__tool_id << class ImageView methods >>= def __set_tool(self, id): if self.__active_tool: self.__toolbar.ToggleTool(self.__active_tool, 0) if self.__active_tool in self.__tool_ids: self.__tool_ids[self.__active_tool].deactivate(id) self.__toolbar.ToggleTool(id, 1) if id in self.__tool_ids: self.__tool_ids[id].activate(id) self.__active_tool = id << class ImageView methods >>= ## # Sets the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image and # the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def set_zoom(self, zoom): self.__origin = [self.__origin[0] * zoom / self.__zoom, self.__origin[1] * zoom / self.__zoom] self.__zoom = zoom self.__set_scrollbars() self.__get_scrollbars() self.__image_win.Refresh(0) << class ImageView methods >>= ## # Returns the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image # and the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def get_zoom(self): return self.__zoom << class ImageView methods >>= ## # Returns the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image # and the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def get_sharp(self): return self.__sharp << class ImageView methods >>= ## # Returns the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image # and the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def get_color(self): return self.__color << class ImageView methods >>= ## # Returns the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image # and the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def get_bright(self): return self.__bright << class ImageView methods >>= ## # Returns the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image # and the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def get_contrast(self): return self.__contrast << class ImageView methods >>= ## # Sets the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image and # the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def set_sharp(self, sharp): self.__sharp = sharp old_image = self.__image self.set_image(self.__image) self.__image = old_image << class ImageView methods >>= ## # Sets the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image and # the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def set_rgb(self, rgb): self.__rgb = rgb old_image = self.__image self.set_image(self.__image) self.__image = old_image << class ImageView methods >>= ## # Sets the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image and # the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def set_color(self, color): self.__color = color old_image = self.__image self.set_image(self.__image) self.__image = old_image << class ImageView methods >>= ## # Sets the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image and # the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def set_bright(self, bright): self.__bright = bright old_image = self.__image self.set_image(self.__image) self.__image = old_image << class ImageView methods >>= ## # Sets the zoom factor of the image being viewed. 1.0 is a one-for-one pixel correspondence between the image and # the screen, 2.0 is zoomed in by a factor of two and 1.0 / 2.0 is zoomed out by a factor of two. def set_contrast(self, contrast): self.__contrast = contrast old_image = self.__image self.set_image(self.__image) self.__image = old_image << class ImageView methods >>= ## # Sets the on-screen origin of the image being viewed. (0, 0) causes the image to be centered in the image view # window. The origin is applied after the zoom factor. def set_origin(self, origin): self.__origin = list(origin) self.__set_scrollbars() self.__get_scrollbars() self.__image_win.Refresh(0) << class ImageView methods >>= ## # Returns the on-screen origin of the image being viewed. (0, 0) causes the image to be centered in the image view # window. The origin is applied after the zoom factor. def get_origin(self): return [] + self.__origin << class ImageView methods >>= def __set_constraints(self): l = wxLayoutConstraints() l.left.Absolute(0) l.top.Absolute(0) l.height.AsIs() l.width.SameAs(self, wxWidth) self.__toolbar.SetConstraints(l) l = wxLayoutConstraints() l.left.Absolute(0) l.top.Below(self.__toolbar) l.bottom.SameAs(self, wxHeight) l.width.SameAs(self, wxWidth) self.__image_win.SetConstraints(l) self.Layout() << class ImageView methods >>= def __on_tool(self, evt): self.__set_tool(evt.GetId()) << class ImageView methods >>= def __on_scroll(self, evt): if evt.GetOrientation() == wxHORIZONTAL: dim = 0 else: dim = 1 pos = self.__image_win.GetScrollPos(evt.GetOrientation()) self.__image_win.SetScrollPos(evt.GetOrientation(), evt.GetPosition()) if evt.GetEventType() == wxEVT_SCROLLWIN_TOP: self.__image_win.SetScrollPos(evt.GetOrientation(), 0) if evt.GetEventType() == wxEVT_SCROLLWIN_BOTTOM: self.__image_win.SetScrollPos(evt.GetOrientation(), evt.GetScrollRange(evt.GetOrientation())) if evt.GetEventType() == wxEVT_SCROLLWIN_LINEUP: self.__image_win.SetScrollPos(evt.GetOrientation(), pos - 96) if evt.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN: self.__image_win.SetScrollPos(evt.GetOrientation(), pos + 96) if evt.GetEventType() == wxEVT_SCROLLWIN_PAGEUP: self.__image_win.SetScrollPos(evt.GetOrientation(), pos - self.GetClientSize()[1]) if evt.GetEventType() == wxEVT_SCROLLWIN_PAGEDOWN: self.__image_win.SetScrollPos(evt.GetOrientation(), pos + self.GetClientSize()[1]) cw = self.__image_win.GetClientSize()[dim] w = self.__image.size[dim] * self.__zoom self.__origin[dim] = self.__image_win.GetScrollPos(evt.GetOrientation()) - 32 - w / 2 + cw / 2 self.__image_win.Refresh(0) << class ImageView methods >>= ## # Translates a tuple of image coordinates from pixel coordinates in the image window to # pixel coordinates in the image itself. def window_to_image(self, pos): (x, y) = pos (cw, ch) = self.__image_win.GetClientSize() if not self.__image: raise ValueError w = self.__image.size[0] * self.__zoom h = self.__image.size[1] * self.__zoom return (((x - cw / 2) + (w / 2 + self.__origin[0])) / self.__zoom, ((y - ch / 2) + (h / 2 + self.__origin[1])) / self.__zoom) << class ImageView methods >>= ## # Translates a tuple of image coordinates from pixel coordinates in the image to # pixel coordinates in the image window. def image_to_window(self, pos): (x, y) = pos (cw, ch) = self.__image_win.GetClientSize() if not self.__image: raise ValueError w = self.__image.size[0] * self.__zoom h = self.__image.size[1] * self.__zoom return (x * self.__zoom - (w / 2 + self.__origin[0]) + cw / 2, y * self.__zoom - (h / 2 + self.__origin[1]) + ch / 2) << class ImageView methods >>= def __on_size(self, evt): self.Layout() self.__set_scrollbars() self.__get_scrollbars() self.__image_win.Refresh(0) << class ImageView methods >>= def __on_paint(self, evt): dc = wxPaintDC(self.__image_win) if not self.__image: return (cw, ch) = self.__image_win.GetClientSize() bmp = wxEmptyBitmap(cw, ch) mdc = wxMemoryDC() mdc.SelectObject(bmp) mdc.SetBackground(wxBrush(wxColour(128, 128, 128))) mdc.Clear() w = int(self.__image.size[0] * self.__zoom) h = int(self.__image.size[1] * self.__zoom) if w + 64 < cw: self.__origin[0] = 0 if h + 64 < ch: self.__origin[1] = 0 (x, y) = self.image_to_window((0, 0)) mdc.DrawLine(x - 1, y - 1, x + w, y - 1) mdc.DrawLine(x + w, y - 1, x + w, y + h) mdc.DrawLine(x + w, y + h, x - 1, y + h) mdc.DrawLine(x - 1, y + h, x - 1, y - 1) if self.__zoom == 1.0: img_bmp = self.__cache.get_tile((0, 0), self.__image.size, 1.0) mdc.DrawBitmap(img_bmp, x, y) else: ul = self.window_to_image((0, 0)) ul = map(int, map(math.floor, ul)) br = self.window_to_image((cw - 1, ch - 1)) br = map(int, map(math.ceil, br)) if ul[0] < 0: ul[0] = 0 if ul[1] < 0: ul[1] = 0 if br[0] >= self.__image.size[0]: br[0] = self.__image.size[0] if br[1] >= self.__image.size[1]: br[1] = self.__image.size[1] tile_size = int(256 / self.__zoom) if tile_size < 1: tile_size = 1 y = ul[1] / tile_size * tile_size while y < br[1]: x = ul[0] / tile_size * tile_size while x < br[0]: img_bmp = self.__cache.get_tile((x, y), (tile_size, tile_size), self.__zoom) pt = self.image_to_window((x, y)) pt = map(int, pt) mdc.DrawBitmap(img_bmp, pt[0], pt[1]) x += tile_size y += tile_size del mdc dc.DrawBitmap(bmp, 0, 0, 0) self.__set_scrollbars() << class ImageView methods >>= def __set_scrollbars(self): (cw, ch) = self.__image_win.GetClientSize() if not self.__image: return w = self.__image.size[0] * self.__zoom h = self.__image.size[1] * self.__zoom self.__image_win.SetScrollbar(wxHORIZONTAL, w / 2 - cw / 2 + self.__origin[0] + 32, cw, w + 64) self.__image_win.SetScrollbar(wxVERTICAL, h / 2 - ch / 2 + self.__origin[1] + 32, ch, h + 64) << class ImageView methods >>= def __get_scrollbars(self): (cw, ch) = self.__image_win.GetClientSize() if not self.__image: return w = self.__image.size[0] * self.__zoom h = self.__image.size[1] * self.__zoom self.__origin[0] = self.__image_win.GetScrollPos(wxHORIZONTAL) - 32 - w / 2 + cw / 2 self.__origin[1] = self.__image_win.GetScrollPos(wxVERTICAL) - 32 - h / 2 + ch / 2 <<newspeach methods >>= class CameraFrame(wxScrolledWindow): << class CameraFrame methods >> << class CameraFrame methods >>= def __init__(self, parent, number, id = -1, size = wxDefaultSize): wxScrolledWindow.__init__(self, parent, id, wxPoint(0, 0), size, wxSUNKEN_BORDER) #self.cam = Device(devnum=0,showVideoWindow=0) self.cam = Device(devnum=number,showVideoWindow=0) self.Imagethen = self.cam.getImage() self.Imagenow = self.cam.getImage() self.imagedifference = ImageChops.difference(self.Imagethen,self.Imagenow) self.quartercount = 0 self.avarage = 32 EVT_CLOSE(self, self.OnCloseWindow) maintimerID = wxNewId() self.maintimer = wxTimer(self, maintimerID) EVT_TIMER(self, maintimerID, self.OnTimer) self.glob_thing = ImageView(self, -1) StartButtonID = wxNewId() self.StartButton = wxButton(self, StartButtonID, "Go", wxPoint(20, 20)) EVT_BUTTON(self, StartButtonID, self.OnGoClick) self.StartButton.SetBackgroundColour(wxBLUE) self.StartButton.SetForegroundColour(wxWHITE) self.StartButton.SetDefault() StopButtonID = wxNewId() self.StopButton = wxButton(self, StopButtonID, "Stop", wxPoint(260, 20)) EVT_BUTTON(self, StopButtonID, self.OnStopClick) self.StopButton.SetBackgroundColour(wxRED) self.StopButton.SetForegroundColour(wxWHITE) self.main_sizer = wxBoxSizer(wxVERTICAL) self.button_sizer = wxBoxSizer(wxHORIZONTAL) self.button_sizer.Add(self.StartButton, 1, wxEXPAND) self.button_sizer.Add(self.StopButton, 1, wxEXPAND) self.main_sizer.Add(self.button_sizer, 1, wxEXPAND) self.main_sizer.Add(self.glob_thing, 10, wxEXPAND) self.SetSizer(self.main_sizer) self.SetAutoLayout(1) self.main_sizer.Fit(self) << class CameraFrame methods >>= def OnTimer(self, event): self.Imagethen = self.Imagenow self.Imagenow = self.cam.getImage() #self.imagedifference = ImageChops.difference(self.Imagethen,self.Imagenow) #print self.Imagenow.mode, ' ', self.imagedifference.mode #enh = ImageEnhance.Sharpness(self.imagedifference) #img = enh.enhance(self.display1.GetValue()/100) #enh = ImageEnhance.Color(img) #img = enh.enhance(self.display2.GetValue()/100) #self.imagedifference = self.imagedifference.convert('L') self.glob_thing.set_image(self.Imagenow) #stats = ImageStat.Stat(self.imagedifference) #num1 = int(stats.sum[0] / 10000) + int(stats.sum[1] / 10000) + int(stats.sum[2] / 10000) #print img.histogram() #if stats.extrema[0][1] > 100: #self.Imagenow.save('C:\\Python22\\tom\\imgtest\\' + str(int(time.time())) + str(self.quartercount) + '.jpg') #self.imagedifference.save('C:\\Python22\\tom\\imgtest\\diff\\dif' + str(self.quartercount) + str(int(time.time())) + '.jpg') #self.avarage = ((self.avarage + num1) / 2) + 1 #self.quartercount = self.quartercount +1 #if self.quartercount == 4: # self.quartercount = 0 #num1 = int(stats.sum[0] / 10000) + int(stats.sum[1] / 10000) + int(stats.sum[2] / 10000) #self.display1.SetValue(int(stats.extrema[0][1])) #self.display2.Replace(0, 25, str(num1) + ' ') << class CameraFrame methods >>= def OnCloseWindow(self, event): self.Destroy() << class CameraFrame methods >>= def OnGoClick(self, event): self.maintimer.Start(25) << class CameraFrame methods >>= def OnStopClick(self, event): self.maintimer.Stop() <<newspeach methods >>= class PythonSTC(wxStyledTextCtrl): << class PythonSTC methods >> << class PythonSTC methods >>= def __init__(self, parent, ID): wxStyledTextCtrl.__init__(self, parent, ID, style = wxNO_FULL_REPAINT_ON_RESIZE) self.CmdKeyAssign(ord('B'), wxSTC_SCMOD_CTRL, wxSTC_CMD_ZOOMIN) self.CmdKeyAssign(ord('N'), wxSTC_SCMOD_CTRL, wxSTC_CMD_ZOOMOUT) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, string.join(keyword.kwlist)) self.SetProperty("fold", "1") self.SetProperty("tab.timmy.whinge.level", "1") self.SetMargins(0,0) self.SetViewWhiteSpace(false) #self.SetBufferedDraw(false) self.SetEdgeMode(wxSTC_EDGE_BACKGROUND) self.SetEdgeColumn(78) # Setup a margin to hold fold markers #self.SetFoldFlags(16) ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER? self.SetMarginType(2, wxSTC_MARGIN_SYMBOL) self.SetMarginMask(2, wxSTC_MASK_FOLDERS) self.SetMarginSensitive(2, true) self.SetMarginWidth(2, 12) if 0: # simple folder marks, like the old version self.MarkerDefine(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_ARROW, "navy", "navy") self.MarkerDefine(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_ARROWDOWN, "navy", "navy") # Set these to an invisible mark self.MarkerDefine(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BACKGROUND, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_BACKGROUND, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_BACKGROUND, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_BACKGROUND, "white", "black") else: # more involved "outlining" folder marks self.MarkerDefine(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUSCONNECTED, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUSCONNECTED, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_TCORNER, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_LCORNER, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_VLINE, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS, "white", "black") self.MarkerDefine(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS, "white", "black") EVT_STC_UPDATEUI(self, ID, self.OnUpdateUI) EVT_STC_MARGINCLICK(self, ID, self.OnMarginClick) # Make some styles, The lexer defines what each style is used for, we # just have to define what each style looks like. This set is adapted from # Scintilla sample property files. self.StyleClearAll() # Global default styles for all languages self.StyleSetSpec(wxSTC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces) self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, "face:%(other)s" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold") # Python styles # White space self.StyleSetSpec(wxSTC_P_DEFAULT, "fore:#808080,face:%(helv)s,size:%(size)d" % faces) # Comment self.StyleSetSpec(wxSTC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % faces) # Number self.StyleSetSpec(wxSTC_P_NUMBER, "fore:#007F7F,size:%(size)d" % faces) # String self.StyleSetSpec(wxSTC_P_STRING, "fore:#7F007F,italic,face:%(times)s,size:%(size)d" % faces) # Single quoted string self.StyleSetSpec(wxSTC_P_CHARACTER, "fore:#7F007F,italic,face:%(times)s,size:%(size)d" % faces) # Keyword self.StyleSetSpec(wxSTC_P_WORD, "fore:#00007F,bold,size:%(size)d" % faces) # Triple quotes self.StyleSetSpec(wxSTC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % faces) # Triple double quotes self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % faces) # Class name definition self.StyleSetSpec(wxSTC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % faces) # Function or method name definition self.StyleSetSpec(wxSTC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % faces) # Operators self.StyleSetSpec(wxSTC_P_OPERATOR, "bold,size:%(size)d" % faces) # Identifiers self.StyleSetSpec(wxSTC_P_IDENTIFIER, "fore:#808080,face:%(helv)s,size:%(size)d" % faces) # Comment-blocks self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % faces) # End of line where string is not closed self.StyleSetSpec(wxSTC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % faces) self.SetCaretForeground("BLUE") EVT_KEY_DOWN(self, self.OnKeyPressed) << class PythonSTC methods >>= def OnKeyPressed(self, event): if self.CallTipActive(): self.CallTipCancel() key = event.KeyCode() if key == 32 and event.ControlDown(): pos = self.GetCurrentPos() # Tips if event.ShiftDown(): self.CallTipSetBackground("yellow") self.CallTipShow(pos, 'param1, param2') # Code completion else: #lst = [] #for x in range(50000): # lst.append('%05d' % x) #st = string.join(lst) #print len(st) #self.AutoCompShow(0, st) kw = keyword.kwlist[:] kw.append("zzzzzz") kw.append("aaaaa") kw.append("__init__") kw.append("zzaaaaa") kw.append("zzbaaaa") kw.append("this_is_a_longer_value") kw.append("this_is_a_much_much_much_much_much_much_much_longer_value") kw.sort() # Python sorts are case sensitive self.AutoCompSetIgnoreCase(false) # so this needs to match self.AutoCompShow(0, string.join(kw)) else: event.Skip() << class PythonSTC methods >>= def OnUpdateUI(self, evt): # check for matching braces braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) styleBefore = self.GetStyleAt(caretPos - 1) # check before if charBefore and chr(charBefore) in "[]{}()" and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 # check after if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in "[]{}()" and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) #pt = self.PointFromPosition(braceOpposite) #self.Refresh(true, wxRect(pt.x, pt.y, 5,5)) #print pt #self.Refresh(false) << class PythonSTC methods >>= def OnMarginClick(self, evt): # fold and unfold as needed if evt.GetMargin() == 2: if evt.GetShift() and evt.GetControl(): self.FoldAll() else: lineClicked = self.LineFromPosition(evt.GetPosition()) if self.GetFoldLevel(lineClicked) & wxSTC_FOLDLEVELHEADERFLAG: if evt.GetShift(): self.SetFoldExpanded(lineClicked, true) self.Expand(lineClicked, true, true, 1) elif evt.GetControl(): if self.GetFoldExpanded(lineClicked): self.SetFoldExpanded(lineClicked, false) self.Expand(lineClicked, false, true, 0) else: self.SetFoldExpanded(lineClicked, true) self.Expand(lineClicked, true, true, 100) else: self.ToggleFold(lineClicked) << class PythonSTC methods >>= def FoldAll(self): lineCount = self.GetLineCount() expanding = true # find out if we are folding or unfolding for lineNum in range(lineCount): if self.GetFoldLevel(lineNum) & wxSTC_FOLDLEVELHEADERFLAG: expanding = not self.GetFoldExpanded(lineNum) break; lineNum = 0 while lineNum < lineCount: level = self.GetFoldLevel(lineNum) if level & wxSTC_FOLDLEVELHEADERFLAG and \ (level & wxSTC_FOLDLEVELNUMBERMASK) == wxSTC_FOLDLEVELBASE: if expanding: self.SetFoldExpanded(lineNum, true) lineNum = self.Expand(lineNum, true) lineNum = lineNum - 1 else: lastChild = self.GetLastChild(lineNum, -1) self.SetFoldExpanded(lineNum, false) if lastChild > lineNum: self.HideLines(lineNum+1, lastChild) lineNum = lineNum + 1 << class PythonSTC methods >>= def Expand(self, line, doExpand, force=false, visLevels=0, level=-1): lastChild = self.GetLastChild(line, level) line = line + 1 while line <= lastChild: if force: if visLevels > 0: self.ShowLines(line, line) else: self.HideLines(line, line) else: if doExpand: self.ShowLines(line, line) if level == -1: level = self.GetFoldLevel(line) if level & wxSTC_FOLDLEVELHEADERFLAG: if force: if visLevels > 1: self.SetFoldExpanded(line, true) else: self.SetFoldExpanded(line, false) line = self.Expand(line, doExpand, force, visLevels-1) else: if doExpand and self.GetFoldExpanded(line): line = self.Expand(line, true, force, visLevels-1) else: line = self.Expand(line, false, force, visLevels-1) else: line = line + 1; return line << class PythonSTC methods >>= def SetValue(self, text): self.SetText(text) <<newspeach methods >>= """The event handler for speech events""" class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")): << class ContextEvents methods >> << class ContextEvents methods >>= def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): global speaker,shell,items newResult = win32com.client.Dispatch(Result) print newResult.PhraseInfo.GetText() try: # Exec the appropriate listbox entry exec items[newResult.PhraseInfo.GetText()] except: # If execution fails, display a messagebox with error and cause etype, value, tb = sys.exc_info() message = (str(etype)+":"+str(value)+ "\nat line "+`tb.tb_next.tb_lineno`+ "for text '"+newResult.PhraseInfo.GetText()+"'") dlg = wxMessageDialog(None, message, 'Exception: '+str(etype), wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() <<newspeach methods >>= class MyFrame(wxFrame): << class MyFrame methods >> << class MyFrame methods >>= def __init__(self, parent, id, title): wxFrame.__init__(self, parent, id, title, wxDefaultPosition, wxDefaultSize) global speaker,shell,items self.items = items self.splitter = wxSplitterWindow(self, -1, style=wxNO_3D|wxSP_3D) self.notebook = wxNotebook(self.splitter, -1, style = wxNB_LEFT) self.ie = wxIEHtmlWin(self.notebook, -1, style = wxNO_FULL_REPAINT_ON_RESIZE) self.ie.GoHome() self.splitter.SetSashPosition(135) EVT_CLOSE(self, self.OnCloseWindow) self.mainmenu = wxMenuBar() menu=wxMenu() exitID=wxNewId() menu.Append(exitID, '&Load', 'Load Data') EVT_MENU(self, exitID, self.OnLoadData) exitID=wxNewId() menu.Append(exitID, '&Save', 'Save Data') EVT_MENU(self, exitID, self.OnSaveData) exitID=wxNewId() menu.Append(exitID, 'Save &As', 'Save Data As') EVT_MENU(self, exitID, self.OnSaveAsData) exitID=wxNewId() menu.Append(exitID, '&Clear', 'Clear Data') EVT_MENU(self, exitID, self.OnClearData) self.mainmenu.Append (menu, '&Data') self.SetMenuBar (self.mainmenu) self.LISTBOX_ID = wxNewId() self.EDITOR_ID = wxNewId() tb = self.CreateToolBar(wxTB_HORIZONTAL|wxNO_BORDER|wxTB_FLAT) stop_bmp = wxImage('c:\\python22\\tom\\bitmaps\\STOP.BMP', wxBITMAP_TYPE_BMP).ConvertToBitmap() go_bmp = wxImage('c:\\python22\\tom\\bitmaps\\GO.BMP', wxBITMAP_TYPE_BMP).ConvertToBitmap() internet_bmp = wxImage('c:\\python22\\tom\\bitmaps\\INTERNAT.BMP', wxBITMAP_TYPE_BMP).ConvertToBitmap() add_bmp = wxImage('c:\\python22\\tom\\bitmaps\\open.bmp', wxBITMAP_TYPE_BMP).ConvertToBitmap() delete_bmp = wxImage('c:\\python22\\tom\\bitmaps\\copy.bmp', wxBITMAP_TYPE_BMP).ConvertToBitmap() test_bmp = wxImage('c:\\python22\\tom\\bitmaps\\new.bmp', wxBITMAP_TYPE_BMP).ConvertToBitmap() set_bmp = wxImage('c:\\python22\\tom\\bitmaps\\tog1.bmp', wxBITMAP_TYPE_BMP).ConvertToBitmap() self.CreateStatusBar() tool1 = wxNewId() tool2 = wxNewId() tool3 = wxNewId() tool4 = wxNewId() tool5 = wxNewId() tool6 = wxNewId() tool7 = wxNewId() tool8 = wxNewId() tb.AddSimpleTool(tool1, stop_bmp, "Stop", "Stop Language interpitation") EVT_TOOL(self, tool1, self.OnTurnOffClick) EVT_TOOL_RCLICKED(self, tool1, self.OnTurnOffClick) tb.AddSeparator() tb.AddSimpleTool(tool2, go_bmp, "Go", "Start Language interpitation") EVT_TOOL(self, tool2, self.OnTurnOnClick) EVT_TOOL_RCLICKED(self, tool2, self.OnTurnOnClick) tb.AddSeparator() tb.AddSimpleTool(tool3, add_bmp, "Add", "Add New Command") EVT_TOOL(self, tool3, self.OnAddClick) EVT_TOOL_RCLICKED(self, tool3, self.OnAddClick) tb.AddSeparator() tb.AddSimpleTool(tool4, delete_bmp, "Delete", "Delete Command") EVT_TOOL(self, tool4, self.OnDeleteClick) EVT_TOOL_RCLICKED(self, tool4, self.OnDeleteClick) tb.AddSeparator() tb.AddSimpleTool(tool5, test_bmp, "Test", "Test Command") EVT_TOOL(self, tool5, self.OnTestClick) EVT_TOOL_RCLICKED(self, tool5, self.OnTestClick) tb.AddSeparator() tb.AddSimpleTool(tool6, set_bmp, "Set", "Sets the Text in the Wordlist") EVT_TOOL(self, tool6, self.OnTextEntered) EVT_TOOL_RCLICKED(self, tool6, self.OnTextEntered) tb.AddSeparator() #tb.AddSimpleTool(tool7, internet_bmp, "Internet", "Open Internet Window") #EVT_TOOL(self, tool7, self.OnToolClick) #EVT_TOOL_RCLICKED(self, tool7, self.OnToolRClick) #tb.AddSeparator() #tb.AddSimpleTool(tool8, internet_bmp, "Code", "Open code Window") #EVT_TOOL(self, tool8, self.OnCodelClick) #EVT_TOOL_RCLICKED(self, tool8, self.OnCodelClick) #tb.AddSeparator() EVT_TOOL_ENTER(self, -1, self.OnToolEnter) #EVT_TOOL_RCLICKED(self, -1, self.OnToolRClick) # Match all tb.Realize() self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer") self.context = self.listener.CreateRecoContext() self.grammar = self.context.CreateGrammar() self.grammar.DictationSetState(0) self.ListItemsRule = self.grammar.Rules.Add("ListItemsRule", 33, 0) self.events = ContextEvents(self.context) self.turnedOn = true self.SetWords() self.panelID = wxNewId() cameraID = wxNewId() self.camera = CameraFrame(self.notebook, 1, id = -1, size = wxDefaultSize) self.listBox = wxListBox(self.splitter, self.LISTBOX_ID, wxPoint(10, 10), wxSize(120, 200),sorted(self.items.keys()), wxLB_SINGLE) self.editor = PythonSTC(self.notebook, self.panelID) self.splitter.SetMinimumPaneSize(20) self.notebook.AddPage(self.editor, "Code") self.notebook.AddPage(self.ie, "Internet") self.notebook.AddPage(self.camera, "Camera") try: self.camera2 = CameraFrame(self.notebook, 0, id = -1, size = wxDefaultSize) self.notebook.AddPage(self.camera2, "Camera2") except: pass EVT_LISTBOX(self, self.LISTBOX_ID, self.OnListBoxSelect) self.listBox.SetSelection(0) self.editor.SetValue( self.items[self.listBox.GetStringSelection()] ) self.notebook.SetSelection(0) self.splitter.SplitVertically(self.listBox, self.notebook) << class MyFrame methods >>= def SetWords(self): self.ListItemsRule.Clear() if self.turnedOn: print "Setting words - turned on" [ self.ListItemsRule.InitialState.AddWordTransition(None, word) for word in self.items.keys() ] else: print "Setting words - OFF" self.ListItemsRule.InitialState.AddWordTransition(None, "computer wake up") self.grammar.Rules.Commit() self.grammar.CmdSetRuleState("ListItemsRule", 1) self.grammar.Rules.Commit() << class MyFrame methods >>= def GetStory(self): stories = urllib2.urlopen('http://www.unknowncountry.com/') page = stories.read() substories = page[page.find('<table border=0 cellpadding=5 cellspacing=0 width=430 align=center>'):page.rfind('<table border=0 cellpadding=5 cellspacing=0 width=430 align=center>')] stories.close() substories = substories.replace('src=' , 'src=http://www.unknowncountry.com') substories = substories.replace('href=' , 'href=http://www.unknowncountry.com') self.ie.LoadString(substories) << class MyFrame methods >>= def OnAddClick(self,event): dlg = wxTextEntryDialog(self, 'Text to recognize', "New item") if dlg.ShowModal() == wxID_OK: self.items[dlg.GetValue()] = "" self.listBox.Set(sorted(self.items.keys())) self.listBox.SetStringSelection(dlg.GetValue()) self.editor.SetValue( self.items[self.listBox.GetStringSelection()] ) self.SetWords() dlg.Destroy() << class MyFrame methods >>= def OnDeleteClick(self,event): del self.items[ self.listBox.GetStringSelection() ] self.listBox.Set(sorted(self.items.keys())) self.listBox.SetSelection(0) self.editor.SetValue( self.items[self.listBox.GetStringSelection()] ) self.SetWords() << class MyFrame methods >>= def OnListBoxSelect(self,event): self.editor.SetValue(self.items[self.listBox.GetStringSelection()] ) << class MyFrame methods >>= def OnTestClick(self, event): codeToExecute = self.items[self.listBox.GetStringSelection()] try: exec codeToExecute except: etype, value, tb = sys.exc_info() message = (str(etype)+":"+str(value)+ "\nat line "+`tb.tb_next.tb_lineno`) dlg = wxMessageDialog(self, message, 'Exception: '+str(etype), wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() << class MyFrame methods >>= def OnTextEntered(self, event): the_text = self.editor.GetText() the_text = the_text.replace('\r', '') print the_text self.items[self.listBox.GetStringSelection()] = the_text << class MyFrame methods >>= def OnSaveAsData(self, event): pass << class MyFrame methods >>= def OnClearData(self, event): pass << class MyFrame methods >>= def OnToolClick(self, event): pass << class MyFrame methods >>= def OnCodelClick(self, event): self.splitter.SplitVertically(self.listBox, self.editor) << class MyFrame methods >>= def OnToolRClick(self, event): self.splitter.SplitVertically(self.listBox, self.ie) << class MyFrame methods >>= def OnToolEnter(self, event): pass << class MyFrame methods >>= def OnLoadData(self, event): try: self.items = pickle.load(open('save.p')) except IOError: self.items = {u'turn on tee vee': u'sendKeys("^(%z)")', u'channel forty two': u'sendKeys("42")', u'close program now': u'sendKeys("%( )c")', u'channel thirty six': u'sendKeys("36")', u'play woman rock': u"say('please stand by')\nbrowseTo('http://release.theplatform.com/deliverable.select?pid=Mf5zobHmqTDt6bze2ThXCugPnEUpJQQh&UserID=choiceradio')", u'channel sixteen': u'sendKeys("16")', u'open tee vee guide': u"browseTo('http://tv.yahoo.com/grid?lineup=us_AZ02423&dur=&.intl=us&startdate=0&starthour=0&genres=0')", u'channel thirty four': u'sendKeys("34")', u'channel forty four': u'sendKeys("44")', u'play raggae': u"say('please stand by')\nbrowseTo('http://www.totallyradio.com/asx/live/reggae.asx')", u'computer': u"say('working')", u'channel forty': u'sendKeys("40")', u'channel thirty eight': u'sendKeys("38")', u'stop music': u'sendKeys("^(s)")', u'play mellow yellow': u"say('please stand by')\nbrowseTo('http://radio.player.loudeye.com/LoudSE/radio.jsp?anID=22&aID=1874&dsoID=4')", u'channel seven': u'sendKeys("7")', u'channel two': u'sendKeys("2")', u'play new age': u"say('please stand by')\nbrowseTo('http://release.theplatform.com/deliverable.select?pid=tXSTT6E-SWIv_678ayYHCdIp51IFHhLb&UserID=choiceradio')"} << class MyFrame methods >>= def OnSaveData(self, event): pickle.dump(self.items, open('save.p', 'w')) << class MyFrame methods >>= def OnCloseWindow(self, event): pickle.dump(self.items, open('save.p', 'w')) if hasattr(self, "tbicon"): del self.tbicon self.Destroy() << class MyFrame methods >>= def OnTurnOnClick(self, event): if not self.turnedOn: self.turnedOn = true self.SetWords() << class MyFrame methods >>= def OnTurnOffClick(self, event): if (self.turnedOn): self.turnedOn = false self.SetWords() <<newspeach methods >>= class MyApp(wxApp): << class MyApp methods >> << class MyApp methods >>= def OnInit(self): # Create an instance of our customized Frame class self.frame = MyFrame(None, -1, "Speech macros") self.frame.Show(true) # Tell wxWindows that this is our main window self.SetTopWindow(self.frame) # Return a success flag return true