Esempio n. 1
0
    def __init__(self):
        super(BaseWindow, self).__init__('Test')

        # Definition of the forms fields
        self._mdiArea = ControlMdiArea()

        self._textField = ControlText("Example")
        self._projectTree = ControlDockWidget(
            'Project tree', side=ControlDockWidget.SIDE_RIGHT)
        self._details = ControlDockWidget('Details',
                                          side=ControlDockWidget.SIDE_RIGHT)
        self._addWindow = ControlButton('Add window')

        self.formset = ['_addWindow', '_textField', '_mdiArea']

        self._details.value = SimpleExample1()

        # self._mdiArea.showCloseButton = False
        self._addWindow.value = self.__addWindow

        self.mainmenu.append({
            'File': [
                {
                    'Save as': self.saveWindow
                },
                {
                    'Open as': self.loadWindow
                },
                '-',
                {
                    'Exit': self.__exit
                },
            ]
        })
Esempio n. 2
0
class SRSMicroscope(BaseWidget):
    def __init__(self):
        BaseWidget.__init__(self, 'SRS Microscope')
        self.set_margin(10)

        self.expmt = None
        self._open_panel = ControlDockWidget()
        self._selector = Selector()
        self._selector._start_button.value = self._new_experiment

        self._open_panel.value = self._selector

        self._expmt_panel = ControlEmptyWidget()
        self._expmt_panel.hide()

        self.mainmenu = [ { 'File' : [ { 'Save' : self.save } ] } ]

        self.calibfile = 'calibration/t0_calibration.yaml'

    def _new_experiment(self):
        tmp = ''
        with open('calibration/formset.yaml') as f:
            for line in f:
                tmp += line
            formset = yaml.load(tmp)
        try:
            if self._selector.dir == '':
                raise DirError
            if self._selector.expmt == 0:
                raise ExpmtError
            elif self._selector.expmt == 1:
                self.expmt = BasicExperiment(formset, self.calibfile, self._selector.dir)
                self.expmt.parent = self._expmt_panel
                self._expmt_panel.value = self.expmt
                self.value = self.expmt
                self._expmt_panel.show()
                self._open_panel.hide()
            elif self._selector.expmt == 2:
                self.expmt = Calibrator(formset, self.calibfile, self._selector.dir)
                self.expmt.parent = self._expmt_panel
                self._expmt_panel.value = self.expmt
                self.value = self.expmt
                self._expmt_panel.show()
                self._open_panel.hide()

        except DirError as e:
            print(e)
        except ExpmtError as e:
            print(e)

    def save(self):
        tmp = time.localtime()[0:3]
    #    date = '%i-%i-%i' % (tmp[0], tmp[1], tmp[2])
    #    with open('%s/%s_ExpmtLog' % (self._selector.dir, date), 'w') as f:
    #        f.write(self.expmt.expmt_history.value)

    def closeEvent(self, event):
        self.expmt.beforeClose()
        super(BaseWidget, self).closeEvent(event)
Esempio n. 3
0
class Module(object):
    def __init__(self):
        """
		This implements the Path edition functionality
		"""
        super(Module, self).__init__()

        self._right_docker = ControlDockWidget(
            'Videos list', side=ControlDockWidget.SIDE_LEFT, order=0, margin=5)
        self._right_details = ControlDockWidget(
            'Details', side=ControlDockWidget.SIDE_RIGHT, order=1, margin=5)

        self._right_docker.value = self._project
        #self._right_docker.hide()
        #self._right_details.hide()

        self.mainmenu[2]['Windows'].append({
            'Videos': self.__show_objects_list_event,
            'icon': conf.ANNOTATOR_ICON_MOVIES
        })

    def __show_objects_list_event(self):
        self._right_docker.show()
        self._right_details.show()

    def process_frame_event(self, frame):
        """
		Function called before render each frame
		"""
        if self._player.video_index is not None:
            self._project.draw(frame, self._player.video_index - 1)
        return super().process_frame_event(frame)

    def add_graph(self, name, data):
        self._time.add_graph(name, data)

    ######################################################################################
    #### IO FUNCTIONS ####################################################################
    ######################################################################################

    ######################################################################################
    #### PROPERTIES ######################################################################
    ######################################################################################

    @property
    def objects(self):
        return self._project.objects

    @property
    def details(self):
        return self._right_details.value

    @details.setter
    def details(self, value):
        self._right_details.value = value
