Advertisement
themoosemind

GUI

Mar 23rd, 2015
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.87 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. """Write on a canvas, store on-line data."""
  4.  
  5. from __future__ import unicode_literals
  6. __version__ = '0.1'
  7.  
  8. from gi.repository import Gtk, Gdk
  9. import time
  10. import math
  11. import json
  12.  
  13. # For the call for classification
  14. import requests
  15. import urllib
  16.  
  17. try:
  18.     from urllib.parse import urlencode
  19. except:
  20.     # Python 2.7 fallback
  21.     chr = unichr
  22.     from urllib import urlencode
  23.  
  24. # For user interaction / pasting stuff where it should be
  25. from pykeyboard import PyKeyboard
  26.  
  27. classification_guess = ""
  28.  
  29.  
  30. class FormulaWriter(Gtk.Window):
  31.  
  32.     def __init__(self):
  33.         super(FormulaWriter, self).__init__()
  34.         self.odata = []  # On-line writing information, grouped by strokes
  35.  
  36.         # General properties
  37.         self.set_title("Formula Writer %s" % __version__)
  38.         self.resize(400, 400)
  39.         self.set_position(Gtk.WindowPosition.CENTER)
  40.         self.connect("delete-event", self.on_quit)
  41.  
  42.         self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
  43.  
  44.         # Set up canvas
  45.         self.canvas = Gtk.DrawingArea()
  46.         self.canvas.connect("draw", self.on_draw)
  47.         self.canvas.connect("button-press-event", self.on_button_press)
  48.         self.canvas.connect("button-release-event", self.on_button_released)
  49.         self.canvas.connect("motion-notify-event", self.on_mouse_move)
  50.         self.canvas.connect("motion-notify-event", self.on_mouse_move)
  51.         self.canvas.set_events(self.canvas.get_events() |
  52.                                Gdk.EventMask.BUTTON_MOTION_MASK |
  53.                                Gdk.EventMask.BUTTON1_MOTION_MASK |
  54.                                Gdk.EventMask.BUTTON2_MOTION_MASK |
  55.                                Gdk.EventMask.BUTTON3_MOTION_MASK |
  56.                                Gdk.EventMask.BUTTON_PRESS_MASK |
  57.                                Gdk.EventMask.BUTTON_RELEASE_MASK)
  58.  
  59.         self.add(self.canvas)
  60.         self.show_all()
  61.  
  62.     def on_button_press(self, w, event):
  63.         """When a button is pressed, the location gets stored and the canvas
  64.        gets updated.
  65.        """
  66.         self.odata.append([{'x': event.x, 'y': event.y, 'time': time.time()}])
  67.         self.canvas.queue_draw()
  68.  
  69.     def on_mouse_move(self, w, event):
  70.         """When mouse is moved, the mouse position gets stored."""
  71.         point = {'x': event.x, 'y': event.y, 'time': time.time()}
  72.         self.odata[-1].append(point)
  73.         self.canvas.queue_draw()
  74.  
  75.     def on_button_released(self, w, event):
  76.         global classification_guess
  77.         classification = request_classification(self.odata)
  78.         for tmp in classification:
  79.             tmp = list(tmp.items())[0]
  80.             classinfo, probability = tmp
  81.             #print("%0.2f: %s" % (probability, classinfo))
  82.             db_id, latex, unicode_dec, font, font_style = classinfo.split(";")
  83.             classification_guess = latex
  84.             classification_guess = chr(int(unicode_dec))
  85.             break
  86.         self.clipboard.set_text(classification_guess, -1)
  87.  
  88.     def on_draw(self, wid, cr):
  89.         """Handler for drawing action. Draw all strokes.
  90.        :param wid: The DrawingArea
  91.        :param cr: Context
  92.        """
  93.  
  94.         cr.set_source_rgb(1, 0, 0)  # All strokes get drawn in red
  95.         cr.set_line_width(2.5)
  96.  
  97.         for stroke in self.odata:
  98.             for i, point in enumerate(stroke):
  99.                 if len(stroke) == 1:
  100.                     radius = 2
  101.                     cr.arc(point['x'], point['y'], radius, 0, 2.0*math.pi)
  102.                     cr.fill()
  103.                     cr.stroke()
  104.                 elif i != 0:
  105.                     cr.move_to(stroke[i-1]['x'], stroke[i-1]['y'])
  106.                     cr.line_to(point['x'], point['y'])
  107.                     cr.stroke()
  108.  
  109.     def on_quit(self, formulawriter, event):
  110.         """Handle after the user closed the application."""
  111.         Gtk.main_quit()
  112.  
  113.  
  114. def write_guess():
  115.     global classification_guess
  116.     k = PyKeyboard()
  117.     k.press_key(k.control_key)
  118.     k.tap_key('v')
  119.     k.release_key(k.control_key)
  120.  
  121.  
  122. def request_classification(odata, identifier=''):
  123.     """Get the classification for online data.
  124.    :param odata: A list of strokes, where each stroke is a list of dicts.
  125.    :param identifier: Identifier for single users (to improve classification /
  126.        prevent attacks)
  127.    :returns: A list of dictionarys which map class to probability
  128.    """
  129.     url = 'http://i13pc106.ira.uka.de/~mthoma/cgi-bin/test.php'
  130.     payload = {'classify': json.dumps(odata)}
  131.     data = urlencode(payload)
  132.     headers = {'Content-Type': ('application/x-www-form-urlencoded; '
  133.                                 'charset=UTF-8'),
  134.                'Content-Length': len(data)}
  135.     r = requests.post(url, data=data, headers=headers)
  136.     return json.loads(r.text)
  137.  
  138.  
  139. def main():
  140.     FormulaWriter()
  141.     Gtk.main()
  142.     write_guess()
  143.  
  144. if __name__ == "__main__":
  145.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement