Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """ A simple Tkinter Gui for creating a Sentimental Dataset.
- This version uses Checkbuttons because most phrases can be
- assigned to more than one emotion :)
- The dictionaries are loaded from and persisted with cPickle.
- The imported dictionaries are in the format:
- {7875: 'the story is gripping, and of extreme importance.', 7876: ...}
- The resultant dataset is in the format:
- {'this story is great' : [0, 1, 1, 0, 0, 1, 0, 0, 0], 'humbug': ...}
- --lolamontes69
- """
- from Tkinter import *
- from tkFileDialog import *
- import cPickle
- from time import sleep
- from tkMessageBox import askyesno
- class HoldingClass:
- pass
- hc=HoldingClass()
- hc.tempDic = {"frog": "croak", "cat": "meow", "dog": "woof", "sheep": "baa"}
- hc.tempKeys = hc.tempDic.keys()
- hc.newDataset = {}
- class CheckB:
- ''' A class of checkbuttons '''
- def __init__(self, master, r=0, c=0, rsp=1):
- textlist = [["POSITIVE\nSURPRISE","HAPPY","NEUTRAL","SAD","NEGATIVE\nSURPRISE"],
- ["AROUSAL","LOVE\nAFFECTION","NEUTRAL","FEAR","ANGER\nDISGUST"]]
- self.text = textlist[r][c]
- self.var = DoubleVar()
- self.i = Checkbutton(master, text=self.text,
- fg="blue", bg="black", height=3, width=9, font=('Verdana', 14, "bold"),
- padx=5, pady=5)
- self.i.bind("<Button-1>", self.colorChange)
- self.var.set(0)
- self.i.grid(row=r,column=c,rowspan=rsp)
- def colorChange(self,*args):
- ''' Change textcolor of button and do var.set() '''
- if int(self.var.get())==0:
- self.var.set(1)
- self.i.config(fg="red")
- else:
- self.var.set(0)
- self.i.config(fg="blue")
- def resetVar(self,*args):
- ''' reset checkbutton '''
- self.var.set(0)
- self.i.config(fg="blue")
- self.i.deselect()
- def loadcPks(filename):
- ''' Load dictionary from cPickle '''
- fr = open(filename)
- pickledDic = cPickle.load(fr)
- fr.close()
- return pickledDic
- def loadDict():
- ''' Get name of dict to load '''
- filename=askopenfilename(filetypes=[("All Files", "*")])
- hc.tempDic = loadcPks(filename)
- hc.tempKeys = hc.tempDic.keys()
- # Add first quote to textframe
- hc.quote=hc.tempDic[hc.tempKeys[0]]
- updateTextframe()
- def makeCommandMenu():
- ''' Make top menu '''
- CmdBtn = Menubutton(hc.mBar, text='File', bg="black", fg="red", underline=0)
- CmdBtn.pack(side=LEFT, padx="2m")
- CmdBtn.menu = Menu(CmdBtn)
- for lab, cmd in [('Load dictionary...',loadDict),
- ('Save original dictionary...',saveOrigDict),
- ('Save classified dictionary...',saveDict),('Quit',quitGui)]:
- CmdBtn.menu.add_command(label=lab, underline=0, foreground="red",
- background='black', activebackground='green',
- command=cmd)
- CmdBtn['menu'] = CmdBtn.menu
- return CmdBtn
- def processResults(*args):
- ''' Process and update '''
- resList = []
- #get results and reset checkbuttons
- for a in hc.slist:
- resList.append(int(a.var.get()))
- a.resetVar()
- # add results to dictionary and update textframe with new phrase
- if len(hc.tempKeys)>1:
- hc.newDataset[hc.tempDic[hc.tempKeys[0]]] = resList
- print hc.tempDic[hc.tempKeys[0]],":",resList
- del hc.tempDic[hc.tempKeys[0]]
- del hc.tempKeys[0]
- hc.quote=hc.tempDic[hc.tempKeys[0]]
- updateTextframe()
- # if we have ran out of phrases....
- else:
- hc.newDataset[hc.tempDic[hc.tempKeys[0]]] = resList
- print hc.tempDic[hc.tempKeys[0]],":",resList
- hc.tempDic = None
- hc.tempKeys = None
- hc.quote="End of dictionary"
- updateTextframe("red")
- hc.frm2.destroy()
- hc.xf1.destroy()
- hc.b1.config(text="EXIT")
- hc.b1.unbind("<Button-1>")
- hc.b1.bind("<Button-1>",quitGui)
- hc.root.update_idletasks()
- saveDict()
- # add do you want to save your progress dialogs on window shut too
- def quitGui(*args):
- ''' Close the GUI '''
- a=askyesno(message="Do you want to save\nyour progress?")
- if not a:
- try: hc.root.destroy()
- except: pass
- else:
- try:
- saveDict()
- hc.root.destroy()
- except: pass
- def saveDict():
- ''' Persist the classifier in cPickles '''
- try:
- filename=asksaveasfilename(filetypes=[("All Files", "*")])
- f = open(filename, 'w')
- cPickle.dump(hc.newDataset, f) # a list
- f.close()
- except:
- prev = hc.text1.get(0.0,END).strip()
- sleep(0.5)
- hc.quote="Dictionary not saved"
- updateTextframe("red")
- hc.root.update()
- sleep(4)
- hc.quote=prev
- updateTextframe()
- hc.root.update_idletasks()
- def saveOrigDict():
- ''' Persist the classifier in cPickles '''
- filename=asksaveasfilename(filetypes=[("All Files", "*")])
- try:
- f = open(filename, 'w')
- cPickle.dump(hc.tempDic, f) # a list
- f.close()
- except:
- prev = hc.text1.get(0.0,END).strip()
- sleep(0.5)
- hc.quote="Dictionary not saved"
- updateTextframe("red")
- hc.root.update()
- sleep(3)
- hc.quote=prev
- updateTextframe("red")
- hc.root.update_idletasks()
- def updateTextframe(fore="green"):
- hc.text1.config(fg=fore)
- hc.text1.delete(0.0,END)
- hc.text1.insert(END,hc.quote)
- def mainGui():
- hc.root = Tk()
- hc.root.title('Phrase Classifier')
- hc.root.config(borderwidth=10, background="black")
- # Menubar
- hc.mBar = Frame(hc.root, bg="black", borderwidth=2)
- hc.mBar.pack(fill=X)
- CmdBtn = makeCommandMenu()
- hc.mBar.tk_menuBar(CmdBtn)
- # Label above textframe
- hc.xf1 = Frame(hc.root, borderwidth=2, pady=5, background="black")
- Label(hc.xf1, text="Which emotions are contained in this phrase? ",
- font=('Verdana', 14, "bold"), width=76, bg="black", fg="white",
- justify=CENTER).grid(row=0, padx=0, pady=15)
- hc.xf1.pack(side="top")
- # Textframe
- xf2 = Frame(hc.root, borderwidth=2, pady=30, background="black")
- hc.quote=hc.tempDic[hc.tempKeys[0]]
- hc.text1 = Text(xf2, height=5, width=50, bg="black", fg="green",font=('Verdana', 18, "bold"))
- hc.text1.grid(row=1, padx=5, pady=15)
- hc.text1.insert(END,hc.quote)
- xf2.pack(side="top")
- # Process data button
- hc.frm3 = Frame(hc.root, borderwidth=2, pady=10, background="black")
- hc.b1 = Button(hc.frm3, text="NEXT PHRASE",height=1,fg="white", bg="black",
- relief=RAISED, border=5, font=('Verdana', 18, "bold"))
- hc.b1.grid(row=2, column=2, padx=5, pady=5)
- hc.b1.bind("<Button-1>",processResults)
- hc.frm3.pack(side=BOTTOM)
- # Checkbuttons
- hc.frm2 = Frame(hc.root, borderwidth=2, pady=30, background="black")
- hc.slist = []
- for i in range(2):
- for j in range(5):
- if j==2:
- if i==0: hc.slist.append(CheckB(hc.frm2,i,j,2))
- else: hc.slist.append(CheckB(hc.frm2,i,j))
- hc.frm2.pack(side=BOTTOM)
- hc.root.mainloop()
- if __name__ == "__main__":
- mainGui()
Advertisement
Add Comment
Please, Sign In to add comment