Esempio n. 4
0
    def __init__(self, *args, **kwargs):
        super().__init__('Cinema manager')

        self._pesel = ""
        self._client = Client('http://localhost:8080/projekt?wsdl')
        self._selected_date = date.today()

        # Screening window
        self._search_screenings_button = ControlButton("Search")
        self._screening_day = ControlNumber("Day:", default=self._selected_date.day, minimum=1,
                                            maximum=monthrange(self._selected_date.year, self._selected_date.month)[1],
                                            changed_event=self._change_day)
        self._screening_month = ControlNumber("Month:", default=self._selected_date.month, minimum=1,
                                              maximum=12, changed_event=self._change_month)
        self._screening_year = ControlNumber("Year:", default=self._selected_date.year,
                                             minimum=self._selected_date.year,
                                             maximum=self._selected_date.year + 1,
                                             changed_event=self._change_day)
        self._screening_list = ControlList('Screenings', readonly=True, select_entire_row=True,
                                           cell_double_clicked_event=self._screening_changed_event)
        self._screening_list.horizontal_headers = ['Time', 'Movie', 'Description']
        self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month,
                                                                    self._selected_date.day)
        self._search_screenings_button.value = self._searchScreeningsButton

        for showing in self._all_showings:
            self._screening_list += [showing.date.strftime("%H:%M"), str(showing.movie.title),
                                     str(showing.movie.description)]

        # Client window
        self._all_reservations = []

        self._reservation_list = ControlList('Reservations', readonly=True, select_entire_row=True,
                                             cell_double_clicked_event=self._reservation_changed_event)
        self._reservation_list.horizontal_headers = ['Date', 'Time', 'Movie', 'Seats', 'Paid']
        self._screening_panel = ControlDockWidget()
        self._screening_panel.hide()
        self._reservation_panel = ControlDockWidget()
        self._reservation_panel.hide()
        self._loginWindow = LoginWindow(self._client)
        self.hide()
        self._loginWindow.parent = self
        self._loginWindow.show()
        print(self._client.service)
        # Define the organization of the Form Controls
        self.formset = [{
            'a:Screening': [('_screening_day', '_screening_month', '_screening_year', '_search_screenings_button'), '=',
                            '_screening_list'],
            'b:Client': ['_reservation_list']
        },
        ]
Esempio n. 5
0
    def __init__(self):
        BaseWidget.__init__(self, 'SRS Microscope')
        self.set_margin(10)

        self.expmt = None
        self._open_panel = ControlDockWidget()
        self._selector = Selector()
        self._selector._start_button.value = self._new_experiment

        self._open_panel.value = self._selector

        self._expmt_panel = ControlEmptyWidget()
        self._expmt_panel.hide()

        self.mainmenu = [ { 'File' : [ { 'Save' : self.save } ] } ]

        self.calibfile = 'calibration/t0_calibration.yaml'
Esempio n. 6
0
 def __init__(self):
     People.__init__(self)
     BaseWidget.__init__(self, 'People window')
     AddMenuFuntionality.__init__(self)
     self._panel = ControlDockWidget()
     self._peopleList = ControlList('People',
                                    add_function=self.__addPersonBtnAction,
                                    remove_function=self.__rmPersonBtnAction)
     self._peopleList.horizontalHeaders = ['First name', 'Middle name', 'Last name']
