示例#1
0
    def __init__(self, list_of_str, *__args):
        super(Controller, self).__init__(list_of_str, *__args)
        self.mainView = MainView()
        self.profiles = {}

        view = self.mainView.getSubView('result_view')
        if view is not None:
            profile = ResultProfile("result_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        view = self.mainView.getSubView('PX_view')
        if view is not None:
            profile = PXBoardProfile("PX_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        view = self.mainView.getSubView('PG_view')
        if view is not None:
            profile = PGBoardProfile("PG_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        view = self.mainView.getSubView('audio_view')
        if view is not None:
            profile = AudioProfile("audio_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        self.bindHandlers()
示例#2
0
    def __init__(self, parent, id):
        self.plotController = []
        self.current_plotController = 0
        self.loadFlag = False
        self.mainView = MainView(parent, -1)
        self.timer = wx.Timer(self.mainView)
        self.currentVolume = 5
        self.toolbar = []

        fig1 = plt.figure(1, figsize=(16, 4.3), dpi=80)
        fig2 = plt.figure(2, figsize=(16, 4.3), dpi=80)
        self.valence_canvas = FigureCanvasWxAgg(self.mainView.valencePanel, -1,
                                                fig1)
        self.arousal_canvas = FigureCanvasWxAgg(self.mainView.arousalPanel, -1,
                                                fig2)
        fig1.canvas.mpl_connect('button_press_event', self.onClick)
        fig2.canvas.mpl_connect('button_press_event', self.onClick)
        #will be moved to main view
        #self.mainView.sizer.Add(self.canvas, (1,6), span=(8,5))
        # self.mainView.valencePanel.Fit()
        # self.mainView.arousalPanel.Fit()

        self.connect(parent)
        self.timer.Start(100)
        self.fps = 1
        self.previewImage = []
        self.vid_path = ""
    def __init__(self, parent, id):
        self.plotController = []
        self.current_plotController = 0
        self.loadFlag = False
        self.mainView = MainView(parent, -1)
        self.timer = wx.Timer(self.mainView)
        self.currentVolume = 5
        self.toolbar = []

        fig1 = plt.figure(1, figsize=(16, 4.3), dpi = 80)
        fig2 = plt.figure(2, figsize=(16, 4.3), dpi = 80)
        self.valence_canvas = FigureCanvasWxAgg(self.mainView.valencePanel, -1, fig1)
        self.arousal_canvas = FigureCanvasWxAgg(self.mainView.arousalPanel, -1, fig2)
        fig1.canvas.mpl_connect('button_press_event', self.onClick)
        fig2.canvas.mpl_connect('button_press_event', self.onClick)
        #will be moved to main view
        #self.mainView.sizer.Add(self.canvas, (1,6), span=(8,5))
        # self.mainView.valencePanel.Fit()
        # self.mainView.arousalPanel.Fit()

        
        
        self.connect(parent)
        self.timer.Start(100)
        self.fps = 1
        self.previewImage = []
        self.vid_path = ""
示例#4
0
    def __init__(self):
        """
        Sets everything up.
        """

        # initialize some objects
        self.IPChooserView = IPChooserView.View()
        self.mainView = MainView.View()
        self.model = None

        # set up the IP chooser
        # in case IP/Port is already defined in sys.argv, set as value of input fields
        self.IPChooserView.show()
        if len(sys.argv) == 3:
            self.IPChooserView.IPAdressInput.setText(sys.argv[1])
            self.IPChooserView.portInput.setText(sys.argv[2])

        # bind ip chooser widget's buttons to methods
        QObject.connect(self.IPChooserView.connectButton, SIGNAL("clicked()"),
                        self.connect)
        QObject.connect(self.IPChooserView.closeButton, SIGNAL("clicked()"),
                        self.close)
        # bind main widget's buttons to methods
        QObject.connect(self.mainView.checkButton, SIGNAL("clicked()"),
                        self.check)
        QObject.connect(self.mainView.resetButton, SIGNAL("clicked()"),
                        self.reset)
        QObject.connect(self.mainView.closeButton, SIGNAL("clicked()"),
                        self.close)
    def __init__(self, root):
        # View config
        self.main_view = MainView(root)
        self.main_view.upload_button.config(command=self.upload)
        self.main_view.upload_button_template.config(command=self.upload_template)
        self.main_view.download_button.config(command=self.download)

        # Paths
        self.input_path = ''
        self.input_path_template = ''
        self.output_path = ''

        # Target groups
        self.target_groups_dict = {}

        # Export content
        self.export_content = ExportContent()
        self.input_handler = None
 def setupUi(self, Form):
     self.MainView = MainView.Main_Form()
     self.mainApp = QtWidgets.QApplication(sys.argv)
     self.mainForm = QtWidgets.QWidget()
     self.form = Form
     Form.setObjectName("Form")
     Form.resize(400, 159)
     Form.setWindowIcon(QtGui.QIcon('data\icon.png'))
     self.pushButton = QtWidgets.QPushButton(Form)
     self.pushButton.setGeometry(QtCore.QRect(50, 90, 131, 28))
     font = QtGui.QFont()
     font.setFamily("Roboto Condensed Light")
     font.setPointSize(9)
     self.pushButton.setFont(font)
     self.pushButton.setObjectName("pushButton")
     self.pushButton_2 = QtWidgets.QPushButton(Form)
     self.pushButton_2.setGeometry(QtCore.QRect(260, 90, 93, 28))
     font = QtGui.QFont()
     font.setFamily("Roboto Condensed Light")
     font.setPointSize(9)
     self.pushButton_2.setFont(font)
     self.pushButton_2.setObjectName("pushButton_2")
     self.label = QtWidgets.QLabel(Form)
     self.label.setGeometry(QtCore.QRect(110, 40, 201, 16))
     font = QtGui.QFont()
     font.setFamily("Roboto Condensed Light")
     font.setPointSize(10)
     font.setBold(False)
     font.setItalic(False)
     font.setWeight(50)
     self.label.setFont(font)
     self.label.setObjectName("label")
     self.retranslateUi(Form)
     QtCore.QMetaObject.connectSlotsByName(Form)
     Form.show()
     self.pushButton.clicked.connect(self.loadButton)
     self.pushButton_2.clicked.connect(self.learnButton)
示例#7
0
 def main_view(self, games):
     self.window_resize(_WIDTH, _HEIGHT)
     self.empty_frame(self.frame_container)
     self.existing_main_view = MV.MainView(self.frame_container, self,
                                           games)
     self.get_games()
class MainController:

    def __init__(self, root):
        # View config
        self.main_view = MainView(root)
        self.main_view.upload_button.config(command=self.upload)
        self.main_view.upload_button_template.config(command=self.upload_template)
        self.main_view.download_button.config(command=self.download)

        # Paths
        self.input_path = ''
        self.input_path_template = ''
        self.output_path = ''

        # Target groups
        self.target_groups_dict = {}

        # Export content
        self.export_content = ExportContent()
        self.input_handler = None

    def download(self):
        """
        Downloads word document

        Triggered on download_button click
        :return:
        """
        self.__clear_messages()
        if self.input_path:
            self.output_path = tkFileDialog.asksaveasfilename(defaultextension=".docx")
            if self.output_path:
                self.__download_generated_word_document(self.output_path)
                self.__set_success_message(Messages.SUCCESS_DOWNLOAD)
                try:
                    pass
                except ValueError as e:
                    print e
                    self.__set_error_message(Messages.ERROR_INVALID_JSON)
                except Exception as e:
                    print e
                    self.__set_error_message(Messages.ERROR_INVALID_INPUT_CONTENT)
        else:
            self.__set_error_message(Messages.ERROR_NO_INPUT_PATH_SELECTED)

    def upload(self):
        """
        Uploads JSON input file

        Triggered on upload_button click
        :return:
        """
        self.__clear_messages()
        self.main_view.disable_download_button(True)
        path = tkFileDialog.askopenfilename(parent=self.main_view, initialdir="/", title='Last opp JSON-fil')
        self.main_view.set_input_path('')
        if not path:
            pass
        elif self.__get_file_extension(path).lower() != 'json':
            self.__set_error_message(Messages.ERROR_INVALID_FILE_FORMAT)
        else:   # Valid path
            try:
                self.input_path = path
                self.input_handler = InputHandler(self.input_path)
                self.__set_target_groups_drop_down_option()
                self.main_view.set_input_path(self.input_path)
                self.__check_downloadable()
            except ValueError as e:
                print e
                self.__set_error_message(Messages.ERROR_INVALID_JSON)
            except Exception as e:
                print e
                self.__set_error_message(Messages.ERROR_INVALID_INPUT_CONTENT)

    def upload_template(self):
        """
        Uploads Word template

        Triggered on upload_button_template click
        :return:
        """
        self.__clear_messages()
        self.main_view.disable_download_button(True)
        path = tkFileDialog.askopenfilename(parent=self.main_view, initialdir="/", title='Last opp Word-mal')
        self.main_view.set_input_path_template('')
        if not path:
            pass
        elif self.__get_file_extension(path).lower() != 'docx':
            self.__set_error_message(Messages.ERROR_INVALID_FILE_FORMAT)
        else:  # Valid path
            try:
                self.input_path_template = path
                self.main_view.set_input_path_template(self.input_path_template)
                self.__check_downloadable()
            except ValueError as e:
                print e
                self.__set_error_message(Messages.ERROR_INVALID_JSON)
            except Exception as e:
                print e
                self.__set_error_message(Messages.ERROR_INVALID_INPUT_CONTENT)

    def __set_target_groups_drop_down_option(self):
        """
        Updates target_groups_drop_down values from JSON file.
        The default value is not touched.
        :return:
        """
        options = self.main_view.target_groups_drop_down.children['menu']
        options.delete(1, 'end')  # Clear drop down

        target_groups = self.input_handler.get_target_groups()

        for target_group in target_groups:
            target_group_name = target_group['name']
            self.target_groups_dict[target_group_name] = target_group['id']
            options.add_command(label=target_group_name, command=lambda v=self.main_view.selected_target_group, l=target_group_name: v.set(l))

    def __check_downloadable(self):
        """
        Checks that both a JSON file and a Word template is uploaded.
        :return:
        """
        if self.input_path and self.input_path_template:
            self.main_view.disable_download_button(False)

    def __clear_messages(self):
        self.main_view.set_error_message('')
        self.main_view.set_success_message('')

    def __set_error_message(self, error_message):
        self.main_view.set_success_message('')
        self.main_view.set_error_message(error_message)

    def __set_success_message(self, success_message):
        self.main_view.set_error_message('')
        self.main_view.set_success_message(success_message)

    def __generate_word_document(self):
        """
        Generates word document.
        :param input_path:
        :return:
        """
        topics = self.input_handler.get_topics()
        for topic in topics:
            documents = self.input_handler.get_documents_by_topic_id(topic['id'])
            self.export_content.add_topic(topic, documents, self.input_handler, 0)

    def __generate_word_document_based_on_target_groups(self, target_group_id):
        """
        Generates Word document with the documents in which the specified target group appears.
        :param target_group_id:
        :return:
        """
        topics = self.input_handler.get_topics()
        for topic in topics:
            documents = self.input_handler.get_documents_by_topic_id(topic['id'])
            self.export_content.add_topic(topic, documents, self.input_handler, target_group_id)

    def __download_generated_word_document(self, output_path):  # TODO: look at documentation
        """
        Downloads docx file with the inserted values from json file.
        There is no support for for links in python-docx-template (docxtpl),
        therefore the file is first saved, and then read using python-docx (docx)
        to replace the links with working hyperlinks, before the file is written
        back to disk.
        :param output_path:
        :return:
        """
        # Python-docx-template
        template = DocxTemplate(self.input_path_template)

        self.export_content.reset_list()    # Reset list to make sure the content is not repeated on multiple downloads
        if self.main_view.selected_target_group.get() == GuiContent.DROP_DOWN_VALUE_NO_SELECTED_TARGET_GROUP: # If no target group is selected
            self.__generate_word_document() #   Word document is generated with all documents
        else:
            target_group = self.input_handler.get_target_group_by_id(self.target_groups_dict[self.main_view.selected_target_group.get()])
            self.__generate_word_document_based_on_target_groups(target_group['id'])    # Word document is generated with all documents that contains specified target group
        content = self.export_content.get_content()
        template.render(content)    # Insert values to jinja2 template
        try:
            template.save(self.output_path) # Temporary saved on disk

            # Python-docx - replace links and insert page breaks, before Word document is saved
            word_handler = WordHandler(output_path)
            word_handler.insert_hyper_links()
            word_handler.insert_new_page()
            word_handler.save_word_document(output_path)
        except IOError as e:
            self.__set_error_message(Messages.ERROR_CANT_WRITE_TO_FILE)
        except Exception as e:
            self.__set_error_message(Messages.ERROR_DEFAULT)
            print e

    def __get_file_path(self, full_path):
        """
        Returns folder path.
        input: 'c:/folder/file.json', returns 'c:/folder'
        :param full_path:
        :return:
        """
        end_of_path_index = full_path.rfind('/')  # Last occurrence of '/'
        return full_path[:end_of_path_index]

    def __get_file_name(self, full_path):
        """
        Returns filename.
        input: 'c:/folder/file.json', returns 'file.json'
        :param full_path:
        :return:
        """
        file_name_with_extension = full_path[len(self.__get_file_path(full_path)) + 1:]
        file_extension_index = file_name_with_extension.rfind('.docx')
        return file_name_with_extension[:file_extension_index]

    def __get_file_extension(self, full_path):
        """
        Returns file extension.
        input: 'c:/folder/file.json', returns 'json'
        :param full_path:
        :return:
        """
        file_name_with_extension = full_path[len(self.__get_file_path(full_path)) + 1:]
        file_extension_index = file_name_with_extension.rfind('.')
        return file_name_with_extension[file_extension_index+1:]
示例#9
0
class Controller(QtGui.QApplication):
    def __init__(self, list_of_str, *__args):
        super(Controller, self).__init__(list_of_str, *__args)
        self.mainView = MainView()
        self.profiles = {}

        view = self.mainView.getSubView('result_view')
        if view is not None:
            profile = ResultProfile("result_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        view = self.mainView.getSubView('PX_view')
        if view is not None:
            profile = PXBoardProfile("PX_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        view = self.mainView.getSubView('PG_view')
        if view is not None:
            profile = PGBoardProfile("PG_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        view = self.mainView.getSubView('audio_view')
        if view is not None:
            profile = AudioProfile("audio_view", view)
            self.profiles[profile.whoAmI()] = profile
            self.mainView.currentView.append(profile)

        self.bindHandlers()

    def bindHandlers(self):
        self.connect(self.mainView, QtCore.SIGNAL("exitAppl(PyQt_PyObject)"), self.shutDown)
        self.connect(self.mainView, QtCore.SIGNAL("viewChanged(PyQt_PyObject)"), self.notifyViewChanged)

    def shutDown(self):
        self.mainView.close()
        self.exit(0)

    def notifyViewChanged(self, name):
        if self.profiles.has_key(name):
            self.mainView.activeView(name)

    def run(self):
        self.mainView.disableToolBar()
        self.mainView.show()
        sys.exit(self.exec_())
示例#10
0
import re

import CassandraClass
import MainView

path = []



path=['C:/python/Logs/3502/before-AFO-i-3502-15.txt',\
      'C:/python/Logs/3503/before-AFO-i-3503-16.txt',\
      'C:/python/Logs/3504/before-AFO.txt',\
      'C:/python/Logs/3505/before-AFO.txt',\
      'C:/python/Logs/4171/before-AFO.txt'
      ]

cassandraclusterinstance = CassandraClass.cassandraCluster('folder1')
for idx, pathrow in enumerate(path):
    file = open(pathrow, 'r')
    cassandrainstance = CassandraClass.Cassandra()
    cassandrainstance.populate(file)
    cassandraclusterinstance.add_cassandraNode(cassandrainstance)

clusterlist = {}
clusterlist['folder1'] = cassandraclusterinstance

mainviewinst5ance = MainView.MainView(clusterlist)
示例#11
0
def register_api(app, api):
    ''' Register the Flask API routes used '''

    MainView.register(api)
    app.register_blueprint(api)
示例#12
0
from MainView import *
from CurrencyModule import *

app = MainView()
示例#13
0
from MainView import *

if __name__ == '__main__':
    root = Tkinter.Tk()
    MainView(root).place()
    root.title("Bench by Krzysztof Kapitan & Jan Badura")
    root.resizable(0, 0)
    root.geometry("500x900")

    root.mainloop()
示例#14
0
    def __init__(self):
        # Using num_popup to count how many
        # popup windows do we have
        self.num_popup = 0
        self.aboutme_popup = None
        self.fontsize_popup = None
        self.not_found_popup = None
        self.overwrite_popup = None

        # The root window
        self.root = Tk()
        self.root.title("Cold Caller")
        self.root.geometry("500x500")

        # Adaptive view setting
        rows = 0
        while rows <= 50:
            self.root.rowconfigure(rows, weight=1)
            self.root.columnconfigure(rows, weight=1)
            rows += 1

        # Add MainView Frame into the root window
        self.mainView = MainView(self.root)
        # Let it occupy all the window
        self.mainView.grid(row=0,
                           column=0,
                           columnspan=50,
                           rowspan=50,
                           sticky=(N, W, S, E))
        # Get 2 tab views from the MainView Frame
        self.cold_caller_tab_view = self.mainView.get_cold_caller_tab_view()
        self.log_tab_view = self.mainView.get_log_tab_view()

        # Bind button/keystrokes to Cold Caller Service APIs
        self.cold_caller_tab_view.createWidgets_bottom_Frame()
        self.cold_caller_tab_view.good_btns[1].bind(
            "<Button-1>", lambda e: self.remove(e, 0))
        self.cold_caller_tab_view.concern_btns[1].bind(
            "<Button-1>", lambda e: self.remove(e, 0, True))

        self.cold_caller_tab_view.good_btns[2].bind(
            "<Button-1>", lambda e: self.remove(e, 1))
        self.cold_caller_tab_view.concern_btns[2].bind(
            "<Button-1>", lambda e: self.remove(e, 1, True))

        self.cold_caller_tab_view.good_btns[3].bind(
            "<Button-1>", lambda e: self.remove(e, 2))
        self.cold_caller_tab_view.concern_btns[3].bind(
            "<Button-1>", lambda e: self.remove(e, 2, True))
        # Keystrokes mapping
        global CONCERN_1A, CONCERN_1B, CONCERN_2, CONCERN_3
        global REMOVE_1A, REMOVE_1B, REMOVE_2, REMOVE_3
        self.root.bind(CONCERN_1A, lambda e: self.remove(e, 0, True))
        self.root.bind(CONCERN_1B, lambda e: self.remove(e, 0, True))
        self.root.bind(CONCERN_2, lambda e: self.remove(e, 1, True))
        self.root.bind(CONCERN_3, lambda e: self.remove(e, 2, True))
        self.root.bind(CONCERN_4, lambda e: self.remove(e, 2, True))

        self.root.bind(REMOVE_1A, lambda e: self.remove(e, 0))
        self.root.bind(REMOVE_1B, lambda e: self.remove(e, 0))
        self.root.bind(REMOVE_2, lambda e: self.remove(e, 1))
        self.root.bind(REMOVE_3, lambda e: self.remove(e, 2))

        # Binding buttons in the log-tab-view
        self.log_tab_view.refresh_log.config(
            command=lambda: self.log_tab_view.set_text(getDailyLog()))
        self.log_tab_view.export_summary.config(
            command=self.export_summary_file_target_path_with_name)

        # Create the top-bar menu
        self.createMenu()

        # When closing the app, save the queue
        def onclosing():
            IO.instance().set_curr_queue()
            self.root.destroy()

        self.root.protocol('WM_DELETE_WINDOW', onclosing)

        # Call Cold Caller Service to get the first 3 students
        self.update_students_info()
示例#15
0
class MainViewController():
    def __init__(self):
        # Using num_popup to count how many
        # popup windows do we have
        self.num_popup = 0
        self.aboutme_popup = None
        self.fontsize_popup = None
        self.not_found_popup = None
        self.overwrite_popup = None

        # The root window
        self.root = Tk()
        self.root.title("Cold Caller")
        self.root.geometry("500x500")

        # Adaptive view setting
        rows = 0
        while rows <= 50:
            self.root.rowconfigure(rows, weight=1)
            self.root.columnconfigure(rows, weight=1)
            rows += 1

        # Add MainView Frame into the root window
        self.mainView = MainView(self.root)
        # Let it occupy all the window
        self.mainView.grid(row=0,
                           column=0,
                           columnspan=50,
                           rowspan=50,
                           sticky=(N, W, S, E))
        # Get 2 tab views from the MainView Frame
        self.cold_caller_tab_view = self.mainView.get_cold_caller_tab_view()
        self.log_tab_view = self.mainView.get_log_tab_view()

        # Bind button/keystrokes to Cold Caller Service APIs
        self.cold_caller_tab_view.createWidgets_bottom_Frame()
        self.cold_caller_tab_view.good_btns[1].bind(
            "<Button-1>", lambda e: self.remove(e, 0))
        self.cold_caller_tab_view.concern_btns[1].bind(
            "<Button-1>", lambda e: self.remove(e, 0, True))

        self.cold_caller_tab_view.good_btns[2].bind(
            "<Button-1>", lambda e: self.remove(e, 1))
        self.cold_caller_tab_view.concern_btns[2].bind(
            "<Button-1>", lambda e: self.remove(e, 1, True))

        self.cold_caller_tab_view.good_btns[3].bind(
            "<Button-1>", lambda e: self.remove(e, 2))
        self.cold_caller_tab_view.concern_btns[3].bind(
            "<Button-1>", lambda e: self.remove(e, 2, True))
        # Keystrokes mapping
        global CONCERN_1A, CONCERN_1B, CONCERN_2, CONCERN_3
        global REMOVE_1A, REMOVE_1B, REMOVE_2, REMOVE_3
        self.root.bind(CONCERN_1A, lambda e: self.remove(e, 0, True))
        self.root.bind(CONCERN_1B, lambda e: self.remove(e, 0, True))
        self.root.bind(CONCERN_2, lambda e: self.remove(e, 1, True))
        self.root.bind(CONCERN_3, lambda e: self.remove(e, 2, True))
        self.root.bind(CONCERN_4, lambda e: self.remove(e, 2, True))

        self.root.bind(REMOVE_1A, lambda e: self.remove(e, 0))
        self.root.bind(REMOVE_1B, lambda e: self.remove(e, 0))
        self.root.bind(REMOVE_2, lambda e: self.remove(e, 1))
        self.root.bind(REMOVE_3, lambda e: self.remove(e, 2))

        # Binding buttons in the log-tab-view
        self.log_tab_view.refresh_log.config(
            command=lambda: self.log_tab_view.set_text(getDailyLog()))
        self.log_tab_view.export_summary.config(
            command=self.export_summary_file_target_path_with_name)

        # Create the top-bar menu
        self.createMenu()

        # When closing the app, save the queue
        def onclosing():
            IO.instance().set_curr_queue()
            self.root.destroy()

        self.root.protocol('WM_DELETE_WINDOW', onclosing)

        # Call Cold Caller Service to get the first 3 students
        self.update_students_info()

    # Update students' portrait photos, names, spelling
    def update_students_info(self):
        f = ColdCallerService.instance()
        for i in range(3):
            new_student = f.get_studnt_at(i)
            if not new_student == None:
                name = ""
                spelling = ""
                photo = None
                # If this student doesn't have privacy protection
                # Show his/her name, photo, spelling
                if new_student.getReveal():
                    global HOME_PHOTOS_PATH
                    name = new_student.getName()
                    spelling = new_student.getPSpell()
                    photo = path.join(HOME_PHOTOS_PATH,
                                      new_student.getID() + '.png')
                # Otherwise, only show his/her initials
                else:
                    name = new_student.getNameInitial()

                self.cold_caller_tab_view.set_Widgets_top_portrait(
                    i, name=name, spelling=spelling, portrait_path=photo)

    # Call cold caller service to remove a student at a certain position
    # and then update the view
    def remove(self, event, pos: int, concern=False):
        if (self.mainView.nb.index("current") == 0 and self.num_popup == 0):
            f = ColdCallerService.instance()
            if (not concern):
                if (f.remove_stuent_at(pos)):
                    self.update_students_info()
            else:
                f.concern_recent_student()

    # The following methods are for the use of top-bar menu
    #
    # Destory a popup window after doing a certain job
    def destory_popup_window_after(self, popup, doing_this_before=None):
        if not doing_this_before == None:
            try:
                doing_this_before()
            except Exception as e:
                print(e)
        popup.destroy()
        self.num_popup -= 1

    # When importing a roster, if that file is not found
    # fire this window
    def not_found_window(self):
        # If there is an active popup window
        # Foucus on it
        try:
            self.not_found_popup.focus_set()
            return
        except Exception:
            pass
        # Otherwise create a new one
        self.num_popup += 1
        self.not_found_popup = Toplevel(self.root)
        self.not_found_popup.title("File Not Found")
        self.not_found_popup.resizable(0, 0)

        explanation = "Unable to open the file you selected"

        onclosing = lambda: self.destory_popup_window_after(self.
                                                            not_found_popup)
        self.not_found_popup.protocol('WM_DELETE_WINDOW', onclosing)
        Label(self.not_found_popup, text=explanation).grid()
        Button(self.not_found_popup, text='OK', command=onclosing).grid()

        self.not_found_popup.transient(self.root)
        self.mainView.wait_window(self.not_found_popup)

    # Call IOService and pass the importing file path to it
    def _import_roster(self, path_with_name):
        IO.instance().importRoster(path_with_name, True)
        self.update_students_info()

    # Display the difference between current roster and the importing roster
    # and ask whether to overwrite the current roster
    def overwrite_window(self, diff, path_with_name):
        try:
            self.overwrite_popup.focus_set()
            return
        except Exception:
            pass
        self.num_popup += 1
        self.overwrite_popup = Toplevel(self.root)
        self.overwrite_popup.title("Overwrite the current roster")
        self.overwrite_popup.resizable(0, 0)

        explanation = "Do you want to overwrite the current roster? The difference between the current roster and the importing roster is:\n"
        explanation += diff

        onclosing = lambda: self.destory_popup_window_after(self.
                                                            overwrite_popup)
        self.overwrite_popup.protocol('WM_DELETE_WINDOW', onclosing)
        Label(self.overwrite_popup, text=explanation).grid()

        Button(self.overwrite_popup,
               text='Yes',
               command=lambda: self.destory_popup_window_after(
                   self.overwrite_popup, lambda: self._import_roster(
                       path_with_name))).grid()
        Button(self.overwrite_popup, text='No', command=onclosing).grid()

        self.overwrite_popup.transient(self.root)
        self.mainView.wait_window(self.overwrite_popup)

    # Use a file dialog to let the user choose a roster to import
    def import_roster_file_path_with_name(self):
        if (self.mainView.nb.index("current") == 0 and self.num_popup == 0):
            path_with_file_name = filedialog.askopenfilename(
                title='Choose your csv/tsv file',
                filetypes=(('CSV', '*.csv'), ('TSV', '*.tsv')))
            rslt = IO.instance().importRoster(path_with_file_name)
            if (rslt[0] == 1):
                self.not_found_window()
            elif (rslt[0] == 2):
                self.overwrite_window(rslt[1], path_with_file_name)
            else:
                self.update_students_info()

    # Use a file dialog to let the user choose a directory to export the roster
    def export_roster_file_target_path_with_name(self):
        if (self.mainView.nb.index("current") == 0 and self.num_popup == 0):
            target = filedialog.asksaveasfilename(initialdir="/",
                                                  title="Select file",
                                                  filetypes=(('CSV', '*.csv'),
                                                             ('TSV', '*.tsv')))
            IO.instance().exportRoster(target)

    # Use a file dialog to let the user choose a directory to export the summary log
    def export_summary_file_target_path_with_name(self):
        if (self.mainView.nb.index("current") == 1 and self.num_popup == 0):
            target = filedialog.asksaveasfilename(initialdir="/",
                                                  title="Select file",
                                                  filetypes=(('TXT',
                                                              '*.txt'), ))
            if not target == None and not target == "":
                summary(target)

    # User a file dialog to let the user choose a directory to read students' portraits
    def set_photos_folder_path(self):
        if (self.num_popup == 0):
            tmp = filedialog.askdirectory(title='Choose your Photos directory')
            if not tmp == None and not tmp == "":
                global HOME_PHOTOS_PATH
                HOME_PHOTOS_PATH = tmp
                self.update_students_info()

    # Let the user select the font size of name label
    def font_size_window(self):
        try:
            self.font_size_window.focus_set()
            return
        except Exception:
            pass
        self.num_popup += 1
        self.fontsize_popup = Toplevel(self.root)
        self.fontsize_popup.title("Set names' font size")
        self.fontsize_popup.resizable(0, 0)

        onclosing = lambda: self.destory_popup_window_after(self.fontsize_popup
                                                            )
        self.fontsize_popup.protocol('WM_DELETE_WINDOW', onclosing)
        Label(self.fontsize_popup, text="Select font size").grid(row=0,
                                                                 column=0)

        listbox = Listbox(self.fontsize_popup)
        for i in range(12, 25):
            listbox.insert(END, i)
        listbox.select_set(
            int(self.cold_caller_tab_view.label_font['size']) - 12)
        listbox.grid(row=0, column=1)

        onOk = lambda: self.destory_popup_window_after(
            self.fontsize_popup, lambda: self.cold_caller_tab_view.label_font.
            config(size=listbox.get(ANCHOR)))
        Button(self.fontsize_popup, text='OK', command=onOk).grid(row=1,
                                                                  column=0)
        Button(self.fontsize_popup, text='Cancel',
               command=onclosing).grid(row=1, column=1)
        self.fontsize_popup.transient(self.root)
        self.mainView.wait_window(self.fontsize_popup)

    # About me
    def aboutme_window(self):
        try:
            self.aboutme_popup.focus_set()
            return
        except Exception:
            pass
        self.num_popup += 1
        self.aboutme_popup = Toplevel(self.root)
        self.aboutme_popup.title("About")
        self.aboutme_popup.resizable(0, 0)

        explanation = "This program is built to help in increasing students' participation in classes."

        onclosing = lambda: self.destory_popup_window_after(self.aboutme_popup)
        self.aboutme_popup.protocol('WM_DELETE_WINDOW', onclosing)
        Label(self.aboutme_popup, text=explanation).grid()
        Button(self.aboutme_popup, text='OK', command=onclosing).grid()

        self.aboutme_popup.transient(self.root)
        self.mainView.wait_window(self.aboutme_popup)

    def createMenu(self):
        self.menu = Menu(self.root)
        self.root.config(menu=self.menu)
        self.submenu = Menu(self.menu)
        self.menu.add_cascade(label="Import/Export", menu=self.submenu)
        self.submenu.add_command(
            label="Import a Roster",
            command=self.import_roster_file_path_with_name)
        self.submenu.add_command(
            label="Export to a Roster",
            command=self.export_roster_file_target_path_with_name)
        self.submenu.add_separator()
        self.submenu.add_command(label="Exit", command=self.root.quit)

        self.submenu2 = Menu(self.menu)
        self.menu.add_cascade(label="Misc", menu=self.submenu2)
        self.submenu2.add_command(label="Set Photos Folder",
                                  command=self.set_photos_folder_path)
        self.submenu2.add_command(label="Font Size",
                                  command=self.font_size_window)
        self.submenu2.add_command(label="About", command=self.aboutme_window)

    # Render the UI
    def show(self):
        self.root.mainloop()
示例#16
0
class ToolController():
    def __init__(self, parent, id):
        self.plotController = []
        self.current_plotController = 0
        self.loadFlag = False
        self.mainView = MainView(parent, -1)
        self.timer = wx.Timer(self.mainView)
        self.currentVolume = 5
        self.toolbar = []

        fig1 = plt.figure(1, figsize=(16, 4.3), dpi=80)
        fig2 = plt.figure(2, figsize=(16, 4.3), dpi=80)
        self.valence_canvas = FigureCanvasWxAgg(self.mainView.valencePanel, -1,
                                                fig1)
        self.arousal_canvas = FigureCanvasWxAgg(self.mainView.arousalPanel, -1,
                                                fig2)
        fig1.canvas.mpl_connect('button_press_event', self.onClick)
        fig2.canvas.mpl_connect('button_press_event', self.onClick)
        #will be moved to main view
        #self.mainView.sizer.Add(self.canvas, (1,6), span=(8,5))
        # self.mainView.valencePanel.Fit()
        # self.mainView.arousalPanel.Fit()

        self.connect(parent)
        self.timer.Start(100)
        self.fps = 1
        self.previewImage = []
        self.vid_path = ""

    def connect(self, parent):

        #binding the menu bar item
        parent.Bind(wx.EVT_MENU, self.onLoadFile, self.mainView.loadButton)
        parent.Bind(wx.EVT_MENU, self.exportToCSV, self.mainView.exportButton)
        parent.Bind(wx.EVT_MENU, self.importFromCSV,
                    self.mainView.importButton)
        parent.Bind(wx.EVT_MENU, self.importConfigData,
                    self.mainView.importConfigButton)
        parent.Bind(wx.EVT_MENU, self.exportConfigData,
                    self.mainView.exportConfigButton)

        self.mainView.Bind(wx.EVT_BUTTON, self.onPlay,
                           self.mainView.playButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.onPause,
                           self.mainView.pauseButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.onStop,
                           self.mainView.stopButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.showPreview,
                           self.mainView.previewButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.show_current_position,
                           self.mainView.showCurPosButton)

        self.mainView.Bind(wx.EVT_BUTTON, self.add_state,
                           self.mainView.addStateButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.add_quantile_section,
                           self.mainView.addQuantileButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.remove_quantile_section,
                           self.mainView.removeQuantileButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.interpolate,
                           self.mainView.interpolateButton)

        self.mainView.Bind(wx.EVT_SLIDER, self.onSeek, self.mainView.slider)
        self.mainView.Bind(wx.EVT_SLIDER, self.setVolume,
                           self.mainView.volumeSlider)
        self.mainView.Bind(wx.EVT_TIMER, self.onTimer)

        self.mainView.Bind(wx.EVT_CLOSE, self.on_close)
        self.mainView.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.plotChanged)

        self.mainView.Bind(wx.EVT_CHECKBOX, self.setAudioOff)

    def setAudioOff(self, evt):
        if self.mainView.audioOff.GetValue():
            self.mainView.volumeSlider.SetValue(0)
            self.mainView.mc.SetVolume(0)
        else:
            print self.currentVolume
            self.mainView.volumeSlider.SetValue(self.currentVolume)
            self.mainView.mc.SetVolume(self.currentVolume)

    def setVolume(self, evt):
        volume = self.mainView.volumeSlider.GetValue()
        self.mainView.mc.SetVolume(volume)
        self.currentVolume = volume
        if volume == 0:
            self.mainView.audioOff.SetValue(True)
        else:
            self.mainView.audioOff.SetValue(False)

    def onPlay(self, evt):
        self.mainView.mc.Play()

    def onPause(self, evt):
        self.mainView.mc.Pause()

    def onStop(self, evt):
        self.mainView.mc.Stop()

    def onSeek(self, evt):
        offset = self.mainView.slider.GetValue()
        self.mainView.mc.Seek(offset)

    def onTimer(self, evt):
        offset = self.mainView.mc.Tell()
        pos = self.mainView.mc.Tell() * self.fps / 1000
        self.current_frame = pos
        self.plotController[0].current_frame = pos
        self.plotController[1].current_frame = pos
        self.mainView.slider.SetValue(offset)
        self.mainView.st_size.SetLabel('size: %s ms' %
                                       self.mainView.mc.Length())
        self.mainView.st_len.SetLabel('( %d seconds )' %
                                      (self.mainView.mc.Length() / 1000))
        self.mainView.st_pos.SetLabel('position: %d frame' %
                                      (int(offset * self.fps / 1000)))

    def onLoadFile(self, evt):
        dlg = wx.FileDialog(self.mainView,
                            message="Choose a media file",
                            defaultDir=os.getcwd(),
                            defaultFile="",
                            style=wx.OPEN | wx.CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self.doLoadFile(path)
            dlg.Destroy()

    def doLoadFile(self, path):
        if not self.mainView.mc.Load(path):
            wx.MessageBox("Unable to load %s: Unsupported format?" % path,
                          "ERROR", wx.ICON_ERROR | wx.OK)
            self.mainView.mc.Load(self.vid_path)
        else:
            self.vid_path = path
            folder, filename = os.path.split(path)
            self.mainView.vid_name.SetLabel(filename)
            self.cv_capture = cv2.VideoCapture(path)
            self.fps = self.cv_capture.get(cv.CV_CAP_PROP_FPS)
            self.mainView.slider.SetRange(0, self.mainView.mc.Length())

            self.mainView.volumeSlider.SetRange(0, 100)
            self.mainView.mc.SetVolume(self.currentVolume)
            self.mainView.volumeSlider.SetValue(self.currentVolume)
            if self.currentVolume > 0:
                self.mainView.audioOff.SetValue(False)
            else:
                self.mainView.audioOff.SetValue(True)
            self.doLoadPlot()

    def doLoadPlot(self):
        fig1 = plt.figure(1)
        fig2 = plt.figure(2)
        if self.loadFlag:
            del self.plotController
            self.plotController = []
            fig1.clf()
            fig2.clf()

        valence_plotController = PlotController(
            1, self.cv_capture.get(cv.CV_CAP_PROP_FRAME_COUNT), '')
        arousal_plotController = PlotController(
            2, self.cv_capture.get(cv.CV_CAP_PROP_FRAME_COUNT), '')

        #fig1 = plt.figure(0)
        self.current_plotController = self.mainView.plot_notebook.GetSelection(
        )
        self.loadFlag = True
        self.plotController.append(valence_plotController)
        self.plotController.append(arousal_plotController)

        self.current_frame = 0
        #self.toolbar =Toolbar(self.canvas)
        #self.mainView.SetSizer(self.mainView.sizer)
        #self.plotController[0].plotView.update()
        self.mainView.Layout()

    def posIndicate1(self, i):
        print "running 1"
        #print self.current_frame
        pos = self.current_frame
        x = np.linspace(pos, pos)
        y = np.linspace(-100, 100)
        line1.set_data(x, y)
        return line1,

    def RepresentsInt(self, s):
        try:
            int(s)
            return True
        except ValueError:
            return False

    def show_current_position(self, evt):
        if self.loadFlag:
            offset = self.mainView.mc.Tell()
            current_frame = offset * self.fps / 1000
            self.plotController[self.current_plotController].showFramePos(
                self.current_frame)

    def add_quantile_section(self, evt):
        if self.loadFlag:
            raw_lower = self.mainView.textField1.GetValue().strip()
            raw_upper = self.mainView.textField2.GetValue().strip()
            raw_level = self.mainView.textField3.GetValue().strip()
            raw_color = self.mainView.textField4.GetValue().strip()

            if self.RepresentsInt(raw_lower) and self.RepresentsInt(raw_upper):
                raw_lower = int(raw_lower)
                raw_upper = int(raw_upper)
                if raw_lower < raw_upper and raw_lower >= -100 and raw_upper <= 100 and raw_color in [
                        'blue', 'yellow', 'green', 'purple', 'red'
                ]:
                    self.plotController[
                        self.current_plotController].add_quantile_section(
                            int(raw_lower), int(raw_upper), raw_level,
                            raw_color)
            self.mainView.textField1.SetValue("")
            self.mainView.textField2.SetValue("")
            self.mainView.textField3.SetValue("")
            self.mainView.textField4.SetValue("")

    def remove_quantile_section(self, evt):
        p = self.mainView.textField1.GetValue().strip()
        if self.RepresentsInt(p):
            p = int(p)
            self.plotController[
                self.current_plotController].remove_quantile_section(p)
        self.mainView.textField1.SetValue("")

    def add_state(self, evt):
        _state = self.mainView.textField5.GetValue().strip()
        #there is a plot in UI, and successfully add state
        if self.loadFlag:
            if self.plotController[self.current_plotController].add_state(
                    _state):
                self.mainView.add_check_box(_state)
                self.mainView.textField5.SetValue("")

    def show_landmark(self, landmark_pos, state_list):
        self.cv_capture.set(cv.CV_CAP_PROP_POS_FRAMES, landmark_pos)
        pos = self.cv_capture.get(cv.CV_CAP_PROP_POS_MSEC)
        self.mainView.mc.Seek(pos)
        for cb in self.mainView.stateCheckBox:
            index = self.mainView.stateCheckBox.index(cb)
            if cb.GetLabel() in state_list:
                self.mainView.stateCheckBox[index].SetValue(True)
            else:
                self.mainView.stateCheckBox[index].SetValue(False)

    def onClick(self, evt):
        #self.current_plotController = self.mainView.plot_notebook.GetSelection()
        if self.loadFlag and evt.xdata and evt.ydata:
            pos = self.mainView.mc.Tell()
            print "click event on %f" % (pos)
            self.cv_capture.set(cv.CV_CAP_PROP_POS_MSEC, pos)
            self.current_frame = self.cv_capture.get(cv.CV_CAP_PROP_POS_FRAMES)
            state_list = []
            audioflag = self.mainView.audioOff.GetValue()
            offset = self.cv_capture.get(cv.CV_CAP_PROP_FRAME_COUNT) * 0.002
            temp_landmark = []

            for landmark in self.plotController[
                    self.current_plotController].landmark_list:
                if landmark[0] > evt.xdata - offset and landmark[
                        0] < evt.xdata + offset and landmark[
                            1] > evt.ydata - offset and landmark[
                                1] < evt.ydata + offset:
                    temp_landmark = landmark
                    print "landmark clicked!!"
                    print landmark
                    break
            #if left click
            if evt.button == 1:
                for cb in self.mainView.stateCheckBox:
                    if cb.GetValue():
                        state_list.append(cb.GetLabel())
                #no landmark is clicked
                if not temp_landmark:
                    print "adding a land mark on %f, %f " % (
                        self.current_frame, evt.ydata)
                    self.plotController[
                        self.current_plotController].add_landmark(
                            self.current_frame, evt.ydata, audioflag,
                            state_list)
                else:
                    self.show_landmark(temp_landmark[0], temp_landmark[4])
            #if right click
            else:
                if temp_landmark:
                    self.plotController[
                        self.current_plotController].remove_landmark(landmark)

    def showPreview(self, evt):
        k = 5
        if self.loadFlag:
            if self.previewImage:
                for p in self.previewImage:
                    self.previewImage.remove(p)

            offset = self.mainView.mc.Tell()
            k_frame = offset * self.fps / 1000
            if k_frame >= 2 * k:
                k_frame = k_frame - 2 * k
            for i in range(0, 5):
                self.cv_capture.set(cv.CV_CAP_PROP_POS_FRAMES, k_frame)
                ret, frame = self.cv_capture.read()
                frame = cv2.resize(frame, (144, 108))
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                height, width = frame.shape[:2]
                bmp = wx.BitmapFromBuffer(width, height, frame)
                control = wx.StaticBitmap(self.mainView.infoPanel, -1, bmp)
                control.SetPosition((5 + (144 + 10) * i, 100))
                self.previewImage.append(control)
                k_frame = k_frame + k
            self.cv_capture.set(cv.CV_CAP_PROP_POS_MSEC, offset)

    def interpolate(self, evt):
        self.plotController[self.current_plotController].fit_curve()

    def exportToCSV(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView, "Save CSV file", "", "",
                                "CSV files (*.csv)|*.csv",
                                wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_CANCEL:
                return
            path = dlg.GetPath()
            self.plotController[self.current_plotController].exportData(
                path, 0)
            dlg.Destroy()

    def exportConfigData(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView, "Save config file", "", "",
                                "CSV files (*.csv)|*.csv",
                                wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_CANCEL:
                return
            path = dlg.GetPath()
            self.plotController[self.current_plotController].exportConfigData(
                path)
            dlg.Destroy()

    def importFromCSV(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView,
                                message="Choose a csv file",
                                defaultDir=os.getcwd(),
                                defaultFile="",
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                path = dlg.GetPath()
                print self.current_plotController
                self.plotController[self.current_plotController].importData(
                    path)
                dlg.Destroy()

    def importConfigData(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView,
                                message="Choose a configuration csv file",
                                defaultDir=os.getcwd(),
                                defaultFile="",
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                path = dlg.GetPath()
                self.plotController[
                    self.current_plotController].importConfigData(path)
                dlg.Destroy()
                #animpos1 = animation.FuncAnimation(fig1, self.posIndicate1, interval = 1000, blit=False, repeat = True)

    #
    #framepos2 = animation.FuncAnimation(fig2, posIndicate2, fargs = (self.mainView.mc.Tell() * self.fps / 1000),
    #                                                                    interval=10, blit=False)
    #self.toolbar =Toolbar(self.canvas)
    #self.mainView.SetSizer(self.mainView.sizer)

    def plotChanged(self, event):
        self.current_plotController = self.mainView.plot_notebook.GetSelection(
        )
        event.Skip()

    def on_close(self, evt):
        evt.skip()
        print "True"
        exit()
class ToolController():
    def __init__(self, parent, id):
        self.plotController = []
        self.current_plotController = 0
        self.loadFlag = False
        self.mainView = MainView(parent, -1)
        self.timer = wx.Timer(self.mainView)
        self.currentVolume = 5
        self.toolbar = []

        fig1 = plt.figure(1, figsize=(16, 4.3), dpi = 80)
        fig2 = plt.figure(2, figsize=(16, 4.3), dpi = 80)
        self.valence_canvas = FigureCanvasWxAgg(self.mainView.valencePanel, -1, fig1)
        self.arousal_canvas = FigureCanvasWxAgg(self.mainView.arousalPanel, -1, fig2)
        fig1.canvas.mpl_connect('button_press_event', self.onClick)
        fig2.canvas.mpl_connect('button_press_event', self.onClick)
        #will be moved to main view
        #self.mainView.sizer.Add(self.canvas, (1,6), span=(8,5))
        # self.mainView.valencePanel.Fit()
        # self.mainView.arousalPanel.Fit()

        
        
        self.connect(parent)
        self.timer.Start(100)
        self.fps = 1
        self.previewImage = []
        self.vid_path = ""
    
    def connect(self, parent):
        
        #binding the menu bar item
        parent.Bind(wx.EVT_MENU, self.onLoadFile, self.mainView.loadButton)
        parent.Bind(wx.EVT_MENU, self.exportToCSV, self.mainView.exportButton)
        parent.Bind(wx.EVT_MENU, self.importFromCSV, self.mainView.importButton)
        parent.Bind(wx.EVT_MENU, self.importConfigData, self.mainView.importConfigButton)
        parent.Bind(wx.EVT_MENU, self.exportConfigData, self.mainView.exportConfigButton)
        
        
        
        self.mainView.Bind(wx.EVT_BUTTON, self.onPlay, self.mainView.playButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.onPause, self.mainView.pauseButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.onStop, self.mainView.stopButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.showPreview, self.mainView.previewButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.show_current_position, self.mainView.showCurPosButton)
  
        self.mainView.Bind(wx.EVT_BUTTON, self.add_state, self.mainView.addStateButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.add_quantile_section, self.mainView.addQuantileButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.remove_quantile_section, self.mainView.removeQuantileButton)
        self.mainView.Bind(wx.EVT_BUTTON, self.interpolate, self.mainView.interpolateButton)
        
        self.mainView.Bind(wx.EVT_SLIDER, self.onSeek, self.mainView.slider)
        self.mainView.Bind(wx.EVT_SLIDER, self.setVolume, self.mainView.volumeSlider)
        self.mainView.Bind(wx.EVT_TIMER, self.onTimer)

        self.mainView.Bind(wx.EVT_CLOSE, self.on_close)
        self.mainView.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.plotChanged)
    
        self.mainView.Bind(wx.EVT_CHECKBOX, self.setAudioOff)
    
    
    def setAudioOff(self, evt):
        if self.mainView.audioOff.GetValue():
            self.mainView.volumeSlider.SetValue(0)
            self.mainView.mc.SetVolume(0)
        else:
            print self.currentVolume
            self.mainView.volumeSlider.SetValue(self.currentVolume)
            self.mainView.mc.SetVolume(self.currentVolume)
    def setVolume(self, evt):
        volume = self.mainView.volumeSlider.GetValue()
        self.mainView.mc.SetVolume(volume)
        self.currentVolume = volume
        if volume == 0:
            self.mainView.audioOff.SetValue(True)
        else:
            self.mainView.audioOff.SetValue(False)

    def onPlay(self, evt):
        self.mainView.mc.Play()
            
    def onPause(self, evt):
        self.mainView.mc.Pause()
    
    def onStop(self, evt):
        self.mainView.mc.Stop()
    def onSeek(self, evt):
        offset = self.mainView.slider.GetValue()
        self.mainView.mc.Seek(offset)
    
    def onTimer(self, evt):
        offset = self.mainView.mc.Tell()
        pos = self.mainView.mc.Tell() * self.fps / 1000
        self.current_frame = pos
        self.plotController[0].current_frame = pos
        self.plotController[1].current_frame = pos
        self.mainView.slider.SetValue(offset)
        self.mainView.st_size.SetLabel('size: %s ms' % self.mainView.mc.Length())
        self.mainView.st_len.SetLabel('( %d seconds )' % (self.mainView.mc.Length()/1000))
        self.mainView.st_pos.SetLabel('position: %d frame' % (int(offset*self.fps/1000)))


    def onLoadFile(self, evt):
        dlg = wx.FileDialog(self.mainView, message="Choose a media file",
                        defaultDir=os.getcwd(), defaultFile="",
                        style=wx.OPEN | wx.CHANGE_DIR )
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            self.doLoadFile(path)
            dlg.Destroy()




    def doLoadFile(self, path):
        if not self.mainView.mc.Load(path):
            wx.MessageBox("Unable to load %s: Unsupported format?" % path, "ERROR", wx.ICON_ERROR | wx.OK)
            self.mainView.mc.Load(self.vid_path)
        else:
            self.vid_path = path
            folder, filename = os.path.split(path)
            self.mainView.vid_name.SetLabel(filename)
            self.cv_capture = cv2.VideoCapture(path)
            self.fps = self.cv_capture.get(cv.CV_CAP_PROP_FPS)
            self.mainView.slider.SetRange(0, self.mainView.mc.Length())
    
            self.mainView.volumeSlider.SetRange(0, 100)
            self.mainView.mc.SetVolume(self.currentVolume)
            self.mainView.volumeSlider.SetValue(self.currentVolume)
            if self.currentVolume > 0:
                self.mainView.audioOff.SetValue(False)
            else:
                self.mainView.audioOff.SetValue(True)
            self.doLoadPlot()


    def doLoadPlot(self):
        fig1 = plt.figure(1)
        fig2 = plt.figure(2)
        if self.loadFlag:
            del self.plotController
            self.plotController = []
            fig1.clf()
            fig2.clf()
        
        valence_plotController = PlotController(1, self.cv_capture.get(cv.CV_CAP_PROP_FRAME_COUNT),'')
        arousal_plotController = PlotController(2, self.cv_capture.get(cv.CV_CAP_PROP_FRAME_COUNT),'')
        
        
        #fig1 = plt.figure(0)
        self.current_plotController = self.mainView.plot_notebook.GetSelection()
        self.loadFlag = True
        self.plotController.append(valence_plotController)
        self.plotController.append(arousal_plotController)


        self.current_frame = 0
        #self.toolbar =Toolbar(self.canvas)
        #self.mainView.SetSizer(self.mainView.sizer)
        #self.plotController[0].plotView.update()
        self.mainView.Layout()
        
    def posIndicate1(self, i):
        print "running 1"
        #print self.current_frame
        pos = self.current_frame
        x = np.linspace(pos, pos)
        y = np.linspace(-100,100)
        line1.set_data(x,y)
        return line1,

    def RepresentsInt(self,s):
        try:
            int(s)
            return True
        except ValueError:
            return False



    def show_current_position(self, evt):
        if self.loadFlag:
            offset = self.mainView.mc.Tell()
            current_frame = offset*self.fps/1000
            self.plotController[self.current_plotController].showFramePos(self.current_frame)

    def add_quantile_section(self, evt):
        if self.loadFlag:
            raw_lower = self.mainView.textField1.GetValue().strip()
            raw_upper = self.mainView.textField2.GetValue().strip()
            raw_level = self.mainView.textField3.GetValue().strip()
            raw_color = self.mainView.textField4.GetValue().strip()

            if self.RepresentsInt(raw_lower) and self.RepresentsInt(raw_upper):
                raw_lower = int(raw_lower)
                raw_upper = int(raw_upper)
                if raw_lower < raw_upper and raw_lower >= -100 and raw_upper <= 100 and raw_color in ['blue', 'yellow', 'green', 'purple', 'red'] :
                    self.plotController[self.current_plotController].add_quantile_section(int(raw_lower),int(raw_upper), raw_level, raw_color)
            self.mainView.textField1.SetValue("")
            self.mainView.textField2.SetValue("")
            self.mainView.textField3.SetValue("")
            self.mainView.textField4.SetValue("")

    def remove_quantile_section(self,evt):
        p = self.mainView.textField1.GetValue().strip()
        if self.RepresentsInt(p):
            p = int(p)
            self.plotController[self.current_plotController].remove_quantile_section(p)
        self.mainView.textField1.SetValue("")




    def add_state(self, evt):
        _state = self.mainView.textField5.GetValue().strip()
        #there is a plot in UI, and successfully add state
        if self.loadFlag:
            if self.plotController[self.current_plotController].add_state(_state):
                self.mainView.add_check_box(_state)
                self.mainView.textField5.SetValue("")

    def show_landmark(self, landmark_pos, state_list):
        self.cv_capture.set(cv.CV_CAP_PROP_POS_FRAMES, landmark_pos)
        pos = self.cv_capture.get(cv.CV_CAP_PROP_POS_MSEC)
        self.mainView.mc.Seek(pos)
        for cb in self.mainView.stateCheckBox:
            index = self.mainView.stateCheckBox.index(cb)
            if cb.GetLabel() in state_list:
                self.mainView.stateCheckBox[index].SetValue(True)
            else:
                self.mainView.stateCheckBox[index].SetValue(False)


    def onClick(self, evt):
        #self.current_plotController = self.mainView.plot_notebook.GetSelection()
        if self.loadFlag and evt.xdata and evt.ydata:
            pos = self.mainView.mc.Tell()
            print "click event on %f"%(pos)
            self.cv_capture.set(cv.CV_CAP_PROP_POS_MSEC, pos)
            self.current_frame = self.cv_capture.get(cv.CV_CAP_PROP_POS_FRAMES)
            state_list = []
            audioflag = self.mainView.audioOff.GetValue()
            offset = self.cv_capture.get(cv.CV_CAP_PROP_FRAME_COUNT) * 0.002
            temp_landmark = []
            
            for landmark in self.plotController[self.current_plotController].landmark_list:
                if landmark[0] > evt.xdata - offset and landmark[0] < evt.xdata + offset and landmark[1] > evt.ydata - offset and landmark[1] < evt.ydata + offset:
                    temp_landmark = landmark
                    print "landmark clicked!!"
                    print landmark
                    break
            #if left click
            if evt.button == 1:
                for cb in self.mainView.stateCheckBox:
                    if cb.GetValue():
                        state_list.append(cb.GetLabel())
                #no landmark is clicked
                if not temp_landmark:
                    print "adding a land mark on %f, %f "%(self.current_frame, evt.ydata)
                    self.plotController[self.current_plotController].add_landmark(self.current_frame, evt.ydata, audioflag, state_list)
                else:
                    self.show_landmark(temp_landmark[0], temp_landmark[4])
            #if right click
            else:
                if temp_landmark:
                    self.plotController[self.current_plotController].remove_landmark(landmark)



                        



    def showPreview(self, evt):
        k = 5
        if self.loadFlag:
            if self.previewImage:
                for p in self.previewImage:
                    self.previewImage.remove(p)
        
            offset = self.mainView.mc.Tell()
            k_frame = offset*self.fps/1000
            if k_frame >= 2 * k:
                k_frame = k_frame - 2 * k
            for i in range(0,5):
                self.cv_capture.set(cv.CV_CAP_PROP_POS_FRAMES, k_frame)
                ret, frame = self.cv_capture.read()
                frame = cv2.resize(frame, (144, 108))
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                height, width = frame.shape[:2]
                bmp = wx.BitmapFromBuffer(width, height, frame)
                control = wx.StaticBitmap(self.mainView.infoPanel, -1, bmp)
                control.SetPosition((5+(144+10) * i, 100))
                self.previewImage.append(control)
                k_frame = k_frame + k
            self.cv_capture.set(cv.CV_CAP_PROP_POS_MSEC, offset)


    def interpolate(self, evt):
        self.plotController[self.current_plotController].fit_curve()


    def exportToCSV(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView, "Save CSV file", "", "",
                                "CSV files (*.csv)|*.csv", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_CANCEL:
                return
            path = dlg.GetPath()
            self.plotController[self.current_plotController].exportData(path, 0)
            dlg.Destroy()
            
    def exportConfigData(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView, "Save config file", "", "",
                                "CSV files (*.csv)|*.csv", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_CANCEL:
                return
            path = dlg.GetPath()
            self.plotController[self.current_plotController].exportConfigData(path)
            dlg.Destroy()


    def importFromCSV(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView, message="Choose a csv file",
                            defaultDir=os.getcwd(), defaultFile="",
                            style=wx.OPEN | wx.CHANGE_DIR )
            if dlg.ShowModal() == wx.ID_OK:
                path = dlg.GetPath()
                print self.current_plotController
                self.plotController[self.current_plotController].importData(path)
                dlg.Destroy()


    def importConfigData(self, evt):
        if self.loadFlag:
            dlg = wx.FileDialog(self.mainView, message="Choose a configuration csv file",
                                defaultDir=os.getcwd(), defaultFile="",
                                style=wx.OPEN | wx.CHANGE_DIR )
            if dlg.ShowModal() == wx.ID_OK:
                path = dlg.GetPath()
                self.plotController[self.current_plotController].importConfigData(path)
                dlg.Destroy()
                #animpos1 = animation.FuncAnimation(fig1, self.posIndicate1, interval = 1000, blit=False, repeat = True)
    #
    #framepos2 = animation.FuncAnimation(fig2, posIndicate2, fargs = (self.mainView.mc.Tell() * self.fps / 1000),
    #                                                                    interval=10, blit=False)
    #self.toolbar =Toolbar(self.canvas)
    #self.mainView.SetSizer(self.mainView.sizer)



    def plotChanged(self, event):
        self.current_plotController = self.mainView.plot_notebook.GetSelection()
        event.Skip()





    def on_close(self, evt):
        evt.skip()
        print "True"
        exit()
示例#18
0
from MainView import *
if __name__ == '__main__':
    app = QApplication(sys.argv)

    downloadThreads = []
    requestPath = 1
    ui = MainView()
    # ui.setupUi(mainWindow)
    ui.show()
    sys.exit(app.exec_())