lolamontes69

Tkinter GUI for Virtual Assistant Project.

Jan 6th, 2014
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.88 KB | None | 0 0
  1. """ A simple GUI that plays videos (by embedding mplayer output),
  2.    and classifies inputted text based upon datasets derived from
  3.    sentiWordNet and the Stanford Sentiment Treebank.
  4.    Still in a basic state and not that padded out yet but the
  5.    GUI is still neat and functional :)
  6.                          --lolamontes69
  7. """
  8.  
  9. #!/usr/bin/env python
  10.  
  11. from Tkinter import *
  12. import commands
  13. import cPickle
  14. from os import path
  15. from re import compile as re_compile
  16.  
  17.  
  18. class HoldingClass:
  19.     ''' For keeping Global Variables + Constants '''
  20.     def __init__(self):
  21.         self.loadDics()
  22.         self.vidStore()
  23.         self.sentimentTotal = 0
  24.         self.frame    = None
  25.         self.frame1   = None
  26.         self.master   = None
  27.         self.fwid     = None
  28.         self.reply    = "This is the voice from AI."
  29.  
  30.     def loadDics(self):
  31.         print "Initialising..."
  32.  
  33.         if path.isfile("lib/sentiWordNet1.cPk"):
  34.             self.senti = loadcPks("lib/sentiWordNet1.cPk")
  35.             print "loaded sentiWordNet1"
  36.         else: self.senti = {}
  37.  
  38.         if path.isfile("lib/sentiMovie.cPk"):
  39.             self.sentiMovie = loadcPks("lib/sentiMovie.cPk")
  40.             print "loaded sentiMovie"
  41.         else: self.sentiMovie = {}
  42.  
  43.     def vidStore(self):
  44.         self.testVid  = "vids/002.flv"
  45.         self.testVid1 = "vids/MOV131.flv"
  46.  
  47.  
  48. def playV(vidname):
  49.     ''' Embed video into hc.frame '''
  50.     hc.textframe.destroy()
  51.     hc.frame.config(width=450, height=256)
  52.     hc.frame.update()
  53.     hc.fwid = hc.frame.winfo_id()
  54.     mpc = "mplayer -vo x11 -wid %s %s"%(hc.fwid, vidname)    # use x11 video driver
  55.     output = commands.getoutput(mpc)                    
  56.     del output
  57.  
  58. def choseVid(event):
  59.     ''' Text parse for textframe1'''
  60.     a = hc.textframe1.get(0.0,END).strip()
  61.     hc.textframe1.delete(0.0, END)
  62.     if a.lower()=='one':
  63.         playV(hc.testVid)
  64.         hc.reply = 'That was a ballet video.'
  65.     elif a.lower()=='two':
  66.         playV(hc.testVid1)
  67.         hc.reply = 'That was a roundabout video.'
  68.     elif a.lower()=='quit': hc.master.destroy()
  69.     else:
  70.         score  = getScore(getwords(a.lower()),hc.senti)
  71.         score1 = getScore(getwords(a.lower()),hc.sentiMovie)
  72.         score2 = (score+score1)/2.0
  73.         hc.sentimentTotal += score2
  74.  
  75.         hc.reply  = "senti rating = %0.3f\n" % score
  76.         hc.reply += "stanford rating = %0.3f\n" % score1
  77.         hc.reply += "avg rating = %0.3f\n" % score2
  78.         hc.reply += "current sentiment = %0.3f" % hc.sentimentTotal
  79.  
  80.         hc.textframe.delete(0.0, END)
  81.         hc.textframe.insert(END, hc.reply)
  82.         hc.master.update()
  83.  
  84.         # Use sentimentalTotal score as a trigger
  85.         if hc.sentimentTotal>2:
  86.             hc.sentimentTotal=0
  87.             playV(hc.testVid)
  88.             hc.reply = 'That was a ballet video.'
  89.         elif hc.sentimentTotal<-2:
  90.             hc.sentimentTotal=0
  91.             playV(hc.testVid1)
  92.             hc.reply = 'That was a roundabout video.'
  93.  
  94.     # Clear video frame then recreate textframe1
  95.     try:
  96.         hc.frame.destroy()
  97.         main()
  98.     except: pass      # When master has been destroyed.
  99.  
  100. def getwords(doc,phraselen=4):
  101.     ''' Create features from the input text '''
  102.     splitter = re_compile('\\W*')
  103.     words    = [s.lower() for s in splitter.split(doc) if len(s)>2 and len(s)<20]
  104.     for a in range(len(words)-phraselen+1):
  105.         phrases = ' '.join(words[a:a+phraselen])
  106.         words.append(phrases)
  107.     return dict([(w,1) for w in words])
  108.  
  109. def getScore(dic,dic1):
  110.     ''' Calculate an average score between -1 and 1 '''
  111.     incount, total = 0, 0
  112.     for a in dic:
  113.         if a in dic1:
  114.             total   += float(dic1[a][0])
  115.             total   -= float(dic1[a][1])
  116.             incount += 1
  117.     if incount>0: return total/float(incount)
  118.     else: return 0
  119.  
  120. def loadcPks(filename):
  121.     ''' Load dictionaries stored as cPickles '''
  122.     fr = open(filename)
  123.     pickledDic = cPickle.load(fr)
  124.     fr.close()
  125.     return pickledDic
  126.  
  127. def main():
  128.     ''' After the initial creation of the gui this recreates and updates hc.frame '''
  129.     if hc.master==None:
  130.         hc.master = Tk()
  131.         hc.master.title('AI Project')
  132.         hc.master.config(bg="black",width=450)
  133.         # position in center screen
  134.         screen_width = hc.master.winfo_screenwidth()
  135.         screen_height = hc.master.winfo_screenheight()
  136.         scwid = (int(screen_width)-450)/2
  137.         schei = (int(screen_height)-256)/2
  138.         scpos = '+%d+%d' % (scwid, schei)
  139.         hc.master.geometry(scpos)  # '200x100+200+100' = tk size,screenposition
  140.  
  141.     hc.frame = Frame(hc.master, bg="black", colormap="new")
  142.  
  143.     hc.textframe = Text(hc.frame, wrap=WORD, background='black', fg='green',
  144.                         font=('sans', 12), height = 11, width = 40, borderwidth=1, pady=5)
  145.     hc.textframe.insert(END, hc.reply)
  146.     hc.textframe.bind('<Key>',lambda e: "break")
  147.     hc.textframe.bind('<B1-Motion>',lambda e: "break")   # Disables select text
  148.     hc.textframe.bind('<Button-1>',lambda e: "break")
  149.     hc.textframe.bind('<Button-3>',lambda x: hc.master.destroy())
  150.  
  151.     hc.textframe.grid(row=0, column=0)
  152.     hc.frame.grid(row=0, column=0)
  153.  
  154.     if hc.frame1==None:
  155.         hc.frame1 = Frame(hc.master,bg="black")
  156.         hc.textframe1 = Text(hc.frame1, wrap=WORD, background='white', fg='black',
  157.                              font=('sans', 12), height = 2, width = 40, borderwidth=1)
  158.         hc.textframe1.insert(END, "")
  159.  
  160.         hc.lab3 = Label(hc.frame1, text="Enter some text", bg="black", fg="green")
  161.         hc.lab3.grid(row=1, column=0, pady=5)
  162.  
  163.         hc.textframe1.grid(row=2, column=0, padx=5, pady=5)
  164.         hc.textframe1.bind('<Return>',choseVid)
  165.         hc.textframe1.focus_set()
  166.         hc.frame1.grid(row=1, column=0)
  167.         hc.frame1.focus_set()
  168.  
  169.     hc.master.mainloop()
  170.  
  171. if __name__ == "__main__":
  172.     hc = HoldingClass()
  173.     main()
Advertisement
Add Comment
Please, Sign In to add comment