Esempio n. 7
0
 def __init__(self, *args, **kwargs):
     global games_json
     super().__init__("NSScreenshotMaker")
     self._tmpinputfolder = tempfile.mkdtemp()
     self._settingsbutton = ControlButton("⚙️")
     self._settingsbutton.value = self.openSettings
     self._runbutton = ControlButton("Go!")
     self._runbutton.value = self.go
     self._combo = ControlCombo(
         helptext="The game the Switch will think the screenshot is from")
     self.gameslist = games_json
     for k in self.gameslist:
         self._combo.add_item(k, self.gameslist[k])
     self._combo.add_item("Custom", "Custom")
     self._combolabel = ControlLabel(
         "Game ID",
         helptext="The game the Switch will think the screenshot is from")
     self._imagelist = ControlFilesTree()
     self._imagelist._form.setDragEnabled(True)
     self._imagelist._form.setAcceptDrops(True)
     self._imagelist._form.setDropIndicatorShown(True)
     self._imagelist._form.dropEvent = self.dropEvent
     model = QFileSystemModel(parent=None)
     model.setReadOnly(False)
     self._imagelist._form.setModel(model)
     model.setRootPath(QtCore.QDir.currentPath())
     self._imagelist._form.setRootIndex(
         model.setRootPath(self._tmpinputfolder))
     self._imagelist._form.setIconSize(QtCore.QSize(32, 32))
     self.formset = [("_combolabel", "_combo", "_settingsbutton"),
                     "_imagelist", "_runbutton"]
     self._firstrunpanel = ControlDockWidget()
     self._firstrunpanel.hide()
     self._firstrunwin = FirstRun()
     if not os.path.isfile(
             appdirs.AppDirs("NSScreenshotMaker", "").user_data_dir +
             "/settings.json"):
         self._firstrunwin.parent = self
         self._firstrunpanel.value = self._firstrunwin
         self._firstrunpanel.show()
         self._firstrunwin.show()
     self._settingspanel = ControlDockWidget()
     self._settingspanel.hide()
     self._settingswin = SettingsWindow()
Esempio n. 8
0
    def __init__(self):
        super(MainWindow, self).__init__('Workflow')

        self._leftDock = ControlDockWidget('Project', side='left')
        self._rightDock = ControlDockWidget('Available Plugins', side='right')
        self._topDock = ControlDockWidget('Workflow', side='top')

        self._loadedPlugins = ViewerModulesListWidget()
        self.pluginsTree = PluginsTree()
        self._projWorkFlow = ViewerWorkFlowWidget(self)
        self.mdiArea = ControlMdiArea('Windows')

        self._rightDock.value = self.pluginsTree
        self._leftDock.value = self._loadedPlugins
        self._topDock.value = self._projWorkFlow

        #self._projWorkFlow 	= ControlOpenGL('Project Workflow')

        self._formset = ['mdiArea']

        self.mainmenu = [{
            'File': [
                {
                    'New': self.__newProjectEvent
                },
                {
                    'Open': self.__openProjectEvent
                },
                '-',
                {
                    'Save': self.__saveProjectEvent
                },
                '-',
                {
                    'Close': self.__closeEvent
                },
            ]
        }]

        self.pluginsTree.expandAll()
        self._viewers = []  #: Project viewers list
        self._viewers.append(self._loadedPlugins)
        self._viewers.append(self._projWorkFlow)
Esempio n. 9
0
    def __init__(self):
        """
		This implements the Path edition functionality
		"""
        super(Module, self).__init__()

        self._right_docker = ControlDockWidget(
            'Videos list', side=ControlDockWidget.SIDE_LEFT, order=0, margin=5)
        self._right_details = ControlDockWidget(
            'Details', side=ControlDockWidget.SIDE_RIGHT, order=1, margin=5)

        self._right_docker.value = self._project
        #self._right_docker.hide()
        #self._right_details.hide()

        self.mainmenu[2]['Windows'].append({
            'Videos': self.__show_objects_list_event,
            'icon': conf.ANNOTATOR_ICON_MOVIES
        })
Esempio n. 10
0
    def __init__(self):
        global conf
        conf += 'pythonvideoannotator.resources'  # Resources can only be loaded after pyqt is running

        super(BaseModule, self).__init__('Video annotation editor')

        self._project = Project(parent=self)
        Dialog.project = self._project

        self._player = ControlPlayer("Player")
        self._time = ControlEventTimeline('Time')
        self._dock = ControlDockWidget("Timeline",
                                       side='bottom',
                                       order=1,
                                       margin=5)

        self.formset = ['_player']

        self._dock.value = self._time
        self._player.process_frame_event = self.process_frame_event
        self._player.click_event = self.on_player_click_event
        self._time.key_release_event = self.__timeline_key_release_event

        self.load_order = []

        self.mainmenu.insert(
            0, {
                'File': [{
                    'Open': self.__open_project_event,
                    'icon': conf.ANNOTATOR_ICON_OPEN
                }, '-', {
                    'Save': self.__save_project_event,
                    'icon': conf.ANNOTATOR_ICON_SAVE
                }, {
                    'Save as': self.__save_project_as_event,
                    'icon': conf.ANNOTATOR_ICON_SAVE
                }, '-', {
                    'Exit': QApplication.closeAllWindows,
                    'icon': conf.ANNOTATOR_ICON_EXIT
                }]
            })
        self.mainmenu.insert(1, {'Modules': []})
        self.mainmenu.insert(2, {'Windows': []})

        track_user_stats()
Esempio n. 11
0
class CinemaManager(BaseWidget):

    def __init__(self, *args, **kwargs):
        super().__init__('Cinema manager')

        self._pesel = ""
        self._client = Client('http://localhost:8080/projekt?wsdl')
        self._selected_date = date.today()

        # Screening window
        self._search_screenings_button = ControlButton("Search")
        self._screening_day = ControlNumber("Day:", default=self._selected_date.day, minimum=1,
                                            maximum=monthrange(self._selected_date.year, self._selected_date.month)[1],
                                            changed_event=self._change_day)
        self._screening_month = ControlNumber("Month:", default=self._selected_date.month, minimum=1,
                                              maximum=12, changed_event=self._change_month)
        self._screening_year = ControlNumber("Year:", default=self._selected_date.year,
                                             minimum=self._selected_date.year,
                                             maximum=self._selected_date.year + 1,
                                             changed_event=self._change_day)
        self._screening_list = ControlList('Screenings', readonly=True, select_entire_row=True,
                                           cell_double_clicked_event=self._screening_changed_event)
        self._screening_list.horizontal_headers = ['Time', 'Movie', 'Description']
        self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month,
                                                                    self._selected_date.day)
        self._search_screenings_button.value = self._searchScreeningsButton

        for showing in self._all_showings:
            self._screening_list += [showing.date.strftime("%H:%M"), str(showing.movie.title),
                                     str(showing.movie.description)]

        # Client window
        self._all_reservations = []

        self._reservation_list = ControlList('Reservations', readonly=True, select_entire_row=True,
                                             cell_double_clicked_event=self._reservation_changed_event)
        self._reservation_list.horizontal_headers = ['Date', 'Time', 'Movie', 'Seats', 'Paid']
        self._screening_panel = ControlDockWidget()
        self._screening_panel.hide()
        self._reservation_panel = ControlDockWidget()
        self._reservation_panel.hide()
        self._loginWindow = LoginWindow(self._client)
        self.hide()
        self._loginWindow.parent = self
        self._loginWindow.show()
        print(self._client.service)
        # Define the organization of the Form Controls
        self.formset = [{
            'a:Screening': [('_screening_day', '_screening_month', '_screening_year', '_search_screenings_button'), '=',
                            '_screening_list'],
            'b:Client': ['_reservation_list']
        },
        ]

    def _screening_changed_event(self, row, column):
        self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month,
                                                                    self._selected_date.day)
        print(self._all_showings)
        win = ScreeningWindow(self._all_showings[row], self._client, self._pesel)
        win.parent = self
        self._screening_panel.show()
        self._reservation_panel.hide()
        self._screening_panel.label = "Screening info"
        self._screening_panel.value = win

    def _reservation_changed_event(self, row, column):
        self._all_reservations = self._client.service.getUserReservationsByPesel(self._pesel)
        win = ClientReservationWindow(self._all_reservations[row], self._client)
        win.parent = self
        self._screening_panel.hide()
        self._reservation_panel.show()
        self._reservation_panel.label = "Reservation details"
        self._reservation_panel.value = win

    def setUserPesel(self,pesel):
        self._pesel = pesel
        self.updateInfo()

    def updateInfo(self):
        self._screening_list.clear()
        self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month,
                                                                    self._selected_date.day)
        for show in self._all_showings:
            self._screening_list += [show.date.strftime("%H:%M"), str(show.movie.title),
                                     str(show.movie.description)]
        self._reservation_list.clear()
        self._all_reservations = self._client.service.getUserReservationsByPesel(self._pesel)
        for reservation in self._all_reservations:
            self._reservation_list += [reservation['showing']['date'].strftime("%d-%m-%Y"),
                                       reservation['showing']['date'].strftime("%H:%M"),
                                       str(reservation['showing']['movie']['title']), str(reservation['places']),
                                       "Yes" if reservation['isPaid'] is True else "No"]

    def _searchScreeningsButton(self):
        self._screening_list.clear()
        self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month,
                                                                    self._selected_date.day)
        for show in self._all_showings:
            self._screening_list += [show.date.strftime("%H:%M"), str(show.movie.title),
                                     str(show.movie.description)]

    def _change_day(self):
        self._selected_date = self._selected_date.replace(day=int(self._screening_day.value))

    def _change_month(self):
        self._selected_date = self._selected_date.replace(month=int(self._screening_month.value), day=1)
        self._screening_day.max = monthrange(self._selected_date.year, self._selected_date.month)[1]
        self._screening_day.value = 1
    def __init__(self, screening_info: dict, client: Client, pesel: str):
        BaseWidget.__init__(self, 'Person window')
        # Definition of the forms fields
        self._screening_info = screening_info
        self._client = client
        self._pesel = pesel
        self._image = self._client.service.getImage(
            self._screening_info['movie']['id_movie'])
        image_open = Image.open(io.BytesIO(self._image))
        rgb_im = image_open.convert('RGB')
        if not os.path.exists("../resources/images"):
            os.makedirs("../resources/images")
        rgb_im.save(
            f'../resources/images/{str(self._screening_info["movie"]["id_movie"])}.jpg'
        )
        self._dateField = ControlText(
            'Date',
            enabled=False,
            default=self._screening_info['date'].strftime("%d-%m-%Y"))
        self._timeField = ControlText(
            'Time',
            enabled=False,
            default=self._screening_info['date'].strftime("%H:%M"))
        self._titleField = ControlText(
            'Title',
            enabled=False,
            default=self._screening_info['movie']['title'])
        self._descriptionField = ControlTextArea(
            'Description',
            enabled=False,
            default=self._screening_info['movie']['description'])
        self._actorField = ControlList('Actors', enabled=False)
        self._actorField.horizontal_headers = ['Name', 'Surname']
        for actor in self._screening_info['movie']['actors']:
            self._actorField += [actor['firstName'], actor['secondName']]
        self._directorField = ControlList("Director", enabled=False)
        self._directorField.horizontal_headers = ['Name', 'Surname']
        self._directorField += [
            self._screening_info['movie']['director']['firstName'],
            self._screening_info['movie']['director']['secondName']
        ]
        self._imageField = ControlImage('Poster')
        self._imageField.value = cv2.imread(
            f'../resources/images/{str(self._screening_info["id_showing"])}.jpg'
        )
        self._freeSeatsField = ControlTextArea(
            'Free seats',
            enabled=False,
            default=self._screening_info['freePlaces'])
        self._chosenSeatsField = ControlText(
            'Chosen seats (write down the numbers and separate them with ";")')
        self._buttonField = ControlButton('Reserve')
        self._panel = ControlDockWidget()
        # Define the button action
        self._buttonField.value = self.__buttonAction

        self.formset = [('_dateField', '_timeField'),
                        ('_imageField', ['_titleField', '_descriptionField']),
                        ('_directorField', '_actorField'),
                        ('_freeSeatsField', '_chosenSeatsField'),
                        '_buttonField', '_panel']
Esempio n. 13
0
class NSScreenshotMakerGUI(BaseWidget):
    def __init__(self, *args, **kwargs):
        global games_json
        super().__init__("NSScreenshotMaker")
        self._tmpinputfolder = tempfile.mkdtemp()
        self._settingsbutton = ControlButton("⚙️")
        self._settingsbutton.value = self.openSettings
        self._runbutton = ControlButton("Go!")
        self._runbutton.value = self.go
        self._combo = ControlCombo(
            helptext="The game the Switch will think the screenshot is from")
        self.gameslist = games_json
        for k in self.gameslist:
            self._combo.add_item(k, self.gameslist[k])
        self._combo.add_item("Custom", "Custom")
        self._combolabel = ControlLabel(
            "Game ID",
            helptext="The game the Switch will think the screenshot is from")
        self._imagelist = ControlFilesTree()
        self._imagelist._form.setDragEnabled(True)
        self._imagelist._form.setAcceptDrops(True)
        self._imagelist._form.setDropIndicatorShown(True)
        self._imagelist._form.dropEvent = self.dropEvent
        model = QFileSystemModel(parent=None)
        model.setReadOnly(False)
        self._imagelist._form.setModel(model)
        model.setRootPath(QtCore.QDir.currentPath())
        self._imagelist._form.setRootIndex(
            model.setRootPath(self._tmpinputfolder))
        self._imagelist._form.setIconSize(QtCore.QSize(32, 32))
        self.formset = [("_combolabel", "_combo", "_settingsbutton"),
                        "_imagelist", "_runbutton"]
        self._firstrunpanel = ControlDockWidget()
        self._firstrunpanel.hide()
        self._firstrunwin = FirstRun()
        if not os.path.isfile(
                appdirs.AppDirs("NSScreenshotMaker", "").user_data_dir +
                "/settings.json"):
            self._firstrunwin.parent = self
            self._firstrunpanel.value = self._firstrunwin
            self._firstrunpanel.show()
            self._firstrunwin.show()
        self._settingspanel = ControlDockWidget()
        self._settingspanel.hide()
        self._settingswin = SettingsWindow()

    def dropEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            # to get a list of files:
            drop_list = []
            for url in event.mimeData().urls():
                drop_list.append(str(url.toLocalFile()))
            # handle the list here
            for f in drop_list:
                try:
                    if not f.endswith(".cbr") and not f.endswith(
                            ".cbz") and not f.endswith(
                                ".zip") and not f.endswith(".rar"):
                        Image.open(f)
                    shutil.copy(f, self._tmpinputfolder)
                except:
                    pass
        else:
            event.ignore()

    def closeEvent(self, event):
        shutil.rmtree(self._tmpinputfolder)

    def openSettings(self):
        self._firstrunwin.close()
        self._firstrunpanel.hide()
        self._settingswin.close()
        self._settingswin.parent = self
        self._settingspanel.value = self._settingswin
        self._settingspanel.show()
        self._settingswin.show()

    def go(self):
        global settings_json
        if len(os.listdir(self._tmpinputfolder)) == 0:
            return
        prevFileName = ""
        totalElements = 0
        state = 0
        if settings_json["type"] == "manga":
            state = 1
        if settings_json["type"] == "comics":
            state = 2
        for fileName in os.listdir(self._tmpinputfolder):
            print("Processing file " + fileName)
            totalElements += 1
            if fileName.endswith(".zip") or fileName.endswith(".cbz"):
                zf = zipfile.ZipFile(self._tmpinputfolder + "/" + fileName)
                for f in zf.infolist():
                    with open(self._tmpinputfolder + "/" + f.filename,
                              "wb") as fp:
                        fp.write(zf.read(f))
            elif fileName.endswith(".rar") or fileName.endswith(".cbr"):
                rf = rarfile.RarFile(self._tmpinputfolder + "/" + fileName)
                for f in rf.infolist():
                    with open(self._tmpinputfolder + "/" + f.filename,
                              "wb") as fp:
                        fp.write(rf.read(f))
            else:
                try:
                    if state == 0:
                        if list(self._combo._items.values())[
                                self._combo.current_index] != "Custom":
                            processFile(
                                self._tmpinputfolder + "/" + fileName,
                                bytes.fromhex(settings_json["hmackey"]),
                                list(self._combo._items.values())[
                                    self._combo.current_index],
                                settings_json["outputfolder"])
                        else:
                            processFile(
                                self._tmpinputfolder + "/" + fileName,
                                bytes.fromhex(settings_json["hmackey"]),
                                settings_json["customgameid"],
                                settings_json["outputfolder"])
                    elif prevFileName != "":
                        if list(self._combo._items.values())[
                                self._combo.current_index] != "Custom":
                            processFile(
                                self._tmpinputfolder + "/" + fileName,
                                bytes.fromhex(settings_json["hmackey"]),
                                list(self._combo._items.values())[
                                    self._combo.current_index],
                                settings_json["outputfolder"], state,
                                self._tmpinputfolder + "/" + prevFileName)
                        else:
                            processFile(
                                self._tmpinputfolder + "/" + fileName,
                                bytes.fromhex(settings_json["hmackey"]),
                                settings_json["customgameid"],
                                settings_json["outputfolder"], state,
                                self._tmpinputfolder + "/" + prevFileName)
                        prevFileName = ""
                        continue
                    prevFileName = fileName
                except:
                    pass
        if state != 0 and totalElements % 2 != 0:
            if list(self._combo._items.values())[
                    self._combo.current_index] != "Custom":
                processFile(
                    self._tmpinputfolder + "/" + fileName,
                    bytes.fromhex(settings_json["hmackey"]),
                    list(self._combo._items.values())
                    [self._combo.current_index], settings_json["outputfolder"])
            else:
                processFile(self._tmpinputfolder + "/" + fileName,
                            bytes.fromhex(settings_json["hmackey"]),
                            settings_json["customgameid"],
                            settings_json["outputfolder"])
Esempio n. 14
0
    def __init__(self):
        global conf
        conf += 'pythonvideoannotator.resources'  # Resources can only be loaded after pyqt is running

        super().__init__('Video annotation editor')

        self._project = Project(parent=self)
        Dialog.project = self._project

        self._player = ControlPlayer("Player")
        self._time = ControlEventTimeline('Time')
        self._dock = ControlDockWidget("Timeline",
                                       side='bottom',
                                       order=1,
                                       margin=5)
        self._progress = ControlProgress('Progress', visible=False)

        # define the application toolbar
        self.toolbar = [
            ControlButton('Open',
                          icon=conf.ANNOTATOR_ICON_OPEN,
                          default=self.__open_project_event),
            ControlButton('Save',
                          icon=conf.ANNOTATOR_ICON_SAVE,
                          default=self.__save_project_event)
        ]

        self.formset = ['_player', '_progress']

        self._dock.value = self._time
        self._player.process_frame_event = self.process_frame_event
        self._player.click_event = self.on_player_click_event
        self._player.double_click_event = self.on_player_double_click_event
        self._player.drag_event = self.on_player_drag_event
        self._player.end_drag_event = self.on_player_end_drag_event

        # ignore these controls key release event
        self._time.key_release_event = lambda x: x
        self._player.key_release_event = lambda x: x

        self.load_order = []

        self.mainmenu.insert(
            0, {
                'File': [{
                    'Open': self.__open_project_event,
                    'icon': conf.ANNOTATOR_ICON_OPEN
                }, '-', {
                    'Save': self.__save_project_event,
                    'icon': conf.ANNOTATOR_ICON_SAVE
                }, {
                    'Save as': self.__save_project_as_event,
                    'icon': conf.ANNOTATOR_ICON_SAVE
                }, '-', {
                    'Exit': QApplication.closeAllWindows,
                    'icon': conf.ANNOTATOR_ICON_EXIT
                }]
            })
        self.mainmenu.insert(1, {'Modules': []})
        self.mainmenu.insert(2, {'Windows': []})

        track_user_stats()

        ########################################################################
        ###### CHECK NEW VERSIONS RELEASES #####################################
        ########################################################################
        try:
            versions = pypi_xmlrpc.package_releases('Python-video-annotator')

            if versions is not None:
                new_version = versions[0]
                if float(new_version) > float(__version__):
                    response = self.question(
                        "<h2>New version <b>[{0}]</b> available</h2>"
                        "<p>Do you wish to update the software?</p>"
                        "<p>The software can be updated later by running the next command in the terminal:</p>"
                        "<i>pip install python-video-annotator --force-reinstall</i>"
                        .format(new_version),
                        'New version [{0}]'.format(new_version))

                    if response == 'yes':
                        subprocess.call([
                            sys.executable, "-m", "pip", "install",
                            'python-video-annotator', '--force-reinstall'
                        ])

                        self.message(
                            'The software was updated and this session will be closed. Please execute the software again.',
                            'Restart required')
                        exit()

            else:
                print('Unable to check new versions')

        except Exception as e:
            print('Unable to check new versions:')
Esempio n. 15
0
    def __init__(self):
        global conf
        conf += 'pythonvideoannotator.resources'  # Resources can only be loaded after pyqt is running

        super(BaseModule, self).__init__('Video annotation editor')

        self._project = Project(parent=self)
        Dialog.project = self._project

        self._player = ControlPlayer("Player")
        self._time = ControlEventTimeline('Time')
        self._dock = ControlDockWidget("Timeline",
                                       side='bottom',
                                       order=1,
                                       margin=5)

        self.formset = ['_player']

        self._dock.value = self._time
        self._player.process_frame_event = self.process_frame_event
        self._player.click_event = self.on_player_click_event
        self._time.key_release_event = self.__timeline_key_release_event

        self.load_order = []

        self.mainmenu.insert(
            0, {
                'File': [{
                    'Open': self.__open_project_event,
                    'icon': conf.ANNOTATOR_ICON_OPEN
                }, '-', {
                    'Save': self.__save_project_event,
                    'icon': conf.ANNOTATOR_ICON_SAVE
                }, {
                    'Save as': self.__save_project_as_event,
                    'icon': conf.ANNOTATOR_ICON_SAVE
                }, '-', {
                    'Exit': QApplication.closeAllWindows,
                    'icon': conf.ANNOTATOR_ICON_EXIT
                }]
            })
        self.mainmenu.insert(1, {'Modules': []})
        self.mainmenu.insert(2, {'Windows': []})

        track_user_stats()

        ########################################################################
        ###### CHECK NEW VERSIONS RELEASES #####################################
        ########################################################################
        try:
            versions = pypi_xmlrpc.package_releases('Python-video-annotator')

            if versions is not None:
                new_version = versions[0]
                new_version_numbers = [int(x) for x in new_version.split('.')]
                version_numbers = [int(x) for x in __version__.split('.')]
                for new_n, n in zip(new_version_numbers, version_numbers):
                    if new_n > n:
                        response = self.question(
                            "<h2>New version <b>[{0}]</b> available</h2>"
                            "<p>Do you wish to update the software?</p>"
                            "<p>The software can be updated later by running the next command in the terminal:</p>"
                            "<i>pip install python-video-annotator --force-reinstall</i>"
                            .format(new_version),
                            'New version [{0}]'.format(new_version))

                        if response == 'yes':
                            subprocess.call([
                                sys.executable, "-m", "pip", "install",
                                'python-video-annotator', '--force-reinstall'
                            ])

                            self.message(
                                'The software was updated and this session will be closed. Please execute the software again.',
                                'Restart required')
                            exit()
                        break
            else:
                print('Enabled to check new versions')

        except Exception as e:
            print('Enabled to check new versions:')
Esempio n. 16
0
    def __init__(self, *args, **kwargs):
        super().__init__('Hazard Labelling')

        self._args = {  "filepath": FILEPATH,
                        "folder": FOLDER,
                        "dest": DEST
                        }

        self.set_margin(10)

        #Definition of the forms fields
        self._videofile = ControlFile('Video')
        self._hazardbutton = ControlButton('Hazard')
        self._next = ControlButton('Next Video')
        self._save_data = ControlButton('Save labels')
        self._player = ControlPlayer('Player')
        self._timeline = ControlEventTimeline('Timeline')
        self._panel = ControlDockWidget(label='Timeline', side='bottom', margin=10)
        self._status = ControlText('Status')
        self._file_list = []

        if self._args["folder"] is None:
            if self._args["filepath"] is not None:
                self._file_list = self._args["filepath"]
        elif self._args["folder"] is not None:
            if os.path.isdir(self._args["folder"]):
                self.__updateStatus("Source folder found at: {}".format(self._args["folder"]))
                print("Scanning folder and all subfolders... {}".format(self._args["folder"]))
                count = 0
                for (dirpath, dirnames, filenames) in os.walk(self._args["folder"]):
                    path = []
                    for f in filenames:
                        if f.rsplit('.')[-1] in ACCEPTABLE_EXT:
                            count += 1
                            path.append(dirpath + "/" + f)
                    self._file_list.extend(path)
                    if count % 100 == 0:
                        print("Found {} files...".format(count))
                print("Scan complete, found {} acceptable files".format(count))
        self._video_count = len(self._file_list)
        self._progress = ControlProgress(label="Video %p of " + str(self._video_count), defaultValue=1, min=1, max=self._video_count)

        self._hazard_counter = 0
        self._current_video = 0

        #Define function calls on button presses
        self._videofile.changed_event = self.__videoFileSelectionEvent
        self._hazardbutton.value = self.__labelHazard
        self._next.value = self.__nextVideo
        self._save_data.value = self.__saveData
        self._panel.value = self._timeline
        self._progress.value = self._current_video + 1

        #Define events
        self._player.process_frame_event = self.__processFrame
        self._player.click_event = self.__clickEvent
        self._player.key_release_event = self.__tagEvent

        #Define the organization of the Form Controls
        self._formset = [
            '_player',
            # '_hazardbutton',
            '_panel',
            ('_videofile', '_next'),
            ('_status', '_save_data'),
            '_progress'
            ]

        self._video_loaded = False

        try:
            self.__videoFileSelect(self._file_list[self._current_video])
        except Exception as e:
            self.__updateStatus("Select video...")

        self._hazard_default_duration = 0