コード例 #1
0
class VideoPlayer(QWidget):
    def __init__(self, img_path, parent=None):
        super(VideoPlayer, self).__init__(parent)
        if __name__ == '__main__':
            self.setWindowTitle("Player")
            self.setGeometry(0, 0, 640, 480)
        else:
            self.setGeometry(0, 0, parent.width(), parent.height())
            self.main = parent

        self.fileName = img_path
        btnSize = QSize(16, 16)
        self.videoWidget = QLabel()
        self.videoWidget.setAlignment(Qt.AlignCenter)

        if __name__ == '__main__':
            openButton = QPushButton()
            openButton.setToolTip("Open Video File")
            openButton.setStatusTip("Open Video File")
            openButton.setFixedHeight(24)
            openButton.setIconSize(btnSize)
            openButton.setText("Vidéo")
            openButton.setFont(QFont("Noto Sans", 8))
            openButton.setIcon(QIcon.fromTheme("document-open"))
            openButton.clicked.connect(self.openFile)

        self.playButton = QPushButton()
        self.playButton.setEnabled(True)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        if __name__ == '__main__':
            controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.loadFile(self.fileName)
        self.statusBar.showMessage(self.fileName)

        if __name__ == '__main__':
            self.setLayout(layout)
            self.show()
        else:
            self.main.setLayout(layout)

    def openFile(self):
        self.fileName, _ = QFileDialog.getOpenFileName(
            self, "Open Movie", QDir.homePath(),
            "All Files *.* ;; MP4 *.mp4 ;; FLV *.flv ;; TS *.ts ;; MTS *.mts ;; AVI *.avi"
        )

        if self.fileName != '':
            self.loadFile(self.fileName)

    def loadFile(self, fileName):
        self.state = "WaitingState"
        self.mediaStateChanged()
        self.cap = cv2.VideoCapture(str(fileName))
        self.frame_num = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        self.durationChanged()
        self.frame_count = 0
        self.statusBar.showMessage(fileName)

    def play(self):
        if self.state == "PlayingState":
            self.pause()
        elif self.state == "WaitingState":
            self.start()
        else:
            self.state = "PlayingState"
            self.mediaStateChanged()
            self.cap = cv2.VideoCapture(str(self.fileName))
            self.frame_count = 0

    def pause(self):
        self.state = "WaitingState"
        self.mediaStateChanged()
        self.timer.stop()

    def start(self):
        self.state = "PlayingState"
        self.mediaStateChanged()
        self.timer = QTimer()
        self.timer.timeout.connect(self.nextFrameSlot)
        self.timer.start(1000. / self.cap.get(cv2.CAP_PROP_FPS))

    def nextFrameSlot(self):
        self.frame_count += 1
        self.positionChanged()
        ret, frame = self.cap.read()
        if ret:
            img = QImage(frame.data, frame.shape[1], frame.shape[0],
                         QImage.Format_RGB888)
            img = img.rgbSwapped()
            if __name__ == '__main__':
                w, h = self.videoWidget.size().width(), self.videoWidget.size(
                ).height()
            else:
                #                TODO : Gérer le problème d'agrandissement de la fenêtre
                w, h = self.size().width(), self.size().height()
            pix = QPixmap.fromImage(
                img.scaled(w, h, Qt.KeepAspectRatio, Qt.FastTransformation))
            self.videoWidget.setPixmap(pix)
        else:
            self.state = "FinishingState"
            self.mediaStateChanged()

    def mediaStateChanged(self):
        if self.state == "PlayingState":
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        elif self.state == "WaitingState":
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaStop))

    def positionChanged(self):
        self.positionSlider.setValue(self.frame_count)

    def durationChanged(self):
        self.positionSlider.setRange(0, self.frame_num)
コード例 #2
0
ファイル: OCIOtest.py プロジェクト: dpdulac/pyScript
class convertWindow(QMainWindow):
    def __init__(self, parent=None):
        super(convertWindow, self).__init__(parent)
        self.colorSpaceIcon = QIcon(
            '/s/prodanim/ta/_sandbox/duda/tmp/colormanager.png')
        self.xSize = 1000
        self.ySize = 375
        self.startFrame = '1'
        self.endFrame = '2'
        self.InitUI()

    def InitUI(self):
        self.setWindowTitle('ImageConvert')
        self.centralWidget = QWidget()
        self.mainLayout = QGridLayout()
        self.centralWidget.setLayout(self.mainLayout)
        self.colorSpacesNames = self.findColorSpacesNames()
        self.statusBar = QStatusBar()
        self.statusBar.showMessage("What can I cook for you today " + _USER_ +
                                   " ?")
        self.statusBar.setStyleSheet("color : green")
        self.statusBar.setFont(QFont('Pilkius Romeus', 12))
        self.setStatusBar(self.statusBar)
        # menubar
        self.bar = self.menuBar()
        self.fileBar = self.bar.addMenu("&File")
        self.quitAction = QAction('&Quit', self)
        self.quitAction.setShortcut("Ctrl+Q")
        self.quitAction.setStatusTip(
            'Quit the program with some regrets but no remorse')
        self.quitAction.triggered.connect(qApp.quit)
        self.fileBar.addAction(self.quitAction)
        # button to do the convertion
        self.convertButton = QPushButton('convert')
        self.convertButton.setStyleSheet(
            "background-color: rgba(180,180,180,255)")

        #---------------------------Shot Group Box------------------------------
        self.shotGroupBox = QGroupBox('convert')
        self.shotGroupBox.setCheckable(True)
        self.shotGroupBox.setAttribute(Qt.WA_StyledBackground, True)
        self.shotGroupBox.setStyleSheet(
            "QGroupBox{background-color: rgba(180,180,180,255);},QTGroupBox::QToolTip{ background-color: yellow; }"
        )
        #self.shotGroupBox.setFixedSize(700, 250)
        self.shotLayout = QGridLayout(self.shotGroupBox)

        # Color space group Box
        self.colorSpaceCheckBox = QCheckBox('Use Color Spaces')
        self.colorSpaceCheckBox.setToolTip('use color space convertion')
        self.colorSpaceCheckBox.setIcon(self.colorSpaceIcon)
        self.colorSpaceCheckBox.setChecked(False)
        self.colorSpaceGroupBox = QGroupBox()
        self.colorSpaceGroupBox.setToolTip('choose the in/out color spaces')
        self.colorSpaceGroupBox.setAttribute(Qt.WA_StyledBackground, True)
        self.colorSpaceCheckBox.setStyleSheet(
            "QGroupBox{background-color: rgba(100,100,100,255);},QGroupBox::QToolTip{ background-color: yellow; }"
        )
        self.colorSpaceGroupBox.setVisible(False)
        # self.colorSpaceGroupBox.setCheckable(True)
        # self.colorSpaceGroupBox.setChecked(False)
        self.colorSpaceLayout = QGridLayout(self.colorSpaceGroupBox)
        self.inColorSpaceComboBox = QComboBox()
        self.inColorSpaceComboBox.setFixedSize(120, 25)
        self.inColorSpaceComboBox.setToolTip('from color space')
        self.inColorSpaceComboBox.addItems(self.colorSpacesNames)
        self.inColorSpaceComboBox.setCurrentIndex(self.getColorSpace())
        self.outColorSpaceComboBox = QComboBox()
        self.outColorSpaceComboBox.setFixedSize(120, 25)
        self.outColorSpaceComboBox.setToolTip('to color space')
        self.outColorSpaceComboBox.addItems(self.colorSpacesNames)
        self.outColorSpaceComboBox.setCurrentIndex(self.getColorSpace('srgb8'))
        self.inLabel = QLabel('in color space')
        self.outLabel = QLabel('out color space')
        self.choiceSpaceLabel = QLabel('conversion type')
        self.choiceSpaceComboBox = QComboBox()
        self.choiceSpaceComboBox.addItems(__CONVERTION_LIST__.keys())
        self.choiceSpaceComboBox.setToolTip(__CONVERTION_LIST__[str(
            self.choiceSpaceComboBox.currentText())])
        self.choiceSpaceComboBox.setFixedSize(170, 25)
        self.useOutSpaceName = QCheckBox('out space to name')
        self.useOutSpaceName.setToolTip(
            'add the output color space to the name (useful for rv)')
        self.useOutSpaceName.setChecked(False)
        self.widgetSpace = QWidget()
        self.colorSpaceLayout.addWidget(self.choiceSpaceLabel, 0, 0)
        self.colorSpaceLayout.addWidget(self.inLabel, 0, 1)
        self.colorSpaceLayout.addWidget(self.outLabel, 0, 2)
        self.colorSpaceLayout.addWidget(self.choiceSpaceComboBox, 1, 0)
        self.colorSpaceLayout.addWidget(self.inColorSpaceComboBox, 1, 1)
        self.colorSpaceLayout.addWidget(self.outColorSpaceComboBox, 1, 2)
        self.colorSpaceLayout.addWidget(self.widgetSpace, 1, 3)
        self.colorSpaceLayout.addWidget(self.widgetSpace, 1, 4)
        self.colorSpaceLayout.addWidget(self.useOutSpaceName, 1, 5)
        self.inLabel.setVisible(False)
        self.outLabel.setVisible(False)
        self.inColorSpaceComboBox.setVisible(False)
        self.outColorSpaceComboBox.setVisible(False)

        # file in/out groupBox
        self.fileGroupBox = QGroupBox('file in/out')
        self.fileGroupBox.setToolTip('in/out setting')
        self.fileMainGridLayout = QGridLayout(self.fileGroupBox)
        # file type
        self.fileTypeLayout = QVBoxLayout()
        self.fileTypeCombo = QComboBox()
        self.fileTypeCombo.addItems(__FILE_TYPE__)
        self.fileTypeCombo.setFixedSize(105, 25)
        self.fileTypeCombo.setToolTip(
            'type of image to import (i.e: single frame, sequence of frames, movie)'
        )
        self.fileTypeLabel = QLabel('file type')
        self.fileTypeLayout.addWidget(self.fileTypeLabel)
        self.fileTypeLayout.addWidget(self.fileTypeCombo)
        # in
        self.fileInLayout = QGridLayout()
        self.fileInPushbutton = QPushButton('file in')
        self.fileInPushbutton.setToolTip('In file')
        self.fileInLineEdit = QLineEdit()
        self.fileInLineEdit.setMinimumSize(300, 25)
        self.fileInFormatLineEdit = QLineEdit()
        self.fileInFormatLineEdit.setToolTip('input format')
        self.fileInFormatLineEdit.setFixedSize(50, 25)
        self.fileInFormatLineEdit.setEnabled(False)
        self.fileInFormatLineEdit.setStyleSheet("color: green;")
        self.fileInFormatLabel = QLabel('in format')
        self.fileInLineEdit.setToolTip('image to convert from')
        self.fileInPadLabel = QLabel('in padding')
        self.fileInPadLabel.setEnabled(True)
        self.fileInPadLineEdit = QLineEdit()
        self.fileInPadLineEdit.setToolTip("number of frame to use as padding")
        self.fileInPadLineEdit.setFixedSize(25, 25)
        self.fileInPadLineEdit.setEnabled(False)
        self.fileInPadLineEdit.setStyleSheet("color: green;")
        self.fileInInputFrameLabel = QLabel('frames')
        self.fileInInputLineEdit = QLineEdit()
        self.fileInInputLineEdit.setFixedSize(100, 25)
        self.validator = QRegExpValidator(QRegExp("[0-9,-x]*"))
        self.fileInInputLineEdit.setValidator(self.validator)
        self.fileInInputLineEdit.setToolTip(
            'frame to extract separated with a "," or "-"i.e: 20,30,40-50....')
        self.fileInAllCheckbox = QCheckBox('all')
        self.fileInAllCheckbox.setToolTip(
            'convert all frames from sequence/movie')
        self.fileInLayout.addWidget(self.fileInPushbutton, 1, 0)
        self.fileInLayout.addWidget(self.fileInLineEdit, 1, 1)
        self.fileInLayout.addWidget(self.fileInFormatLabel, 0, 2)
        self.fileInLayout.addWidget(self.fileInFormatLineEdit, 1, 2)
        self.fileInLayout.addWidget(self.fileInInputFrameLabel, 0, 3)
        self.fileInLayout.addWidget(self.fileInInputLineEdit, 1, 3)
        self.fileInLayout.addWidget(self.fileInAllCheckbox, 1, 5)
        self.fileInLayout.addWidget(self.fileInPadLabel, 0, 6)
        self.fileInLayout.addWidget(self.fileInPadLineEdit, 1, 6)
        self.fileInInputFrameLabel.setVisible(False)
        self.fileInInputLineEdit.setVisible(False)
        self.fileInAllCheckbox.setVisible(False)
        self.fileInPadLabel.setVisible(False)
        self.fileInPadLineEdit.setVisible(False)

        #out
        self.fileOutLayout = QGridLayout()
        self.fileOutPushbutton = QPushButton('file out')
        self.fileOutPushbutton.setToolTip('Out Path')
        self.fileOutPathLabel = QLabel('out directory')
        self.fileOutLineEdit = QLineEdit()
        self.fileOutLineEdit.setMinimumSize(300, 25)
        self.fileOutLineEdit.setToolTip('image to convert to')
        self.fileOutFormatLabel = QLabel('out format')
        self.fileOutComboBox = QComboBox()
        self.fileOutComboBox.addItems(__FILE_FORMAT__)
        self.fileOutComboBox.setToolTip(('output format'))
        self.fileOutNameLineEdit = QLineEdit()
        self.fileOutNameLineEdit.setToolTip('name for output image(s)')
        self.fileOutNameLineEdit.setFixedSize(130, 25)
        self.fileOutNameLabel = QLabel('output name')
        self.fileOutPadLabel = QLabel('out padding')
        self.fileOutPadLineEdit = QLineEdit()
        self.fileOutPadLineEdit.setToolTip('out padding')
        self.fileOutPadLineEdit.setFixedSize(25, 25)
        self.fileOutPadCheck = QCheckBox('use padding')
        self.fileOutPadCheck.setToolTip('use padding for output')
        self.fileOutPadCheck.setChecked(False)
        self.fileOutLayout.addWidget(self.fileOutPushbutton, 1, 0)
        self.fileOutLayout.addWidget(self.fileOutLineEdit, 1, 1)
        self.fileOutLayout.addWidget(self.fileOutNameLineEdit, 1, 2)
        self.fileOutLayout.addWidget(self.fileOutComboBox, 1, 3)
        self.fileOutLayout.addWidget(self.fileOutPathLabel, 0, 1)
        self.fileOutLayout.addWidget(self.fileOutFormatLabel, 0, 3)
        self.fileOutLayout.addWidget(self.fileOutNameLabel, 0, 2)
        self.fileOutLayout.addWidget(self.fileOutPadLabel, 0, 4)
        self.fileOutLayout.addWidget(self.fileOutPadLineEdit, 1, 5)
        self.fileOutLayout.addWidget(self.fileOutPadCheck, 1, 4)
        self.fileOutPadLineEdit.setVisible(False)
        self.fileOutPadLabel.setVisible(False)
        self.fileOutPadCheck.setVisible(False)

        self.fileMainGridLayout.addLayout(self.fileTypeLayout, 0, 0)
        self.fileMainGridLayout.addLayout(self.fileInLayout, 1, 0)
        self.fileMainGridLayout.addLayout(self.fileOutLayout, 2, 0)

        self.shotLayout.addWidget(self.fileGroupBox, 0, 0)
        self.shotLayout.addWidget(self.colorSpaceCheckBox, 1, 0)
        self.shotLayout.addWidget(self.colorSpaceGroupBox, 2, 0)

        #----------------------end Shot Group Box--------------------------------

        self.mainLayout.addWidget(self.shotGroupBox, 0, 0)
        self.mainLayout.addWidget(self.convertButton, 1, 0)

        self.setCentralWidget(self.centralWidget)

        self.setFixedSize(self.xSize, self.ySize)

        #self.colorSpaceGroupBox.toggled.connect(self.enableColorSpacesChoice)
        self.colorSpaceCheckBox.toggled.connect(self.displayColorSpace)
        self.fileInAllCheckbox.toggled.connect(self.setAllImages)
        self.fileInPushbutton.clicked.connect(self.findFile)
        self.fileOutPushbutton.clicked.connect(self.findDirectory)
        self.fileTypeCombo.currentTextChanged.connect(self.fileTypeChanged)
        self.choiceSpaceComboBox.currentTextChanged.connect(
            self.convertionChoice)
        self.fileOutPadCheck.toggled.connect(self.showOutPadding)
        self.convertButton.clicked.connect(self.convertImages)

    def showOutPadding(self, s):
        if s:
            self.fileOutPadLineEdit.setVisible(True)
        else:
            self.fileOutPadLineEdit.setVisible(False)

    def convertionChoice(self):
        self.choiceSpaceComboBox.setToolTip(__CONVERTION_LIST__[str(
            self.choiceSpaceComboBox.currentText())])
        if self.choiceSpaceComboBox.currentText() == 'custom':
            self.inLabel.setVisible(True)
            self.outLabel.setVisible(True)
            self.inColorSpaceComboBox.setVisible(True)
            self.outColorSpaceComboBox.setVisible(True)
            self.widgetSpace.setVisible(False)
        else:
            self.inLabel.setVisible(False)
            self.outLabel.setVisible(False)
            self.inColorSpaceComboBox.setVisible(False)
            self.outColorSpaceComboBox.setVisible(False)
            self.widgetSpace.setVisible(True)

    def displayColorSpace(self, s):
        if s:
            self.setFixedSize(self.xSize, self.ySize + 80)
            self.colorSpaceGroupBox.setVisible(True)
            self.useOutSpaceName.setChecked(True)
        else:
            self.setFixedSize(self.xSize, self.ySize)
            self.colorSpaceGroupBox.setVisible(False)
            self.useOutSpaceName.setChecked(False)

    def setAllImages(self, s):
        if s:
            self.fileInInputLineEdit.setVisible(False)
            self.fileInInputFrameLabel.setVisible(False)
        else:
            self.fileInInputLineEdit.setVisible(True)
            self.fileInInputFrameLabel.setVisible(True)

    def fileTypeChanged(self):
        if self.fileTypeCombo.currentText() != __FILE_TYPE__[0]:
            #reset the lineEdit
            self.fileInLineEdit.setText('')
            self.fileOutLineEdit.setText('')
            self.fileOutNameLineEdit.setText('')
            self.fileInPadLineEdit.setText('')
            self.fileInFormatLineEdit.setText('')
            self.fileOutPadLineEdit.setText('')
            # change the size of combobox
            self.fileTypeCombo.setFixedSize(150, 25)
            # uncheck the all checkbox
            self.fileInAllCheckbox.setChecked(False)
            # reset the frame text
            self.fileInInputLineEdit.setText('')
            # reset the padding to invisible
            self.fileInPadLabel.setVisible(False)
            self.fileInPadLineEdit.setVisible(False)
            # set the line edit to be visible
            self.fileInInputFrameLabel.setVisible(True)
            self.fileInInputLineEdit.setVisible(True)
            self.fileInAllCheckbox.setVisible(True)
            self.fileOutPadLabel.setVisible(True)
            #self.fileOutPadLineEdit.setVisible(True)
            self.fileOutPadCheck.setVisible(True)
            if self.fileTypeCombo.currentText() == __FILE_TYPE__[1]:
                self.fileInPadLabel.setVisible(True)
                self.fileInPadLineEdit.setVisible(True)
                self.fileOutPadCheck.setVisible(False)
        else:
            # reset the lineEdit
            self.fileInLineEdit.setText('')
            self.fileOutLineEdit.setText('')
            self.fileOutNameLineEdit.setText('')
            self.fileInPadLineEdit.setText('')
            self.fileInFormatLineEdit.setText('')
            self.fileOutPadLineEdit.setText('')
            # change the size of combobox
            self.fileTypeCombo.setFixedSize(105, 25)
            self.fileInInputLineEdit.setText('')
            self.fileInAllCheckbox.setChecked(False)
            self.fileInInputFrameLabel.setVisible(False)
            self.fileInInputLineEdit.setVisible(False)
            self.fileInAllCheckbox.setVisible(False)
            self.fileInPadLabel.setVisible(False)
            self.fileInPadLineEdit.setVisible(False)
            self.fileOutPadLabel.setVisible(False)
            self.fileOutPadLineEdit.setVisible(False)
            self.fileOutPadCheck.setVisible(False)

    def getColorSpace(self, colorSpace='acescg'):
        #indexNb =0
        try:
            indexNb = self.colorSpacesNames.index(colorSpace)
        except:
            return None
        else:
            return indexNb

    def enableColorSpacesChoice(self, s):
        if s:
            self.setFixedSize(self.xSize, 350)
            self.inColorSpaceComboBox.setEnabled(True)
            self.outColorSpaceComboBox.setEnabled(True)
        else:
            self.inColorSpaceComboBox.setEnabled(False)
            self.outColorSpaceComboBox.setEnabled(False)
            self.useOutSpaceName.setChecked(False)
            self.centralWidget.setFixedHeight(250)

    def findColorSpacesNames(self):
        config = ocio.GetCurrentConfig()
        colorSpaces = [cs.getName() for cs in config.getColorSpaces()]
        return colorSpaces

    def findDirectory(self):
        dirName = QFileDialog.getExistingDirectory(self, 'Open directory',
                                                   '/s/prodanim/ta')
        self.fileOutLineEdit.setText(dirName + '/')

    def findFile(self):
        """dialog to open file of type .mov"""
        filename = ''
        splitFileName = ''
        self.startFrame = -1
        self.endFrame = -1
        if self.fileTypeCombo.currentText() == __FILE_TYPE__[0]:
            filename = QFileDialog.getOpenFileName(
                self, 'Open file', '/s/prodanim/ta',
                "Image files ( *.exr *.jpg *.png *.tif)")
            filename = str(filename[0])
            # split the filename with the .
            splitFileName = filename.split('.')
            # set the format of the in file
            self.fileInFormatLineEdit.setText('.' + splitFileName[-1])
            # pop the format and recreate the name
            splitFileName.pop(-1)
            pathFileName = filename[:filename.rfind('.')]
            # put the name without format in the in path
            self.fileInLineEdit.setText(pathFileName)
            nameframe = filename[filename.rfind('/') + 1:filename.rfind('.')]
            # find the path of the file and set the output with it
            path = filename[:filename.rfind('/')]
            self.fileOutLineEdit.setText(path + '/')
            # prefill the name of the output file
            nameLength = len(nameframe)
            self.fileOutNameLineEdit.setFixedSize(nameLength * 8, 25)
            self.fileOutNameLineEdit.setText(nameframe)
        # else if the type is sequence
        elif self.fileTypeCombo.currentText() == __FILE_TYPE__[1]:
            filename = QFileDialog.getOpenFileName(
                self, 'Open file', '/s/prodanim/ta',
                "Image files ( *.exr *.jpg *.png *.tif)")
            filename = str(filename[0])
            splitFileName = filename.split('.')
            self.fileInFormatLineEdit.setText('.' + splitFileName[-1])
            # get the path
            path = filename[:filename.rfind('/')]
            # extract the image name
            imageName = filename[filename.rfind('/') + 1:filename.rfind('.')]
            while imageName.rfind('.') != -1:
                imageName = imageName[:imageName.rfind('.')]
            # get all the file
            listAllFiles = [
                f for f in os.listdir(path) if os.path.isfile(path + '/' + f)
            ]
            listFile = []
            for i in range(len(listAllFiles)):
                if listAllFiles[i].rfind(imageName) == 0:
                    listFile.append(listAllFiles[i])
            # sort the file in croissant order
            if len(listFile) > 1:
                listFile.sort(key=lambda f: int(filter(str.isdigit, f)))
            # extract only number between .<number>.
            nbList = []
            for nb in listFile:
                nbList.append(nb[nb.find('.') + 1:nb.rfind('.')])
            if len(nbList) > 1:
                self.startFrame = str(int(
                    nbList[0]))  #str(int(filter(str.isdigit, listFile[0])))
                self.endFrame = str(int(
                    nbList[-1]))  #str(int(filter(str.isdigit, listFile[-1])))
                self.fileInInputLineEdit.setText(self.startFrame + '-' +
                                                 self.endFrame)
            # extract the padding number
            pad = nbList[0]
            if pad == '' or len(pad) == 1:
                pad = '1'
                self.fileInPadLineEdit.setText(pad)
                self.fileInLineEdit.setText(path + '/' + imageName)
            else:
                pad.isdigit()
                self.fileInPadLineEdit.setText(str(len(pad)))
                self.fileInLineEdit.setText(path + '/' + imageName)
            self.fileOutNameLineEdit.setFixedSize(len(imageName) * 8, 25)
            self.fileOutNameLineEdit.setText(imageName)
            self.fileOutLineEdit.setText(path + '/')
        else:
            filename = QFileDialog.getOpenFileName(
                self, 'Open file', '/s/prodanim/ta',
                "Image files ( *.mov *.qt)")
            filename = str(filename[0])
            splitFileName = filename.split('.')
            self.fileInFormatLineEdit.setText('.' + splitFileName[-1])
            # get the path
            path = filename[:filename.rfind('/')]
            # extract the image name
            imageName = filename[filename.rfind('/') + 1:filename.rfind('.')]
            while imageName.rfind('.') != -1:
                imageName = imageName[:imageName.rfind('.')]
            # find the nb of subimages i.e end frame
            buf = oiio.ImageBuf(filename)
            self.endFrame = str(buf.nsubimages - 1)
            self.startFrame = '1'
            self.fileInInputLineEdit.setText(self.startFrame + '-' +
                                             self.endFrame)
            self.fileInLineEdit.setText(filename[:filename.rfind('.')])
            # get the path
            path = filename[:filename.rfind('/')]
            # extract the image name
            imageName = filename[filename.rfind('/') + 1:filename.rfind('.')]
            self.fileOutNameLineEdit.setFixedSize(len(imageName) * 8, 25)
            self.fileOutNameLineEdit.setText(imageName)
            self.fileOutLineEdit.setText(path + '/')

    def convertImages(self):
        done = False
        QApplication.setOverrideCursor(Qt.WaitCursor)
        #__OIIOTOOL__ = 'rez env pyoiio -- oiiotool -v '
        __OIIOTOOL__ = 'oiiotool -v '
        # find if there is a path in the line edit
        if self.fileInLineEdit.text() == '':
            print('no image to convert')
        else:
            inSpace = ''
            outSpace = ''
            inFrame = str(self.fileInLineEdit.text() +
                          self.fileInFormatLineEdit.text())
            outFrame = str(self.fileOutLineEdit.text() +
                           self.fileOutNameLineEdit.text() + '.' +
                           self.fileOutComboBox.currentText())
            # if convert color on
            if self.colorSpaceCheckBox.isChecked():
                if self.choiceSpaceComboBox.currentText() != 'custom':
                    choice = str(self.choiceSpaceComboBox.currentText())
                    inSpace = choice[:choice.find('-')]
                    outSpace = choice[choice.rfind('>') + 1:]
                else:
                    inSpace = str(self.inColorSpaceComboBox.currentText())
                    outSpace = str(self.outColorSpaceComboBox.currentText())
            # if image mode
            if self.fileTypeCombo.currentText() == __FILE_TYPE__[0]:
                if self.useOutSpaceName.isChecked():
                    outFrame = str(self.fileOutLineEdit.text() + outSpace +
                                   '_' + self.fileOutNameLineEdit.text() +
                                   '.' + self.fileOutComboBox.currentText())
                else:
                    outFrame = str(self.fileOutLineEdit.text() +
                                   self.fileOutNameLineEdit.text() + '.' +
                                   self.fileOutComboBox.currentText())

                if self.colorSpaceCheckBox.isChecked():
                    __OIIOTOOL__ += inFrame + ' --colorconvert ' + inSpace + ' ' + outSpace + ' -o ' + outFrame
                    os.system(__OIIOTOOL__)
                else:
                    __OIIOTOOL__ += inFrame + ' -o ' + outFrame
                    os.system(__OIIOTOOL__)
                done = True
            # image mode is seqences
            elif self.fileTypeCombo.currentText() == __FILE_TYPE__[1]:
                pad = '%0' + str(self.fileInPadLineEdit.text()) + 'd'
                if self.fileInAllCheckbox.isChecked():
                    inFrameNb = self.startFrame
                    outFrameNb = self.endFrame
                    frameRange = '.' + inFrameNb + '-' + outFrameNb + pad
                    inFrame = self.fileInLineEdit.text(
                    ) + frameRange + self.fileInFormatLineEdit.text()

                    if self.useOutSpaceName.isChecked():
                        outFrame = str(self.fileOutLineEdit.text() + outSpace +
                                       '_' + self.fileOutNameLineEdit.text() +
                                       frameRange + '.' +
                                       self.fileOutComboBox.currentText())
                    else:
                        outFrame = str(self.fileOutLineEdit.text() +
                                       self.fileOutNameLineEdit.text() +
                                       frameRange + '.' +
                                       self.fileOutComboBox.currentText())

                    if self.colorSpaceCheckBox.isChecked():
                        __OIIOTOOL__ += inFrame + ' --colorconvert ' + inSpace + ' ' + outSpace + ' -o ' + outFrame
                        os.system(__OIIOTOOL__)
                    else:
                        __OIIOTOOL__ += inFrame + ' -o ' + outFrame
                        os.system(__OIIOTOOL__)
                else:
                    frameRange = ' --frames ' + str(
                        self.fileInInputLineEdit.text()) + ' '
                    inFrame = frameRange + self.fileInLineEdit.text(
                    ) + '.' + pad + self.fileInFormatLineEdit.text()
                    if self.useOutSpaceName.isChecked():
                        outFrame = str(self.fileOutLineEdit.text() + outSpace +
                                       '_' + self.fileOutNameLineEdit.text() +
                                       '.' + pad + '.' +
                                       self.fileOutComboBox.currentText())
                    else:
                        outFrame = str(self.fileOutLineEdit.text() +
                                       self.fileOutNameLineEdit.text() + '.' +
                                       pad + '.' +
                                       self.fileOutComboBox.currentText())

                    if self.colorSpaceCheckBox.isChecked():
                        __OIIOTOOL__ += inFrame + ' --colorconvert ' + inSpace + ' ' + outSpace + ' -o ' + outFrame
                        os.system(__OIIOTOOL__)
                    else:
                        __OIIOTOOL__ += inFrame + ' -o ' + outFrame
                        os.system(__OIIOTOOL__)

                done = True

            elif self.fileTypeCombo.currentText() == __FILE_TYPE__[2]:
                inFrame = self.fileInLineEdit.text(
                ) + self.fileInFormatLineEdit.text()
                pad = ''
                goodListFrame = []
                if self.fileOutPadCheck.isChecked():
                    pad = self.fileOutPadLineEdit.text()
                    if pad == '':
                        pad = '0'
                else:
                    pad = '0'
                pad = '%0' + pad + 'd'

                if self.useOutSpaceName.isChecked():
                    outFrame = str(self.fileOutLineEdit.text() + outSpace +
                                   '_' + self.fileOutNameLineEdit.text() +
                                   '.' + pad + '.' +
                                   self.fileOutComboBox.currentText())
                else:
                    outFrame = str(self.fileOutLineEdit.text() +
                                   self.fileOutNameLineEdit.text() + '.' +
                                   pad + '.' +
                                   self.fileOutComboBox.currentText())
                if self.fileInAllCheckbox.isChecked():
                    inFrameNb = self.startFrame
                    outFrameNb = self.endFrame
                    for i in range(int(inFrameNb), int(outFrameNb) + 1):
                        goodListFrame.append(str(i))
                    goodListFrame.sort(
                        key=lambda f: int(filter(str.isdigit, f)))
                    # for fn in goodListFrame:
                    #     if self.colorSpaceCheckBox.isChecked():
                    #         __OIIOTOOL__ = 'rez env pyoiio -- oiiotool -v ' + inFrame + ' --frames ' + str(fn) + ' --subimage ' + str(fn) + ' --colorconvert ' + inSpace + ' ' + outSpace + ' -o ' + outFrame
                    #         print(__OIIOTOOL__)
                    #     else:
                    #         __OIIOTOOL__= 'rez env pyoiio -- oiiotool -v ' + inFrame + ' --frames ' + str(fn) + ' --subimage ' + str(fn) +' -o ' + outFrame
                    #         print(__OIIOTOOL__)
                else:
                    # split the input in fucntion of ','
                    listFrame = str(self.fileInInputLineEdit.text()).split(',')
                    # take care of the item with '-' and add the range to the list
                    for i in range(0, len(listFrame)):
                        if listFrame[i].find('-') > 0:
                            group = listFrame[i]
                            start = group[:group.find('-')]
                            end = group[group.find('-') + 1:]
                            for j in range(int(start), int(end) + 1):
                                listFrame.append(str(j))
                    # get rid of elements with '-'
                    goodListFrame = []
                    for i in listFrame:
                        if i.find('-') < 0:
                            goodListFrame.append(i)
                    # get rid of duplicate
                    goodListFrame = list(dict.fromkeys(goodListFrame))
                    # sort the list in croissant order
                    goodListFrame.sort(
                        key=lambda f: int(filter(str.isdigit, f)))
                for fn in goodListFrame:
                    if self.colorSpaceCheckBox.isChecked():
                        __OIIOTOOL__ = 'oiiotool -v ' + inFrame + ' --frames ' + str(
                            fn
                        ) + ' --subimage ' + str(
                            fn
                        ) + ' --colorconvert ' + inSpace + ' ' + outSpace + ' -o ' + outFrame
                        os.system(__OIIOTOOL__)
                    else:
                        __OIIOTOOL__ = 'oiiotool -v ' + inFrame + ' --frames ' + str(
                            fn) + ' --subimage ' + str(fn) + ' -o ' + outFrame
                        os.system(__OIIOTOOL__)
                done = True

        if done:
            QApplication.restoreOverrideCursor()
        print("you're images are cooked enjoy with no moderation")
コード例 #3
0
class VideoPlayer(QWidget):
    send_img = pyqtSignal(QPixmap)

    def __init__(self):
        super(VideoPlayer, self).__init__()
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        btnSize = QSize(16, 16)
        self.videoWidget = QVideoWidget()

        openBtn = QPushButton("Open")
        openBtn.setFixedHeight(24)
        openBtn.clicked.connect(self.loadVideo)

        self.captureBtn = QPushButton("Capture")
        self.captureBtn.setEnabled(False)
        self.captureBtn.setFixedHeight(24)

        self.playBtn = QPushButton()
        self.playBtn.setEnabled(False)
        self.playBtn.setFixedHeight(24)
        self.playBtn.setIconSize(btnSize)
        self.playBtn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playBtn.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")

        self.captureBtn.clicked.connect(self.capture)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openBtn)
        controlLayout.addWidget(self.playBtn)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.captureBtn)

        layout = QVBoxLayout()
        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)
        self.setLayout(layout)

        self.screen = QApplication.primaryScreen()
        self.secondW = CaptureWindow()
        self.send_img.connect(self.secondW.gotImg)

    def capture(self):
        shot = self.screen.grabWindow(self.videoWidget.winId())
        print("Capture Btn Clicked")
        self.send_img.emit(shot)

    def loadVideo(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Selecciona los mediose", ".",
            "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")
        if fileName != '':
            try:
                self.mediaPlayer.setMedia(
                    QMediaContent(QUrl.fromLocalFile(fileName)))
                self.playBtn.setEnabled(True)
                self.statusBar.showMessage(fileName)
                self.play()
            except Exception as e:
                print(e)

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
            self.captureBtn.setEnabled(True)
        else:
            self.mediaPlayer.play()
            self.captureBtn.setEnabled(False)

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playBtn.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playBtn.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playBtn.setEnabled(False)
        print(self.mediaPlayer.errorString())
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
コード例 #4
0
ファイル: Notepad+.py プロジェクト: yashrajput0508/Notepad-
class GUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(600, 600)
        self.setWindowTitle("Untitled-Notepad")
        self.setWindowIcon(
            QIcon(r'C:\Users\Yash\PycharmProjects\ppppp\Notepad\icons.png'))
        #self.timer=QTimer(self)
        #self.timer.timeout.connect(self.geometrychange)
        #self.timer.start(10)
        self.menu = QMenuBar(self)
        self.file = QMenu("File", self.menu)
        file = self.file.addAction("New")
        file.setShortcut("Ctrl+N")
        file.triggered.connect(self.files)
        opens = self.file.addAction('Open')
        opens.setShortcut("Ctrl+O")
        opens.triggered.connect(self.open)
        save = self.file.addAction("Save")
        save.setShortcut("Ctrl+S")
        save.triggered.connect(self.save)
        saveas = self.file.addAction("Save as")
        saveas.triggered.connect(self.saveas)
        self.file.addSeparator()
        printsetup = self.file.addAction("Print Preview")
        printsetup.triggered.connect(self.printsetup)
        prints = self.file.addAction("Print")
        prints.setShortcut("Ctrl+P")
        prints.triggered.connect(self.prints)
        self.file.addSeparator()
        exits = self.file.addAction("Exit")
        exits.setShortcut("Alt+X")
        exits.triggered.connect(self.exists)
        self.menu.addMenu(self.file)

        self.edit = QMenu("Edit", self.menu)
        undo = self.edit.addAction("Undo")
        undo.setShortcut("Ctrl+Z")
        undo.triggered.connect(self.undos)
        self.edit.addSeparator()
        self.cuts = self.edit.addAction("Cut")
        self.cuts.setShortcut("Ctrl+X")
        self.cuts.triggered.connect(self.cut)
        self.copys = self.edit.addAction("Copy")
        self.copys.setShortcut("Ctrl+C")
        self.copys.triggered.connect(self.copy)
        self.pastes = self.edit.addAction("Paste")
        self.pastes.setShortcut("Ctrl+V")
        self.pastes.triggered.connect(self.paste)
        self.deletes = self.edit.addAction("Delete")
        self.deletes.setShortcut("Del")
        self.deletes.triggered.connect(self.delete)
        self.edit.addSeparator()
        self.finding = self.edit.addAction("Find")
        self.finding.setShortcut("Ctrl+F")
        self.finding.triggered.connect(self.finds)
        self.findnexts = self.edit.addAction("Find Next")
        self.findnexts.setShortcut("F3")
        self.findnexts.triggered.connect(self.nexts)
        replace = self.edit.addAction("Replace")
        replace.setShortcut("Ctrl+H")
        replace.triggered.connect(self.replace)
        go = self.edit.addAction("Go To")
        go.setShortcut("Ctrl+G")
        go.triggered.connect(self.go)
        check = QTimer(self)
        check.timeout.connect(self.check)
        check.start(100)
        self.edit.addSeparator()
        select = self.edit.addAction("Select All")
        select.setShortcut("Ctrl+A")
        select.triggered.connect(self.select)
        time = self.edit.addAction("Time/Date")
        time.setCheckable(True)
        time.setShortcut("F5")
        time.triggered.connect(self.todaytime)
        self.menu.addMenu(self.edit)

        self.format = QMenu("Format", self.menu)
        self.wrap = self.format.addAction("Word Wrap")
        self.wrap.setCheckable(True)
        self.wrap.setChecked(True)
        self.wrap.triggered.connect(self.word)
        font = self.format.addAction("Font")
        font.triggered.connect(self.fonts)
        self.menu.addMenu(self.format)

        self.view = QMenu("View", self.menu)
        zoom = QMenu("Zoom", self.view)
        In = zoom.addAction("Zoom In")
        In.setShortcut("Ctrl++")
        In.triggered.connect(self.zoomin)
        out = zoom.addAction("Zoom Out")
        out.setShortcut("Ctrl+-")
        out.triggered.connect(self.zoomout)
        restore = zoom.addAction("Restore Default Zoom")
        restore.setShortcut("Ctrl+0")
        restore.triggered.connect(self.restore)
        self.view.addMenu(zoom)
        self.statused = self.view.addAction("Status Bar")
        self.statused.setCheckable(True)
        self.statused.setChecked(True)
        self.statused.triggered.connect(self.status)
        self.menu.addMenu(self.view)

        self.help = QMenu("Help", self.menu)
        help = self.help.addAction("View Help")
        help.triggered.connect(self.helps)
        self.help.addSeparator()
        about = self.help.addAction("About Notepad")
        about.triggered.connect(self.about)
        self.menu.addMenu(self.help)
        self.setMenuBar(self.menu)

        self.centralwidget = QWidget(self)
        self.textEdit = QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QRect(0, 0, 600, 579))
        self.textEdit.setUndoRedoEnabled(True)
        font = QFont()
        font.setFamily('Arial')
        font.setPointSize(16)
        self.textEdit.setFont(font)
        self.textEdit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.textEdit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.textEdit.setLineWrapMode(self.textEdit.WidgetWidth)
        self.textEdit.setLineWidth(2)
        try:
            self.path = str(sys.argv[1])
            f = open(self.path, 'r', encoding='utf-8')
            data = f.read()
            self.textEdit.setText(data)
            self.setWindowTitle(os.path.basename(self.path) + '-Notepad')
        except:
            pass
        self.setCentralWidget(self.centralwidget)
        self.show()

    def closeEvent(self, event):
        if self.close:
            reply = QMessageBox.question(self, "You want to quit? ",
                                         "Task is in progress !",
                                         QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()

    def resizeEvent(self, event):
        if self.statused.isChecked() == True:
            self.status()
            self.statusbar.setGeometry(
                QRect(self.geometry().x() - self.geometry().getCoords()[0],
                      self.geometry().width(),
                      self.geometry().width(), 20))
            self.textEdit.setGeometry(
                QRect(self.geometry().x() - self.geometry().getCoords()[0],
                      self.geometry().y() - self.geometry().getCoords()[1],
                      self.geometry().width(),
                      self.geometry().height() - 42))
        else:
            self.textEdit.setGeometry(
                QRect(self.geometry().x() - self.geometry().getCoords()[0],
                      self.geometry().y() - self.geometry().getCoords()[1],
                      self.geometry().width(),
                      self.geometry().height() - 21))

    def check(self):
        if len(self.textEdit.toPlainText()) == 0:
            self.copys.setDisabled(True)
            self.cuts.setDisabled(True)
            self.pastes.setDisabled(True)
            self.deletes.setDisabled(True)
            self.finding.setDisabled(True)
            self.findnexts.setDisabled(True)
        else:
            self.finding.setDisabled(False)
            self.findnexts.setDisabled(False)
            self.copys.setDisabled(False)
            self.cuts.setDisabled(False)
            self.pastes.setDisabled(False)
            self.deletes.setDisabled(False)
        if self.statused.isChecked() == True:
            time = QTime.currentTime()
            text = time.toString("hh:mm:ss")
            self.time.display(text)
            cursor = self.textEdit.textCursor()
            row = cursor.blockNumber() + 1
            col = cursor.columnNumber()
            self.label.setText("Row: " + str(row) + "| Col: " + str(col))

    def status(self):
        if self.statused.isChecked() == True:
            self.statusbar = QStatusBar(self)
            self.statusbar.setGeometry(
                QRect(self.geometry().x() - self.geometry().getCoords()[0],
                      self.geometry().width(),
                      self.geometry().width(), 20))
            self.textEdit.setGeometry(
                QRect(self.geometry().x() - self.geometry().getCoords()[0],
                      self.geometry().y() - self.geometry().getCoords()[1],
                      self.geometry().width(),
                      self.geometry().height() - 42))
            font = QFont()
            font.setPointSize(10)
            self.statusbar.setFont(font)
            self.label = QLabel("Row: 0 | Col: 0")
            self.statusbar.addPermanentWidget(self.label)
            self.time = QLCDNumber()
            self.time.setDigitCount(8)
            self.time.setFrameShadow(QFrame.Sunken)
            self.time.setFrameShape(QFrame.Panel)
            self.statusbar.addWidget(self.time)
            self.setStatusBar(self.statusbar)
        else:
            self.textEdit.setGeometry(
                QRect(self.geometry().x() - self.geometry().getCoords()[0],
                      self.geometry().y() - self.geometry().getCoords()[1],
                      self.geometry().width(),
                      self.geometry().height() - 21))

            vboxlayout = QVBoxLayout()
            vboxlayout.setContentsMargins(QtCore.QMargins())
            vboxlayout.setSpacing(0)
            sizegrip = QSizeGrip(self.centralwidget)
            sizegrip.setVisible(True)
            vboxlayout.addWidget(sizegrip, 0, Qt.AlignBottom | Qt.AlignRight)
            self.centralwidget.setLayout(vboxlayout)
            self.statusbar.hide()

    def helps(self):
        QMessageBox.information(self, "Help",
                                "This is your notepad made by PyQt5")

    def about(self):
        QMessageBox.information(self, "About",
                                "This is the Notepad made by Yash Rajput")

    def files(self):
        self.textEdit.setText('')
        self.setWindowTitle("Untitled-Notepad")
        self.filename = ["Untitled-Notepad"]
        self.new = True

    def open(self):
        self.filename = QFileDialog.getOpenFileName(
            self, 'Open File', '\home', 'Text Files (*.txt);;All Files (*)')
        if self.filename[0]:
            f = open(self.filename[0], 'r', encoding='utf-8')
        try:
            data = f.read()
            self.textEdit.setText(data)
            self.setWindowTitle(
                os.path.basename(self.filename[0]) + '-Notepad')
        except:
            pass

    def save(self):
        try:
            if self.new == False:
                w = open(self.filename[0], 'w')
                print(self.filename[0])
                w.write(self.textEdit.toPlainText())
                w.close()
            elif self.new == True:
                self.saveas()
        except:
            self.saveas()

    def saveas(self):
        self.filename = QFileDialog.getSaveFileName(
            self, "Save as", '\home', 'Text Files(*.txt);;All Files(*)')
        try:
            f = open(self.filename[0], 'w')
            f.write(self.textEdit.toPlainText())
            f.close()
            self.new = False
            self.setWindowTitle(
                os.path.basename(self.filename[0]) + '-Notepad')
        except:
            pass

    def exists(self):
        box = QMessageBox.question(self, "You want to quit? ",
                                   "Task is in progress !", QMessageBox.Yes,
                                   QMessageBox.No)
        if box.exec() == box.Yes:
            self.destroy()

    def undos(self):
        self.textEdit.undo()

    def cut(self):
        self.textEdit.cut()

    def copy(self):
        self.textEdit.copy()

    def paste(self):
        self.textEdit.paste()

    def select(self):
        self.textEdit.selectAll()

    def delete(self):
        cursor = self.textEdit.textCursor()
        cursor.removeSelectedText()

    def todaytime(self):
        self.textEdit.insertPlainText(str(datetime.today()))

    def word(self):
        if self.wrap.isChecked():
            self.textEdit.setLineWrapMode(self.textEdit.WidgetWidth)
        else:
            self.textEdit.setLineWrapMode(self.textEdit.NoWrap)

    def fonts(self):
        font, ok = QFontDialog.getFont()
        if ok:
            self.textEdit.setFont(font)

    def zoomin(self):
        font = QFont(self.textEdit.font())
        size = font.pointSize()
        font.setPointSize(size + 1)
        self.textEdit.setFont(font)

    def zoomout(self):
        font = QFont(self.textEdit.font())
        size = font.pointSize()
        font.setPointSize(size - 1)
        self.textEdit.setFont(font)

    def restore(self):
        font = QFont()
        font.setPointSize(8)
        font.setFamily('Arial')
        self.textEdit.setFont(font)

    def finds(self):
        self.pc = Find(w)
        self.pc.exec()

    def replace(self):
        p = replaces(w)
        p.exec()

    def go(self):
        temp = Go(w)
        temp.exec()

    def prints(self):
        self.printer = QPrinter(QPrinter.HighResolution)
        dialog = QPrintDialog(self.printer, self)
        if dialog.exec_() == QPrintDialog.Accepted:
            w.textEdit.print_(self.printer)

    def printsetup(self):
        self.printer = QPrinter(QPrinter.HighResolution)
        dialog = QPrintPreviewDialog(self.printer, self)
        dialog.paintRequested.connect(self.handle_paint_request)
        dialog.exec_()

    def handle_paint_request(self, printer):
        self.textEdit.print(printer)

    def nexts(self):
        self.pc.click()
コード例 #5
0
class VideoPlayer(QWidget):
    def __init__(self, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()

        openButton = QPushButton("Open Video")
        openButton.setToolTip("Open Video File")
        openButton.setStatusTip("Open Video File")
        openButton.setFixedHeight(24)
        openButton.setIconSize(btnSize)
        openButton.setFont(QFont("Noto Sans", 8))
        openButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("D:/_Qt/img/open.png")))
        openButton.clicked.connect(self.abrir)

        speedButton = QPushButton("speedVideo")
        speedButton.setToolTip("Open Video File")
        speedButton.setStatusTip("Open Video File")
        speedButton.setFixedHeight(24)
        speedButton.setIconSize(btnSize)
        speedButton.setFont(QFont("Noto Sans", 8))
        speedButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("D:/_Qt/img/open.png")))
        speedButton.clicked.connect(self.speed)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = slider.Slider(QtCore.Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)
        self.positionSlider.sliderPressed.connect(self.setPosition)
        self.positionSlider.sliderReleased.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openButton)
        controlLayout.addWidget(speedButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.setLayout(layout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")

    def abrir(self):

        num = 0
        cmd = "ffmpeg -y -i " + "PART/" + str(
            num
        ) + ".mkv " + "-filter_complex \"[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]\" -map \"[v]\" -map \"[a]\" " + str(
            num) + ".mkv"

        #cmd = "ffmpeg -y -i "+ "PART/" + str(num) + ".mkv" + " -filter:v \"setpts=2.0*PTS\" "+ str(num) + ".mkv"
        os.system(cmd)

        player.setWindowTitle("CLONES")
        fileName = "/home/flo/tmp/Movie-SongMaker/0.mkv"

        if fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(fileName)
            self.play()

    def speed(self):

        num = 0
        cmd = "ffmpeg -y -i " + "PART/" + str(
            num
        ) + ".mkv " + "-filter_complex \"[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]\" -map \"[v]\" -map \"[a]\" " + str(
            num) + ".mkv"

        #cmd = "ffmpeg -y -i "+ "PART/" + str(num) + ".mkv" + " -filter:v \"setpts=2.0*PTS\" "+ str(num) + ".mkv"
        os.system(cmd)

        player.setWindowTitle("CLONES")
        fileName = "/home/flo/tmp/Movie-SongMaker/0.mkv"

        if fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(fileName)
            self.play()

    def play(self):

        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
class VideoPlayer(QWidget):
    def __init__(self, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        iconSize = QSize(12, 12)
        videoWidget = QVideoWidget()

        openButton = QPushButton("Open Video")
        openButton.setToolTip("Open Video File")
        openButton.setStatusTip("Open Video File")
        openButton.setFixedHeight(24)
        openButton.setFont(QFont("Noto Sans", 10))
        openButton.clicked.connect(self.abrir)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(iconSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        #进度条
        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        #音量条
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setRange(0, 100)
        self.volumeSlider.sliderMoved.connect(self.setVolume)

        self.volumeLabel = QLabel()
        self.volumeLabel.setText("    Volume Bar --> ")
        self.volumeLabel.setFont(QFont("Noto Sans", 10, QFont.Bold))

        #Information bar
        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layoutLine2 = QHBoxLayout()
        layoutLine2.setContentsMargins(0, 0, 0, 0)
        layoutLine2.addWidget(self.volumeLabel)
        layoutLine2.addWidget(self.volumeSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addLayout(layoutLine2)
        layout.addWidget(self.statusBar)

        self.setLayout(layout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.volumeChanged.connect(self.volumeChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")

    def abrir(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Selecciona los mediose", ".",
            "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")

        if fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(fileName)
            self.play()

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        print("Play state:", state)
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

        v = self.volumeSlider.value()
        pause = False
        global forwardLock
        global backwardLock
        global upLock
        global downLock
        f = open("result.txt", "r+")
        data = f.readline()

        print("Reading txt...")
        print("Data read from txt: ", data)
        if data == "[4]":
            pause = True
            self.mediaPlayer.pause()
            self.mediaStateChanged(2)
            f.close()
            while pause:
                f = open("result.txt", "r+")
                l = f.readline()
                if l == "[3]":
                    pause = False
                    self.mediaPlayer.play()
                    self.mediaStateChanged(1)
                f.close()

        if data == "[3]" and forwardLock == 0:
            f.close()
            forwardLock = 1
            self.setPosition(position + 20000)
            f = open("result.txt", "w")
            f.write('no motion')
            f.close()
        elif data != "[3]" and forwardLock == 1:
            forwardLock = 0
            f.close()
        else:
            f.close()

        if data == "[2]" and backwardLock == 0:

            f.close()
            backwardLock = 1
            if position > 20000:
                self.setPosition(position - 20000)
            else:
                self.setPosition(0)
            f = open("result.txt", "w")
            f.write('no motion')
            f.close()
        elif data != "[2]" and backwardLock == 1:
            backwardLock = 0
            f.close()
        else:
            f.close()

        if data == "[1]" and upLock == 0:
            f.close()
            upLock = 1
            print(v)
            if v + 15 > 100:
                self.setVolume(100)
            else:
                v += 15
                self.setVolume(v)
            print(v)
            print("Volume set")
            f = open("result.txt", "w")
            f.write('no motion')
            f.close()
        elif data != "[1]" and upLock == 1:
            upLock = 0
            f.close()
        else:
            f.close()

        if data == "[0]" and downLock == 0:
            f.close()
            downLock = 1
            print(v)
            if v - 15 < 0:
                self.setVolume(0)
            else:
                v -= 15
                self.setVolume(v)
            print(v)
            print("Volume set")
            f = open("result.txt", "w")
            f.write('no motion')
            f.close()
        elif data != "[0]" and downLock == 1:
            downLock = 0
            f.close()
        else:
            f.close()

        self.setVolume(v)
        print("Position changed:", position)

    def volumeChanged(self, value):
        self.volumeSlider.setValue(value)

    def setVolume(self, value):
        self.mediaPlayer.setVolume(value)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)
        print("Duration changed:", duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)
        print("Position set:", position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
コード例 #7
0
class VideoPlayer(QWidget):
    def __init__(self, name, file_path, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        # Contains full path
        self.fileName = file_path

        self.res = 'answer not yet'

        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()

        #nameLabel = QLabel("")
        #nameLabel.setText("Name of the person")

        openButton = QPushButton("Open Video")
        openButton.setToolTip("Open Video File")
        openButton.setStatusTip("Open Video File")
        openButton.setFixedHeight(24)
        openButton.setIconSize(btnSize)
        openButton.setFont(QFont("Noto Sans", 8))
        openButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("D:/_Qt/img/open.png")))
        # openButton.clicked.connect(self.abrir)

        self.result = QPushButton("Result")
        self.result.setGeometry(QtCore.QRect(500, 400, 141, 51))
        self.result.setObjectName("result")
        self.result.setEnabled(False)

        self.result.clicked.connect(self.result_window)
        """
        result window event

        """

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(50)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        #controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.result)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.mediaPlayer.setMedia(
            QMediaContent(QUrl.fromLocalFile(self.fileName)))
        self.playButton.setEnabled(True)
        #self.statusBar.showMessage(fileName)
        self.play()

        self.setLayout(layout)

        f = "Hello, " + name
        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage(f)

    def enable_result(self, res):
        self.res = res
        self.result.setEnabled(True)
        print('VideoPlayer, result is enabled')
        pass

    def abrir(self):
        # fileName, _ = QFileDialog.getOpenFileName(self, "Selecciona los mediose",
        #         ".", "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")

        # if fileName != '':
        self.mediaPlayer.setMedia(
            QMediaContent(QUrl.fromLocalFile(self.fileName)))
        self.playButton.setEnabled(True)
        #self.statusBar.showMessage(fileName)
        self.play()

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())

    def result_window(self):
        print("answer: ", self.res)
コード例 #8
0
ファイル: schnipp_plain.py プロジェクト: prometheus42/schnipp
class VideoPlayer(QWidget):
    """
    Source: https://stackoverflow.com/a/57842233
    """
    def __init__(self, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()

        self.overlay = PaintOverlay(videoWidget)
        self.overlay.setVisible(True)
        #self.overlay.hide()
        # self.button.clicked.connect(
        #    lambda: self.overlay.setVisible(False) if self.overlay.isVisible() else self.overlay.setVisible(True))

        openButton = QPushButton("Open Video")
        openButton.setToolTip("Open Video File")
        openButton.setStatusTip("Open Video File")
        openButton.setFixedHeight(24)
        openButton.setIconSize(btnSize)
        openButton.setFont(QFont("Noto Sans", 8))
        openButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("D:/_Qt/img/open.png")))
        openButton.clicked.connect(self.abrir)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.setLayout(layout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")

    def abrir(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, 'Choose video file...', '.',
            'Video Files (*.mp4 *.flv *.ts *.mts *.avi *.mkv)')

        if fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(fileName)
            self.play()

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())

    def resizeEvent(self, event):
        self.overlay.resize(event.size())
        event.accept()
class VideoPlayer(QWidget):
    def __init__(self):
        super().__init__()

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()

        openButton = QPushButton("Open Video")
        openButton.setToolTip("Open Video File")
        openButton.setStatusTip("Open Video File")
        openButton.setFixedHeight(24)
        openButton.setIconSize(btnSize)
        openButton.setFont(QFont("Noto Sans", 8))
        openButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("D:/_Qt/img/open.png")))
        openButton.clicked.connect(self.abrir)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.setLayout(layout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")
        self.video_name = None

        self.shortcut = QShortcut(QKeySequence(Qt.Key_Up), self)
        self.shortcut.activated.connect(self.volumeUp)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Down), self)
        self.shortcut.activated.connect(self.volumeDown)

        self.video_id = None

    def abrir(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Selecciona los mediose", ".",
            "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")

        if fileName != '':
            r = requests.post(POST_DATA_URL_VIDEO, json=dict(name=fileName))
            self.video_id = int(r.text)
            self.video_name = os.path.basename(fileName)
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(fileName)
            self.play()

    def get_video_id(self):
        return self.video_id

    def pause_video(self):
        self.mediaPlayer.pause()

    def resume_video(self):
        self.mediaPlayer.play()

    def volumeUp(self):
        self.mediaPlayer.setVolume(self.mediaPlayer.volume() + 10)
        print("Volume: " + str(self.mediaPlayer.volume()))

    def volumeDown(self):
        self.mediaPlayer.setVolume(self.mediaPlayer.volume() - 10)
        print("Volume: " + str(self.mediaPlayer.volume()))

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def is_paused(self):
        return not self.mediaPlayer.state() == QMediaPlayer.PlayingState

    def get_position(self):
        return self.mediaPlayer.position()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
コード例 #10
0
class GUI(QMainWindow, QThread):
    def __init__(self):
        super(GUI, self).__init__()
        self.initUI()
        self.webcam = Webcam()
        self.video = Video()
        self.input = self.webcam
        self.dirname = ""
        print("Input: webcam")
        self.statusBar.showMessage("Input: webcam", 5000)
        self.btnOpen.setEnabled(False)
        self.process = Process()
        self.status = False
        self.frame = np.zeros((10, 10, 3), np.uint8)
        # self.plot = np.zeros((10,10,3),np.uint8)
        self.bpm = 0

    def initUI(self):

        # set font
        font = QFont()
        font.setPointSize(16)

        # widgets
        self.btnStart = QPushButton("Start", self)
        self.btnStart.move(440, 520)
        self.btnStart.setFixedWidth(200)
        self.btnStart.setFixedHeight(50)
        self.btnStart.setFont(font)
        self.btnStart.clicked.connect(self.run)

        self.btnOpen = QPushButton("Open", self)
        self.btnOpen.move(230, 520)
        self.btnOpen.setFixedWidth(200)
        self.btnOpen.setFixedHeight(50)
        self.btnOpen.setFont(font)
        self.btnOpen.clicked.connect(self.openFileDialog)

        self.cbbInput = QComboBox(self)
        self.cbbInput.addItem("Webcam")
        self.cbbInput.addItem("Video")
        self.cbbInput.setCurrentIndex(0)
        self.cbbInput.setFixedWidth(200)
        self.cbbInput.setFixedHeight(50)
        self.cbbInput.move(20, 520)
        self.cbbInput.setFont(font)
        self.cbbInput.activated.connect(self.selectInput)
        # -------------------

        self.lblDisplay = QLabel(self)  # label to show frame from camera
        self.lblDisplay.setGeometry(10, 10, 640, 480)
        self.lblDisplay.setStyleSheet("background-color: #000000")

        self.lblROI = QLabel(self)  # label to show face with ROIs
        self.lblROI.setGeometry(660, 10, 200, 200)
        self.lblROI.setStyleSheet("background-color: #000000")

        self.lblHR = QLabel(self)  # label to show HR change over time
        self.lblHR.setGeometry(900, 20, 300, 40)
        self.lblHR.setFont(font)
        self.lblHR.setText("Frequency: ")

        self.lblHR2 = QLabel(self)  # label to show stable HR
        self.lblHR2.setGeometry(900, 70, 300, 40)
        self.lblHR2.setFont(font)
        self.lblHR2.setText("Heart rate: ")

        # self.lbl_Age = QLabel(self) #label to show stable HR
        # self.lbl_Age.setGeometry(900,120,300,40)
        # self.lbl_Age.setFont(font)
        # self.lbl_Age.setText("Age: ")

        # self.lbl_Gender = QLabel(self) #label to show stable HR
        # self.lbl_Gender.setGeometry(900,170,300,40)
        # self.lbl_Gender.setFont(font)
        # self.lbl_Gender.setText("Gender: ")

        # dynamic plot
        self.signal_Plt = pg.PlotWidget(self)

        self.signal_Plt.move(660, 220)
        self.signal_Plt.resize(480, 192)
        self.signal_Plt.setLabel('bottom', "Signal")

        self.fft_Plt = pg.PlotWidget(self)

        self.fft_Plt.move(660, 425)
        self.fft_Plt.resize(480, 192)
        self.fft_Plt.setLabel('bottom', "FFT")

        self.timer = pg.QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(200)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(font)
        self.setStatusBar(self.statusBar)

        # event close
        self.c = Communicate()
        self.c.closeApp.connect(self.close)

        # event change combobox index

        # config main window
        self.setGeometry(100, 100, 1160, 640)
        # self.center()
        self.setWindowTitle("Heart rate monitor")
        self.show()

    def update(self):
        # z = np.random.normal(size=1)
        # u = np.random.normal(size=1)
        self.signal_Plt.clear()
        self.signal_Plt.plot(self.process.samples[20:], pen='g')

        self.fft_Plt.clear()
        self.fft_Plt.plot(np.column_stack(
            (self.process.freqs, self.process.fft)),
                          pen='g')

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def closeEvent(self, event):
        reply = QMessageBox.question(self, "Message",
                                     "Are you sure want to quit",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            event.accept()
            self.input.stop()
            cv2.destroyAllWindows()
        else:
            event.ignore()

    def selectInput(self):
        self.reset()
        if self.cbbInput.currentIndex() == 0:
            self.input = self.webcam
            print("Input: webcam")
            self.btnOpen.setEnabled(False)
            # self.statusBar.showMessage("Input: webcam",5000)
        elif self.cbbInput.currentIndex() == 1:
            self.input = self.video
            print("Input: video")
            self.btnOpen.setEnabled(True)
            # self.statusBar.showMessage("Input: video",5000)

    def mousePressEvent(self, event):
        self.c.closeApp.emit()

        # def make_bpm_plot(self):

        # plotXY([[self.process.times[20:],
        # self.process.samples[20:]],
        # [self.process.freqs,
        # self.process.fft]],
        # labels=[False, True],
        # showmax=[False, "bpm"],
        # label_ndigits=[0, 0],
        # showmax_digits=[0, 1],
        # skip=[3, 3],
        # name="Plot",
        # bg=None)

        # fplot = QImage(self.plot, 640, 280, QImage.Format_RGB888)
        # self.lblPlot.setGeometry(10,520,640,280)
        # self.lblPlot.setPixmap(QPixmap.fromImage(fplot))

    def key_handler(self):
        """
        cv2 window must be focused for keypresses to be detected.
        """
        # self.pressed = waitKey(1) & 255  # wait for keypress for 10 ms
        self.pressed = cv2.waitKey(1) & 255
        if self.pressed == 27:  # exit program on 'esc'
            print("[INFO] Exiting")
            self.webcam.stop()
            sys.exit()

    def openFileDialog(self):
        self.dirname = QFileDialog.getOpenFileName(
            self, 'OpenFile', r"C:\Users\uidh2238\Desktop\test videos")
        # self.statusBar.showMessage("File name: " + self.dirname,5000)

    def reset(self):
        self.process.reset()
        self.lblDisplay.clear()
        self.lblDisplay.setStyleSheet("background-color: #000000")

    @pyqtSlot()
    def main_loop(self):
        frame = self.input.get_frame()

        self.process.frame_in = frame
        self.process.run()

        cv2.imshow("Processed", frame)

        self.frame = self.process.frame_out  # get the frame to show in GUI
        self.f_fr = self.process.frame_ROI  # get the face to show in GUI
        # print(self.f_fr.shape)
        self.bpm = self.process.bpm  # get the bpm change over the time

        self.frame = cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)
        cv2.putText(self.frame,
                    "FPS " + str(float("{:.2f}".format(self.process.fps))),
                    (20, 460), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 255), 2)
        img = QImage(self.frame, self.frame.shape[1], self.frame.shape[0],
                     self.frame.strides[0], QImage.Format_RGB888)
        self.lblDisplay.setPixmap(QPixmap.fromImage(img))

        self.f_fr = cv2.cvtColor(self.f_fr, cv2.COLOR_RGB2BGR)
        # self.lblROI.setGeometry(660,10,self.f_fr.shape[1],self.f_fr.shape[0])
        self.f_fr = np.transpose(self.f_fr, (0, 1, 2)).copy()
        f_img = QImage(self.f_fr, self.f_fr.shape[1], self.f_fr.shape[0],
                       self.f_fr.strides[0], QImage.Format_RGB888)
        self.lblROI.setPixmap(QPixmap.fromImage(f_img))

        self.lblHR.setText("Freq: " + str(float("{:.2f}".format(self.bpm))))

        if self.process.bpms.__len__() > 50:
            if (
                    max(self.process.bpms - np.mean(self.process.bpms)) < 5
            ):  # show HR if it is stable -the change is not over 5 bpm- for 3s
                self.lblHR2.setText(
                    "Heart rate: " +
                    str(float("{:.2f}".format(np.mean(self.process.bpms)))) +
                    " bpm")

        # self.lbl_Age.setText("Age: "+str(self.process.age))
        # self.lbl_Gender.setText("Gender: "+str(self.process.gender))
        # self.make_bpm_plot()#need to open a cv2.imshow() window to handle a pause
        # QtTest.QTest.qWait(10)#wait for the GUI to respond
        self.key_handler()  # if not the GUI cant show anything

    def run(self, input):
        self.reset()
        input = self.input
        self.input.dirname = self.dirname
        if self.input.dirname == "" and self.input == self.video:
            print("choose a video first")
            # self.statusBar.showMessage("choose a video first",5000)
            return

        if self.status is False:
            self.status = True
            input.start()
            self.btnStart.setText("Stop")
            self.cbbInput.setEnabled(False)
            self.btnOpen.setEnabled(False)
            self.lblHR2.clear()
            while self.status is True:
                self.main_loop()

        elif self.status is True:
            self.status = False
            input.stop()
            self.btnStart.setText("Start")
            self.cbbInput.setEnabled(True)
コード例 #11
0
ファイル: main.py プロジェクト: adriel3005/SrtEditor
class Main(QMainWindow, Ui_MainWindow):

    lyricList = []
    lyricCount = 0
    videoPath = ""
    videoName = ""
    darkMode = False
    redMode = False
    blueMode = False
    latestStartTime = QtCore.QTime(0, 0, 0)
    latestEndTime = QtCore.QTime(0, 0, 0)

    def __init__(self):
        super(Main, self).__init__()
        self.setupUi(self)

        self.removeButton.clicked.connect(self.OnRemove)
        self.addButton.clicked.connect(lambda: self.OnAddButton())
        self.createSRTButton.clicked.connect(self.CreateSRT)
        self.actionOpen_Video.triggered.connect(self.OpenVideoFile)

        #Modes
        self.actionDark_Mode_2.triggered.connect(
            lambda: self.ToggleDarkMode(self.darkMode))
        self.actionLight_Mode.triggered.connect(self.ToggleLightMode)
        self.actionRed_Palette.triggered.connect(
            lambda: self.ToggleRedMode(self.redMode))
        self.actionBlue_Palette.triggered.connect(
            lambda: self.ToggleBlueMode(self.blueMode))

        #Video
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()

        openButton = QPushButton("Abrir Video")
        openButton.setToolTip("Abrir Video")
        openButton.setStatusTip("Abrir Video")
        openButton.setFixedHeight(40)
        openButton.setIconSize(btnSize)
        openButton.setFont(QFont("Noto Sans", 15))
        openButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("D:/_Qt/img/open.png")))
        openButton.clicked.connect(self.open)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(65)
        self.playButton.setFixedWidth(60)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        #self.QVideoBoxVLayout = QVBoxLayout()
        self.QVideoBoxVLayout.addWidget(videoWidget)
        self.QVideoBoxVLayout.addLayout(controlLayout)
        self.QVideoBoxVLayout.addWidget(self.statusBar)

        self.setLayout(self.QVideoBoxVLayout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        # Every 200 ms
        self.mediaPlayer.setNotifyInterval(200)
        self.translator = google_translator()
        self.statusBar.showMessage("Listo")

        # connect buttons playback
        self.fiveBack.clicked.connect(lambda: self.TimeSkip(5, False))
        self.tenBack.clicked.connect(lambda: self.TimeSkip(10, False))
        self.oneMBack.clicked.connect(lambda: self.TimeSkip(.1, False))
        self.fiveForward.clicked.connect(lambda: self.TimeSkip(5, True))
        self.tenForward.clicked.connect(lambda: self.TimeSkip(10, True))
        self.oneMForward.clicked.connect(lambda: self.TimeSkip(.1, True))

        #Import srt
        self.actionInportar_Subtitulos_srt.triggered.connect(self.ImportSRT)

    def ToggleLightMode(self):
        light_palette = QPalette()
        appctxt.app.setPalette(light_palette)

    def ToggleRedMode(self, dark):

        if not dark:
            red_palette = QPalette()

            red_palette.setColor(QPalette.Window, QColor(100, 53, 53))
            red_palette.setColor(QPalette.WindowText, Qt.white)
            red_palette.setColor(QPalette.Base, QColor(25, 25, 25))
            red_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
            red_palette.setColor(QPalette.ToolTipBase, Qt.white)
            red_palette.setColor(QPalette.ToolTipText, Qt.white)
            red_palette.setColor(QPalette.Text, Qt.white)
            red_palette.setColor(QPalette.Button, QColor(53, 53, 53))
            red_palette.setColor(QPalette.ButtonText, Qt.white)
            red_palette.setColor(QPalette.BrightText, Qt.red)
            red_palette.setColor(QPalette.Link, QColor(42, 130, 218))
            red_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
            red_palette.setColor(QPalette.HighlightedText, Qt.black)

            appctxt.app.setPalette(red_palette)
            #appctxt.app.setStyleSheet(
            #    "QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }")
            self.redMode = True
        else:
            light_palette = QPalette()
            appctxt.app.setPalette(light_palette)
            self.redMode = False

    def ToggleBlueMode(self, dark):

        if not dark:
            blue_palette = QPalette()

            blue_palette.setColor(QPalette.Window, QColor(53, 53, 100))
            blue_palette.setColor(QPalette.WindowText, Qt.white)
            blue_palette.setColor(QPalette.Base, QColor(25, 25, 25))
            blue_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
            blue_palette.setColor(QPalette.ToolTipBase, Qt.white)
            blue_palette.setColor(QPalette.ToolTipText, Qt.white)
            blue_palette.setColor(QPalette.Text, Qt.white)
            blue_palette.setColor(QPalette.Button, QColor(53, 53, 53))
            blue_palette.setColor(QPalette.ButtonText, Qt.white)
            blue_palette.setColor(QPalette.BrightText, Qt.red)
            blue_palette.setColor(QPalette.Link, QColor(42, 130, 218))
            blue_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
            blue_palette.setColor(QPalette.HighlightedText, Qt.black)

            appctxt.app.setPalette(blue_palette)
            #appctxt.app.setStyleSheet(
            #    "QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }")
            self.blueMode = True
        else:
            light_palette = QPalette()
            appctxt.app.setPalette(light_palette)
            self.blueMode = False

    def ToggleDarkMode(self, dark):

        if not dark:
            dark_palette = QPalette()

            dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
            dark_palette.setColor(QPalette.WindowText, Qt.white)
            dark_palette.setColor(QPalette.Base, QColor(25, 25, 25))
            dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
            dark_palette.setColor(QPalette.ToolTipBase, Qt.white)
            dark_palette.setColor(QPalette.ToolTipText, Qt.white)
            dark_palette.setColor(QPalette.Text, Qt.white)
            dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
            dark_palette.setColor(QPalette.ButtonText, Qt.white)
            dark_palette.setColor(QPalette.BrightText, Qt.red)
            dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
            dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
            dark_palette.setColor(QPalette.HighlightedText, Qt.black)

            appctxt.app.setPalette(dark_palette)
            #appctxt.app.setStyleSheet(
            #    "QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }")
            self.darkMode = True
        else:
            light_palette = QPalette()
            appctxt.app.setPalette(light_palette)
            self.darkMode = False

    # Currently only supports mp4
    def ImportSRT(self):
        fileName, _ = QFileDialog.getOpenFileName(self,
                                                  "Selecciona los mediose",
                                                  ".", "SRT Files (*.srt)")
        videoFilePath = (fileName.split(".")[0]) + ".mp4"
        print(videoFilePath)
        if fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(videoFilePath)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(videoFilePath)
            self.play()
            self.videoPath = videoFilePath
            self.videoName = self.videoPath.split("/")[-1]

            # Delete existing objects
            count = self.lyricCount
            for i in range(count):
                self.OnRemove()

            # Create video objects
            self.CreateLyricObjectsFromSRT(fileName)

    def CreateLyricObjectsFromSRT(self, path):
        srtFile = open(path, "r", encoding="utf-8")

        # General srt format is
        # index
        # start time --> end time
        # lyrics
        # empty line

        #--- Temp variables
        index = 1
        foundStart = False
        foundEnd = False
        foundLyrics = False
        lyricsString = ""
        subStringTime = "-->"
        startString = ""
        endString = ""
        # iterate through srt file
        for line in srtFile:
            # after times is lyrics
            if foundStart and foundEnd and not foundLyrics:
                # until we find empty
                if line == "\n":
                    foundLyrics = True

                if lyricsString != "":
                    lyricsString = lyricsString + line.strip('\n').rstrip()
                else:
                    lyricsString = line
            # times
            if subStringTime in line:
                startString = line.split(" --> ")[0].rstrip()
                endString = line.split(" --> ")[-1].rstrip()
                if startString != "":
                    foundStart = True
                else:
                    print("No start time for item", index)
                if endString != "":
                    foundEnd = True
                else:
                    print("No end time for item ", index)
            index = index + 1
            if foundLyrics and startString != "" and endString != "":
                #Create lyrics object here

                startQTime = self.ReturnQTimeObject(startString)
                endQtime = self.ReturnQTimeObject(endString)

                self.OnAdd(start=startQTime, end=endQtime, lyrics=lyricsString)
                lyricsString = ""
                foundLyrics = False
                foundStart = False
                foundEnd = False

        srtFile.close()

    def ReturnQTimeObject(self, timeString):
        hours = timeString.split(":")[0]
        minutes = timeString.split(":")[1]
        secondsAndMsec = timeString.split(":")[2]
        seconds = secondsAndMsec.split(",")[0]
        mSeconds = secondsAndMsec.split(",")[1]

        return QtCore.QTime(int(hours), int(minutes), int(seconds),
                            int(mSeconds))

    def TimeSkip(self, amount, forward):
        if forward:
            tempPosition = self.mediaPlayer.position()
            self.setPosition(tempPosition + int(amount * 1000))
        else:
            tempPosition = self.mediaPlayer.position()
            self.setPosition(tempPosition - int(amount * 1000))

    def SetCurrentTimeText(self, millis):
        millis = int(millis)
        seconds = (millis / 1000) % 60
        seconds = int(seconds)
        minutes = (millis / (1000 * 60)) % 60
        minutes = int(minutes)

        sMillis = self.ThreeCharSyntax(str(millis))
        sSeconds = self.TwoCharSyntax(str(seconds))
        sMinutes = self.TwoCharSyntax(str(minutes))

        self.currentTime.setText("Tiempo Actual " + sMinutes + ":" + sSeconds +
                                 ":" + sMillis)

    def open(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Selecciona los mediose", ".",
            "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")

        if fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(fileName)
            self.play()
            self.videoPath = fileName
            self.videoName = self.videoPath.split("/")[-1]

    def OpenVideoFile(self):
        #self.videoPath, _ = QFileDialog.getOpenFileName(self, 'Open File', options=QFileDialog.DontUseNativeDialog)

        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.videoPath, _ = QFileDialog.getOpenFileName(
            self,
            "Select Video File",
            "",
            "Video File (*.mp4 *.avi *.ogv)",
            options=options)
        self.videoName = self.videoPath.split("/")[-1]

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
            # Show exact time when paused
            self.SetCurrentTimeText(self.mediaPlayer.position())
            self.SetCurrentLyrics(self.mediaPlayer.position())
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)
        self.SetCurrentTimeText(self.mediaPlayer.position())
        self.SetCurrentLyrics(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())

    def OnRemove(self):
        if len(self.lyricList) > 0:
            self.verticalLayout.removeWidget(self.lyricList[-1])
            sip.delete(self.lyricList[-1])
            self.lyricCount -= 1
            del (self.lyricList[-1])
            self.progressBar.setProperty("value", 0)

    def OnAddButton(self):
        if self.lyricCount > 0:

            endTimeObject = self.lyricList[self.lyricCount - 1].findChild(
                QtWidgets.QTimeEdit, "endTime").time()
            newTime = QtCore.QTime(0, endTimeObject.minute(),
                                   endTimeObject.second(),
                                   endTimeObject.msec() + 1)
            self.OnAdd(start=newTime, end=newTime)
            self.scrollArea.ensureWidgetVisible(self.lyricGroup)
            max = self.scrollArea.verticalScrollBar().maximum()
            self.scrollArea.verticalScrollBar().setValue(999999)

        else:
            self.OnAdd()
            max = self.scrollArea.verticalScrollBar().maximum()
            self.scrollArea.verticalScrollBar().setValue(max)

    def OnAdd(self,
              start=QtCore.QTime(0, 0, 0),
              end=QtCore.QTime(0, 0, 0),
              lyrics=""):
        self.lyricGroup = QtWidgets.QWidget(self.scrollAreaWidgetContents)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.lyricGroup.sizePolicy().hasHeightForWidth())
        self.lyricGroup.setSizePolicy(sizePolicy)
        self.lyricGroup.setMinimumSize(QtCore.QSize(0, 150))
        self.lyricGroup.setMaximumSize(QtCore.QSize(600, 100))
        self.lyricGroup.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.lyricGroup.setObjectName("lyricGroup")

        self.gridLayout = QtWidgets.QGridLayout(self.lyricGroup)
        self.gridLayout.setObjectName("gridLayout")
        self.startLabel = QtWidgets.QLabel(self.lyricGroup)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.startLabel.setFont(font)
        self.startLabel.setObjectName("startLabel")
        self.startLabel.setText("Inicio:")
        self.gridLayout.addWidget(self.startLabel, 0, 0, 1, 1)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lyricsText = QtWidgets.QPlainTextEdit(self.lyricGroup)
        self.lyricsText.setObjectName("lyricsText")
        self.lyricsText.setFont(font)
        self.lyricsText.setPlainText(lyrics)
        self.gridLayout.addWidget(self.lyricsText, 0, 2, 2, 1)
        self.endLabel = QtWidgets.QLabel(self.lyricGroup)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.endLabel.setFont(font)
        self.endLabel.setObjectName("endLabel")
        self.endLabel.setText("Final:")
        self.gridLayout.addWidget(self.endLabel, 1, 0, 1, 1)

        self.endTime = QtWidgets.QTimeEdit(self.lyricGroup)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.endTime.sizePolicy().hasHeightForWidth())
        self.endTime.setSizePolicy(sizePolicy)
        self.endTime.setMinimumSize(QtCore.QSize(100, 30))
        self.endTime.setMaximumSize(QtCore.QSize(75, 16777215))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.endTime.setFont(font)
        self.endTime.setObjectName("endTime")
        self.endTime.setDisplayFormat("mm:ss:zzz")
        self.gridLayout.addWidget(self.endTime, 1, 1, 1, 1)
        self.endTime.setCurrentSectionIndex(0)
        self.endTime.setTime(end)

        self.startTime = QtWidgets.QTimeEdit(self.lyricGroup)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.startTime.sizePolicy().hasHeightForWidth())
        self.startTime.setSizePolicy(sizePolicy)
        self.startTime.setMinimumSize(QtCore.QSize(100, 30))
        self.startTime.setMaximumSize(QtCore.QSize(75, 16777215))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.startTime.setFont(font)
        self.startTime.setCurrentSection(QtWidgets.QDateTimeEdit.MSecSection)
        self.startTime.setCurrentSection(2)
        self.startTime.setCurrentSectionIndex(2)
        self.startTime.setTime(start)
        self.startTime.setObjectName("startTime")
        self.startTime.setDisplayFormat("mm:ss:zzz")
        #self.startTime.timeChanged.connect(lambda:self.IncreaseTime(self.endTime))

        self.gridLayout.addWidget(self.startTime, 0, 1, 1, 1)
        self.verticalLayout.addWidget(self.lyricGroup, 0, QtCore.Qt.AlignTop)

        # add to list
        self.lyricList.append(self.lyricGroup)
        self.lyricCount += 1
        self.progressBar.setProperty("value", 0)

    def IncreaseTime(self, endTime):
        if endTime.time().currentTime() <= self.startTime.time().currentTime():
            startTimeObject = self.startTime.time()
            newTime = QtCore.QTime(0, startTimeObject.minute(),
                                   startTimeObject.second(),
                                   startTimeObject.msec())
            endTime.setTime(newTime)

    def CreateSRT(self):
        # For progress bar
        self.progressCount = 1

        itemSelected = self.textAppendList.currentText()

        # Check to see if file has been open
        if self.videoPath:

            self.newVideoPath = self.videoPath.split(
                ".")[0] + " - NoTranslation" + ".srt"
            srtFile = open(self.newVideoPath, "w", encoding="utf-8")

            if self.translateEnglish.isChecked(
            ) and self.translateSpanish.isChecked():
                self.newVideoPath = self.videoPath.split(".")[0] + ".srt"
                srtFile = open(self.newVideoPath, "w", encoding="utf-8")
            elif self.translateEnglish.isChecked():
                self.newVideoPath = self.videoPath.split(
                    ".")[0] + " - English" + ".srt"
                srtFile = open(self.newVideoPath, "w", encoding="utf-8")
            elif self.translateSpanish.isChecked():
                self.newVideoPath = self.videoPath.split(
                    ".")[0] + " - Spanish" + ".srt"
                srtFile = open(self.newVideoPath, "w", encoding="utf-8")

            for i in range(len(self.lyricList)):
                # lyrics
                childLyricsText = self.lyricList[i].findChild(
                    QtWidgets.QPlainTextEdit, "lyricsText")

                # start Time
                ## Format: hh:mm:ss:zzz
                childStartTime = self.lyricList[i].findChild(
                    QtWidgets.QTimeEdit, "startTime").time()

                # end Time
                childEndTime = self.lyricList[i].findChild(
                    QtWidgets.QTimeEdit, "endTime").time()

                #print("Start time : " + str(childStartTime.minute()) + str(childStartTime.second()) + str(
                #    childStartTime.msec()))

                # Number of iteration
                srtFile.write(str(self.progressCount) + "\n")

                # start time
                minuteTime = self.TwoCharSyntax(str(childStartTime.minute()))
                secondTime = self.TwoCharSyntax(str(childStartTime.second()))
                mSecTime = self.ThreeCharSyntax(str(childStartTime.msec()))
                srtFile.write("00:" + minuteTime + ":" + secondTime + "," +
                              mSecTime + " --> ")

                # end time
                minuteTime = self.TwoCharSyntax(str(childEndTime.minute()))
                secondTime = self.TwoCharSyntax(str(childEndTime.second()))
                mSecTime = self.ThreeCharSyntax(str(childEndTime.msec()))
                srtFile.write("00:" + minuteTime + ":" + secondTime + "," +
                              mSecTime)

                # Lyrics

                if self.translateEnglish.isChecked(
                ) and self.translateSpanish.isChecked():
                    result = self.translator.translate(
                        childLyricsText.toPlainText(), lang_tgt='en')
                    srtFile.write("\n" + result.rstrip().replace("\n", " ") +
                                  "\n")
                    result = self.translator.translate(
                        childLyricsText.toPlainText(), lang_tgt='es')
                    srtFile.write(itemSelected +
                                  result.rstrip().replace("\n", " ") +
                                  itemSelected + "\n\n")
                elif self.translateEnglish.isChecked():
                    result = self.translator.translate(
                        childLyricsText.toPlainText(), lang_tgt='en')
                    srtFile.write("\n" + result.rstrip().replace("\n", " ") +
                                  "\n\n")
                elif self.translateSpanish.isChecked():
                    result = self.translator.translate(
                        childLyricsText.toPlainText(), lang_tgt='es')
                    srtFile.write("\n" + itemSelected +
                                  result.rstrip().replace("\n", " ") +
                                  itemSelected + "\n\n")
                else:
                    srtFile.write(
                        "\n" +
                        childLyricsText.toPlainText().replace("\n", " ") +
                        "\n\n")
                progress = self.progressCount / self.lyricCount
                print(int(progress * 100))
                self.progressBar.setProperty("value", int(progress * 100))
                self.progressCount += 1

                if progress == 1:
                    print(self.newVideoPath)
                    openPath = self.newVideoPath.replace('/', '\\')
                    subprocess.Popen(r'explorer /select,"' + openPath + '"')

        else:
            self.ShowPopUpMessage()

    # check if string is only 1 character
    def TwoCharSyntax(self, str):
        if len(str) != 2:
            return "0" + str
        else:
            return str

    #Make into 3 char
    def ThreeCharSyntax(self, str):
        if len(str) == 1:
            return "00" + str
        elif len(str) == 2:
            return "0" + str
        elif len(str) >= 4:
            return str[-3:]
        else:
            return str

    def SetCurrentLyrics(self, currentTime):

        showingLyrics = False
        for i in range(len(self.lyricList)):
            # start Time
            ## Format: hh:mm:ss:zzz
            childStartTime = self.lyricList[i].findChild(
                QtWidgets.QTimeEdit, "startTime").time()

            # convert to msecs
            minuteTime = childStartTime.minute()
            secondTime = childStartTime.second()
            mSecTime = childStartTime.msec()
            startTotal = (minuteTime * 60000) + (secondTime * 1000) + mSecTime

            # end Time
            childEndTime = self.lyricList[i].findChild(QtWidgets.QTimeEdit,
                                                       "endTime").time()

            # convert to msecs
            minuteTime = childEndTime.minute()
            secondTime = childEndTime.second()
            mSecTime = childEndTime.msec()
            endTotal = (minuteTime * 60000) + (secondTime * 1000) + mSecTime

            if currentTime >= startTotal and currentTime <= endTotal:
                childLyricsText = self.lyricList[i].findChild(
                    QtWidgets.QPlainTextEdit, "lyricsText")
                self.currentLyrics.setText(childLyricsText.toPlainText())
                showingLyrics = True
        if showingLyrics == False:
            self.currentLyrics.setText("")

    def ShowPopUpMessage(self):
        errorMsg = QMessageBox()
        errorMsg.setWindowTitle("Error")
        errorMsg.setText("Por favor selecciona un video primero")
        x = errorMsg.exec_()
コード例 #12
0
class VideoPlayer(QWidget):
    def __init__(self, filename, parent=None):
        super(VideoPlayer, self).__init__(parent)
        self.fileName = filename

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()

        self.playButton = QPushButton()
        self.playButton.setEnabled(True)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.setLayout(layout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")
        self.abrir()

    def abrir(self):

        if self.fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(self.fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(self.fileName)

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
コード例 #13
0
class GeneralMainDesign(QMainWindow):
    """General design of the main window"""
    def __init__(self, QWidgetParent=None):
        QMainWindow.__init__(self, QWidgetParent)
        self._set_main_window()
        self.centralwidget = QWidget(self)

        layout = QVBoxLayout(self.centralwidget)
        layout.setContentsMargins(0, 0, 2, 0)
        layout.setSpacing(0)

        # query frame
        self.frame_query = QueryFrame()
        self._set_frame()
        layout.addWidget(self.frame_query)

        self.setCentralWidget(self.centralwidget)

        # status bar
        self.statusbar = QStatusBar(self)
        self._set_status_bar()
        self.setStatusBar(self.statusbar)

        self.progress_bar = ProgressBar(self)
        self.statusbar.addPermanentWidget(self.progress_bar)
        self.progress_bar.setVisible(False)

        self.dw_top = DockWidget(460, 90, 20000, 50)
        self.dw_top.setTitleBarWidget(QWidget())
        self.dwc_top = DockWidgetContentsTop()
        self.dw_top.setWidget(self.dwc_top)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.dw_top)

        # dockwidget collection (left side)
        self.dw_collections = DockWidget(350, 620, 700, 20000)
        self.dw_collections.setTitleBarWidget(QWidget())
        self.dwc_left = DockWidgetContentsLeft(self)
        self.dw_collections.setWidget(self.dwc_left)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dw_collections)

        QtCore.QMetaObject.connectSlotsByName(self)

    def _set_main_window(self):
        """Sets the size policies of the main window"""
        self.resize(1000, 750)
        size_policy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QtCore.QSize(1000, 750))

        # main window icon
        self.setWindowIcon(QIcon(DUNYA_ICON))
        self.setWindowTitle('Dunya Desktop')

    def _set_frame(self):
        self.frame_query.setFrameShape(QFrame.StyledPanel)
        self.frame_query.setFrameShadow(QFrame.Raised)

    def _set_status_bar(self):
        self.statusbar.setMinimumSize(QtCore.QSize(0, 18))
        font = QFont()
        font.setPointSize(9)
        self.statusbar.setFont(font)
コード例 #14
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setObjectName("myGitClone")
        root = QFileInfo.path(QFileInfo(QCoreApplication.arguments()[0]))
        print("root", root)
        self.icon = QIcon(f"{root}/favicon.ico")
        self.setWindowIcon(self.icon)
        self.setGeometry(0, 0, 800, 600)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setMinimumSize(400, 300)
        self.setDocumentMode(True)
        self.settings = QSettings('Axel Schneider', self.objectName())
        self.createStatusbar()
        self.createActions()
        self.createWidgets()
        QMetaObject.connectSlotsByName(self)
        self.readSettings()
        self.statusbar.showMessage("Ready")
        self.setWindowTitle("myGitClone")

        ### process
        ### shell settings
        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)
        self.process.readyReadStandardError.connect(lambda: self.msg("Error"))
        self.process.started.connect(lambda: self.msg("starting shell"))
        self.process.finished.connect(lambda: self.msg("shell ended"))

    ### widgets ###
    def createWidgets(self):
        self.username = ""
        self.url = "https://github.com/%s?tab=repositories" % self.username
        self.repoList = []
        self.gitList = []
        self.dlFolder = QDir.homePath() + "/Downloads"

        ### table ###
        self.lb = QTableWidget()
        self.lb.setColumnCount(2)
        self.lb.setColumnWidth(0, 60)
        self.lb.horizontalHeader().setStretchLastSection(True)
        self.lb.setHorizontalHeaderItem(0, QTableWidgetItem("Select"))
        self.lb.setHorizontalHeaderItem(1, QTableWidgetItem("Repository Name"))

        ### username field ###
        self.uname = QLineEdit("")
        self.uname.setFixedWidth(180)
        self.uname.setPlaceholderText("insert user name")
        self.uname.returnPressed.connect(self.listRepos)

        ### get repos button ###
        self.uBtn = QPushButton(QIcon(self.icon), "get Repos List")
        self.uBtn.setToolTip("get all repos from user")
        self.uBtn.clicked.connect(self.listRepos)

        ### get repos button ###
        self.dlBtn = QPushButton(QIcon.fromTheme("download"),
                                 "download selected Repos")
        self.dlBtn.setToolTip("download selected repos from user")
        self.dlBtn.setFixedWidth(180)
        self.dlBtn.clicked.connect(self.create_dl_list)

        ### Layout
        self.ubox = QHBoxLayout()
        self.ubox.addWidget(self.uname)
        self.ubox.addWidget(self.uBtn)
        self.ubox.addStretch(1)
        self.ubox.addWidget(self.dlBtn)

        self.layout = QVBoxLayout()
        self.wid = QWidget()

        self.layout.addLayout(self.ubox)
        self.layout.addWidget(self.lb)
        self.wid.setLayout(self.layout)

        self.setCentralWidget(self.wid)

    ### actions ###
    def createActions(self):
        self.tbar = QToolBar()
        self.tbar.setIconSize(QSize(16, 16))
        self.tbar.setMovable(False)
        self.tbar.setToolButtonStyle(0)
        self.tbar.setContextMenuPolicy(Qt.PreventContextMenu)
        self.tbar.setObjectName("tbar")
        self.addToolBar(self.tbar)

        self.actionSettings = QAction(self,
                                      triggered=self.appSettings,
                                      toolTip="set output directory")
        icon = QIcon.fromTheme("preferences-system")
        self.actionSettings.setIcon(icon)
        self.actionSettings.setObjectName("actionSettings")

        self.actionAbout = QAction(self, triggered=self.aboutApp)
        icon = QIcon.fromTheme("help-about")
        self.actionAbout.setIcon(icon)

        self.tbar.addAction(self.actionSettings)
        self.tbar.addAction(self.actionAbout)

        ### statusbar###
    def createStatusbar(self):
        self.statusbar = QStatusBar(self)
        font = QFont()
        font.setPointSize(7)
        self.statusbar.setFont(font)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

    ### get username from textfield
    def changeUsername(self):
        self.username = self.uname.text()
        self.url = "https://github.com/%s?tab=repositories" % self.username

    ### get user repos ##
    def listRepos(self):
        self.changeUsername()
        if self.username == "":
            self.msgBox("please type a username")
        else:
            self.lb.setRowCount(0)
            self.repoList = []
            repositories = self.get_repositories()
            print("%s %s" % ("get repos from", self.username))
            self.repoList = list(repositories)
            self.fillTable()
            self.msg("repos loaded")

    ### fill table with user repos
    def fillTable(self):
        self.lb.setRowCount(len(self.repoList))
        if self.lb.rowCount() > 0:
            for x in range(len(self.repoList)):
                rep = QTableWidgetItem(self.repoList[x])
                checkbox = QCheckBox(self.lb)
                checkbox.setStyleSheet("margin-left:20%; margin-right:10%;")
                checkbox.setCheckState(0)
                self.lb.setCellWidget(x, 0, checkbox)
                self.lb.setItem(x, 1, rep)

    ### table context menu
    def contextMenuEvent(self, event):
        self.menu = QMenu(self)
        if self.lb.selectionModel().hasSelection():
            # copy
            downloadAction = QAction(QIcon.fromTheme("download"),
                                     'download Repo', self)
            downloadAction.triggered.connect(
                lambda: self.downloadRepoFromList())
            ###
            self.menu.addAction(downloadAction)
            self.menu.popup(QCursor.pos())

    def listChanged(self):
        self.create_dl_list()

    ### get download list from selected repos
    def create_dl_list(self):
        r = ""
        self.gitList = []
        for x in range(self.lb.rowCount()):
            if self.lb.cellWidget(x, 0).checkState() == 2:
                r = self.lb.item(x, 1).text()
                self.gitList.append(r)
                print("%s %s" % (r, "is selected"))
                self.downloadRepo(r)

    ### download repo
    def downloadRepo(self, gitrepo):
        merror = ""
        cmd = "git clone --progress --verbose https://github.com/" + str(
            self.username) + "/" + str(gitrepo) + " " + str(
                self.dlFolder) + "/" + str(gitrepo)
        print("%s %s" % ("username is:", self.username))
        print(cmd)
        try:
            self.process.execute(cmd)
        except Exception as e:
            s = str(e)
            self.errorBox(s)

    ### download selected repo (context menu)
    def downloadRepoFromList(self):
        row = self.lb.selectionModel().selectedIndexes()[0].row()
        gitrepo = self.lb.item(row, 1).text()
        cmd = "git clone --progress --verbose https://github.com/" + str(
            self.username) + "/" + str(gitrepo) + " " + str(
                self.dlFolder) + "/" + str(gitrepo)
        print(cmd)
        self.process.execute(cmd)

    ### preferences
    def appSettings(self):
        if self.dlFolder == "":
            self.dlFolder = QDir.homePath()
        self.msg("settings called")
        path = QFileDialog.getExistingDirectory(self, "select Folder",
                                                self.dlFolder)
        if path:
            self.dlFolder = path
            print("%s %s" % ("download folder changed to", self.dlFolder))

    def closeEvent(self, e):
        self.writeSettings()
        e.accept()

    ### read settings from config file
    def readSettings(self):
        print("reading settings")
        if self.settings.contains('geometry'):
            self.setGeometry(self.settings.value('geometry'))
        if self.settings.contains('downloadFolder'):
            self.dlFolder = self.settings.value('downloadFolder')
            self.msg(self.dlFolder)
            print("%s %s" % ("download folder:", self.dlFolder))

    ### write settings to config file
    def writeSettings(self):
        print("writing settings")
        self.settings.setValue('geometry', self.geometry())
        self.settings.setValue('downloadFolder', self.dlFolder)

    ### about window
    def aboutApp(self):
        title = "about myGitClone"
        message = """
                    <span style='color: #3465a4; font-size: 18pt;font-weight: bold;'
                    >myGitClone</strong></span></p>
                    <h3>based on <a title='git_clones' href='https://github.com/rootVIII/git_clones' target='_blank'> git_clones</a> by James</h3>
                    <h4>created by  <a title='Axel Schneider' href='http://goodoldsongs.jimdo.com' target='_blank'>Axel Schneider</a> with PyQt5</h3>
                    <br>
                    <span style='color: #555753; font-size: 9pt;'>©2019 Axel Schneider, James</strong></span></p>
                        """
        self.infobox(title, message)

    ### error messagebox
    def errorBox(self, message):
        mwin = QMessageBox.warning(self, "Error", message)

    ### messagebox
    def infobox(self, title, message):
        QMessageBox.about(self, title, message).show()

    ### set statusbar text
    def msg(self, message):
        self.statusbar.showMessage(message)

    def msgBox(self, message):
        msg = QMessageBox.warning(self, "Information", message)

    ### begin from git_clones ###
    def http_get(self):
        if version_info[0] != 2:
            req = urlopen(self.url)
            return req.read().decode('utf-8')
        req = Request(self.url)
        request = urlopen(req)
        return request.read()

    def get_repo_data(self):
        try:
            response = self.http_get()
        except Exception as e:
            s = str(e)
            self.errorBox(s)
            print("Unable to make request to %s's Github page" % self.username)
            exit(1)
        else:
            pattern = r"<a\s?href\W+%s/(.*)\"\s+" % self.username
            for line in findall(pattern, response):
                yield line.split('\"')[0]

    def get_repositories(self):
        return set([repo for repo in self.get_repo_data()])
コード例 #15
0
class ImagePlayer(QWidget):
    def __init__(self, img_path, parent=None):
        super(ImagePlayer, self).__init__(parent)
        if __name__ == '__main__':
            self.setWindowTitle("Viewer")
            self.setGeometry(0, 0, 640, 480)
            self.main = QWidget()
        else:
            self.setGeometry(0, 0, parent.width(), parent.height())
            self.main = parent

        self.vue = QGraphicsView()
        self.vue.setDragMode(QGraphicsView.ScrollHandDrag)
        self.vue.wheelEvent = self.wheel_event

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.addWidget(self.vue)
        self.verticalLayout.addWidget(self.statusBar)

        self.setPixmapView(img_path)

        self.statusBar.showMessage(img_path)

        if __name__ == '__main__':
            self.image_btn = QToolButton()
            self.image_btn.setText("Image")
            self.image_btn.setObjectName("image_btn")
            self.image_btn.clicked.connect(self.get_image)
            self.verticalLayout.addWidget(self.image_btn)

            self.setLayout(self.verticalLayout)
            self.show()
        else:
            self.main.setLayout(self.verticalLayout)

    def get_image(self):
        img, _p = QFileDialog.getOpenFileName(
            self, "Ouvrir un fichier", QDir.homePath(),
            "All Files *.* ;; PNG *.png ;; JPG *.jpg ;; BMP *.bmp")
        if not img:
            with open("img.txt", "w") as file:
                file.write("not img")
            return
        self.setPixmapView(img)

    def setPixmapView(self, img_path):
        self.current_image = ImageQt(img_path)
        w, h = self.size().width(), self.size().height()
        self.pixmap = QPixmap.fromImage(
            self.current_image.scaled(w, h, Qt.KeepAspectRatio,
                                      Qt.FastTransformation))
        self.view_current()
        self.statusBar.showMessage(img_path)

    def view_current(self):
        w_pix, h_pix = self.pixmap.width(), self.pixmap.height()
        self.scene = QGraphicsScene()
        self.scene.setSceneRect(0, 0, w_pix, h_pix)
        self.scene.addPixmap(self.pixmap)
        self.vue.setScene(self.scene)

    def wheel_event(self, event):
        steps = event.angleDelta().y() / 120.0
        self.zoom(steps)
        event.accept()

    def zoom(self, step):
        w_pix, h_pix = self.pixmap.width(), self.pixmap.height()
        w, h = w_pix * (1 + 0.1 * step), h_pix * (1 + 0.1 * step)
        self.pixmap = QPixmap.fromImage(
            self.current_image.scaled(w, h, Qt.KeepAspectRatio,
                                      Qt.FastTransformation))
        self.view_current()
コード例 #16
0
class Player(QWidget):
    """Sub-class of QWidget"""
    def __init__(self, parent=None, *args, **kwargs):
        """Initialize class attributes"""
        super(Player, self).__init__(parent, *args, **kwargs)
        self.init_ui()

    def init_ui(self):
        """Create local components"""
        # loop
        self.loop = False
        # time label text
        self.time_text = '{:0>2d}:{:0>2d}:{:0>2d}/{:0>2d}:{:0>2d}:{:0>2d}'
        self.hours = self.minutes = self.seconds = 0
        # create media player object
        self.mediaPlayer = QMediaPlayer(self, QMediaPlayer.VideoSurface)
        # create videowidget object
        self.videoWidget = QVideoWidget()

        # create open button
        self.btn_size = QSize(16, 16)
        openButton = Button("Open")
        openButton.setToolTip("Open Media File")
        openButton.setStatusTip("Open Media File")
        openButton.setFixedHeight(24)
        openButton.setIconSize(self.btn_size)
        openButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("Icons/Open.bmp")))
        # openButton.setStyleSheet("background-color: #B0C4DE")
        openButton.clicked.connect(self.abrir)

        # create play button
        self.playButton = Button()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(self.btn_size)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        # self.playButton.setStyleSheet("background-color: #B0C4DE")
        self.playButton.clicked.connect(self.play)

        # create slider
        self.positionSlider = PositionSlider(self.mediaPlayer, Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.setObjectName("positionSlider")

        # create status bar
        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto sans", 8))
        self.statusBar.setFixedHeight(14)
        self.statusBar.setStyleSheet('color:#ffffff')

        # create duration time label
        self.durationLabel = QLabel()
        self.durationLabel.setStyleSheet(
            'background-color:rgba(255, 255, 255, 0)')
        self.durationLabel.setText('00:00:00/00:00:00')

        # create hbox layout
        controlLayoutWidget = QWidget(self)
        controlLayout = QHBoxLayout(controlLayoutWidget)
        controlLayoutWidget.setLayout(controlLayout)
        controlLayout.setContentsMargins(2, 2, 2, 2)
        # set widgets to the hbox layout
        controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.durationLabel)
        # change hbox color
        controlLayoutWidget.setStyleSheet(
            'background-color:rgba(255, 255, 255, 50)')
        controlLayoutWidget.setWindowOpacity(0.1)

        # create vbox layout
        self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        # set widgets to vbox layout
        self.layout.addWidget(self.videoWidget)
        self.layout.addWidget(controlLayoutWidget)
        self.sub_controls()
        self.layout.addWidget(self.statusBar)

        self.setLayout(self.layout)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage('{:->33s}{:-<33s}'.format("Have Fun", ""))
        self.key_bindings()

    def key_bindings(self):
        # bind Keys to methods
        self.onplaypause = self.create_shortcut(Qt.Key_Space, self.videoWidget,
                                                self.play)  # Space key for

        self.on_fscreen = self.create_shortcut(
            Qt.Key_F, self.videoWidget,
            self.toggle_fullscreen)  # F key for fullscreen on

        self.onforward = self.create_shortcut(
            Qt.Key_Right, self.videoWidget,
            self.forward)  # Right key for forward

        self.redvolume = self.create_shortcut(
            Qt.Key_Down, self.videoWidget,
            self.red_volume)  # Down key reduce volume

        self.incvolume = self.create_shortcut(
            Qt.Key_Up, self.videoWidget,
            self.inc_volume)  # Up key increase volume

        self.onsetloop = self.create_shortcut(
            "L",
            self.videoWidget,  # L key for repeat on,
            (lambda self=self: self.repeat.toggle() or self.play_again()))

        self.onrewind = self.create_shortcut(
            Qt.Key_Left, self.videoWidget, self.rewind)  # Left key for rewind

        self.volmute = self.create_shortcut(Qt.Key_M, self.videoWidget,
                                            self.mute)  # M for mute and unmute

        self.onopen = self.create_shortcut('Ctrl+O', self.videoWidget,
                                           self.abrir)  # Ctrl+O for open

        self.onstop = self.create_shortcut(Qt.Key_S, self.videoWidget,
                                           self.stop_media)  # S key for stop

    def create_shortcut(self, sequence, widget, obj):
        """generate key shortcuts"""
        return QShortcut(QKeySequence(sequence),
                         widget,
                         obj,
                         context=Qt.ApplicationShortcut)

    def sub_controls(self):
        """Repeat, volume, and mute controls"""
        # repeat button
        self.repeat = Button()
        self.repeat.setCheckable(True)
        self.repeat.toggle()
        self.repeat.setIconSize(self.btn_size)
        self.repeat.setFixedHeight(24)
        self.repeat.setFixedWidth(26)
        self.repeat.setToolTip("repeat")
        self.repeat.setStatusTip("repeat")

        # Icons to correspond with button state
        icon = QIcon()
        icon.addPixmap(QPixmap(os.path.join(FOLDER, "Icons/repeat(1).png")),
                       QIcon.Normal, QIcon.On)
        icon.addPixmap(QPixmap(os.path.join(FOLDER, "Icons/repeat(2).png")),
                       QIcon.Active)
        self.repeat.setIcon(icon)
        # self.repeat.setStyleSheet("background-color: #B0C4DE; margin: 0px 0px 0px 2px;")
        self.repeat.clicked.connect(self.play_again)

        # stop button
        self.stop = Button()
        self.stop.setIconSize(self.btn_size)
        self.stop.setFixedHeight(24)
        self.stop.setFixedWidth(26)
        self.stop.setToolTip("Stop playing media")
        self.stop.setStatusTip("Stop playing media")
        self.stop.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        # self.stop.setStyleSheet("background-color: #B0C4DE; margin: 0px 0px 0px 2px;")
        self.stop.clicked.connect(self.stop_media)

        # volume slider
        self.volumeSlider = VolumeSlider(self.mediaPlayer, Qt.Horizontal)
        self.volumeSlider.setRange(0, 100)
        self.volumeSlider.setFixedWidth(200)
        self.mediaPlayer.setVolume(50)
        self.volumeSlider.sliderMoved.connect(self.set_volume)

        # volume button
        self.volume = Button(self)
        self.volume.setIconSize(self.btn_size)
        self.volume.setFixedHeight(24)
        self.volume.setFixedWidth(26)
        self.volume.setToolTip("Mute or Unmute")
        self.volume.setStatusTip("Mute or Unmute")
        self.volume.setIcon(self.style().standardIcon(QStyle.SP_MediaVolume))
        # self.volume.setStyleSheet("background-color: #B0C4DE; margin: 0px 0px 0px 2px;")
        self.volume.clicked.connect(self.mute)

        # create control widget
        subControlWidget = QWidget(self)
        subControlWidget.setStyleSheet(
            'background-color:rgba(255, 255, 255, 30)')
        # create Horizontal Layout
        subControlLayout = QHBoxLayout(subControlWidget)
        subControlLayout.setContentsMargins(0, 0, 0, 0)
        subControlLayout.addWidget(self.repeat, 0, Qt.AlignLeft)
        subControlLayout.addWidget(self.stop, 1, Qt.AlignLeft)
        # sub layout for volume control
        self.sub_layout = QHBoxLayout()
        self.sub_layout.addWidget(self.volume)
        self.sub_layout.addWidget(self.volumeSlider)
        subControlLayout.addLayout(self.sub_layout)
        subControlLayout.setContentsMargins(2, 2, 2, 2)

        self.layout.addWidget(subControlWidget)

    def abrir(self, event=None, url=None):
        """" Equivalent to open for most GUIs"""
        fileName = None
        if self.videoWidget.isFullScreen():
            self.toggle_fullscreen()
        if not url:
            fileName, _ = QFileDialog.getOpenFileName(self, "Select media")
            if fileName:
                self.mediaPlayer.setMedia(
                    QMediaContent(QUrl.fromLocalFile(fileName)))
        else:
            self.mediaPlayer.setMedia(QMediaContent(QUrl(url)))
        if url or fileName:
            self.volumeSlider.setValue(self.mediaPlayer.volume())
            self.playButton.setEnabled(True)
            self.statusBar.showMessage((fileName or url))
            if not self.loop:
                self.play()

    def play(self):
        """Start media player"""
        if self.playButton.isEnabled():
            if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
                self.mediaPlayer.pause()
            else:
                self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        """Callback for media player state change"""
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))
        if state == QMediaPlayer.StoppedState and self.loop:
            self.play()

    def positionChanged(self, position):
        """Callback for media player position change"""
        if self.mediaPlayer.state() == QMediaPlayer.StoppedState:
            position = 0
        self.positionSlider.setValue(position)
        hours, position = position // 3600000, position % 3600000
        minutes, position = position // 60000, position % 60000
        seconds = position // 1000
        self.durationLabel.setText(
            self.time_text.format(hours, minutes, seconds, self.hours,
                                  self.minutes, self.seconds))

    def durationChanged(self, duration):
        """Callback for media player duration of media change"""
        self.positionSlider.setRange(0, duration)
        self.hours, duration = duration // 3600000, duration % 3600000
        self.minutes, duration = duration // 60000, duration % 60000
        self.seconds = duration // 1000
        self.durationLabel.setText(
            self.time_text.format(0, 0, 0, self.hours, self.minutes,
                                  self.seconds))

    def setPosition(self, position):
        """set media player play position"""
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        """Callback for multiplayer errors"""
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())

    def play_again(self):
        """Set repeat on or off"""
        self.loop = not self.loop

    def stop_media(self):
        """Callback for stop button"""
        if self.loop:
            self.loop = False
            self.repeat.toggle()
        self.mediaPlayer.stop()

    def toggle_fullscreen(self):
        """Toggle in or out of fullscreen mode"""
        self.videoWidget.setWindowFlags(Qt.FramelessWindowHint
                                        | Qt.WindowStaysOnTopHint)
        if self.videoWidget.isFullScreen():
            self.videoWidget.setFullScreen(False)
            self.videoWidget.setWindowState(Qt.WindowNoState)
            self.videoWidget.setParent(self)
            self.layout.insertWidget(0, self.videoWidget)
            self.videoWidget.showNormal()
            self.show()
        else:
            self.videoWidget.setFullScreen(True)
            self.hide()

    def rewind(self, lapse=2500):
        """Rewind the current media file by 1 second"""
        new_position = self.mediaPlayer.position() - lapse
        self.setPosition(new_position)

    def forward(self, lapse=2500):
        """Forward media file by 1 second"""
        new_position = self.mediaPlayer.position() + lapse
        self.setPosition(new_position)

    def set_volume(self, vol=0):
        """Set media player volume volume"""
        if vol:
            self.mediaPlayer.setVolume(vol)

    def red_volume(self, vol=1):
        """Reduce volume by a factor of 0.01"""
        volume = self.mediaPlayer.volume()
        if volume >= 0:
            new_volume = volume - 1
            self.volumeSlider.setValue(new_volume)
            self.set_volume(new_volume)

    def inc_volume(self, vol=1):
        """Increase volume by a factor of 0.01"""
        volume = self.mediaPlayer.volume()
        if self.mediaPlayer.isMuted():
            self.mediaPlayer.setMuted(False)
            self.volume.setIcon(self.style().standardIcon(
                QStyle.SP_MediaVolume))
        if volume <= 100:
            new_volume = volume + 1
            self.volumeSlider.setValue(new_volume)
            self.set_volume(new_volume)

    def mute(self):
        """Mute media player"""
        if self.mediaPlayer.isMuted():
            self.mediaPlayer.setMuted(False)
            self.volume.setIcon(self.style().standardIcon(
                QStyle.SP_MediaVolume))
        else:
            self.mediaPlayer.setMuted(True)
            self.volume.setIcon(self.style().standardIcon(
                QStyle.SP_MediaVolumeMuted))
コード例 #17
0
class StatusbarUI(object):
    def __init__(self, main_window: QMainWindow):
        """
        状态栏
        外观模式
        :param main_window:
        """
        self.main_window = main_window

        self.statusbar = QStatusBar(self.main_window)

        self.ui_list = []
        self.show_time = ShowTime(self.statusbar, 1)  # 时间模块
        self.placeholder = Placeholder(self.statusbar, 2)  # 占位符
        self.net_speed = NetSpeed(self.statusbar, -4)  # 网速
        self.monitor_port = MonitorPort(self.statusbar, -3)  # 监听端口
        self.online_host = OnlineHost(self.statusbar, -1)  # 上线主机

    def options(self) -> None:
        font = QFont()
        font.setPointSize(10)
        self.statusbar.setFont(font)

        # self.statusbar.setGeometry(QtCore.QRect(0, 0, 900, 50))
        self.statusbar.setFixedHeight(30)
        self.main_window.setStatusBar(self.statusbar)
        # self.main_window.setStatusBar()
        # self.statusbar.setContextMenuPolicy(Qt.DefaultContextMenu)

    def setup_ui(self) -> None:
        self.statusbar.setObjectName("statusbar")
        self.options()

        self.load_ui()
        self.show_ui()

        if not settings.STATUSBAR_SHOW:
            self.statusbar.setHidden(False)

    # noinspection PyArgumentList
    def retranslate_ui(self) -> None:
        self.statusbar.setWindowTitle(_translate("StatusbarUI", "状态栏"))

    def load_ui(self) -> None:
        """
        加载模块
        :return:
        """
        self.ui_list.append(self.show_time)
        self.ui_list.append(self.placeholder)
        self.ui_list.append(self.net_speed)
        self.ui_list.append(self.monitor_port)
        self.ui_list.append(self.online_host)

    def show_ui(self) -> None:
        """
        显示数据
        :return:
        """
        for view in self.ui_list:
            view.setup_ui()
            view.retranslate_ui()
コード例 #18
0
class VideoPlayer(QWidget):
    def __init__(self, img_path, parent=None):
        super(VideoPlayer, self).__init__(parent)
        if __name__ == '__main__':
            self.setWindowTitle("Player")
            self.setGeometry(0, 0, 640, 480)
        else:
            self.setGeometry(0, 0, parent.width(), parent.height())
            self.main = parent

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()

        if __name__ == '__main__':
            openButton = QPushButton()
            openButton.setToolTip("Open Video File")
            openButton.setStatusTip("Open Video File")
            openButton.setFixedHeight(24)
            openButton.setIconSize(btnSize)
            openButton.setText("Vidéo")
            openButton.setFont(QFont("Noto Sans", 8))
            openButton.setIcon(QIcon.fromTheme("document-open"))
            openButton.clicked.connect(self.openFile)

        self.playButton = QPushButton()
        self.playButton.setEnabled(True)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        if __name__ == '__main__':
            controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")

        self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(img_path)))
        self.statusBar.showMessage(img_path)

        if __name__ == '__main__':
            self.setLayout(layout)
            self.show()
        else:
            self.main.setLayout(layout)

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Open Movie",
            QDir.homePath() + "/Videos",
            "All Files *.* ;; MP4 *.mp4 ;; FLV *.flv ;; TS *.ts ;; MTS *.mts ;; AVI *.avi"
        )

        if fileName != '':
            self.loadFile(fileName)

    def loadFile(self, fileName):
        self.mediaPlayer.setMedia(cv2.VideoCapture(fileName))
        #        self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
        self.playButton.setEnabled(True)
        self.statusBar.showMessage(fileName)
        self.play()

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
コード例 #19
0
class VideoPlayer(QWidget):
    def __init__(self, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        #self.mediaPlayer.setMinmumSize(QtCore.QSize(445, 225))

        btnSize = QSize(16, 16)
        videoWidget = QVideoWidget()
        videoWidget.setMinimumSize(QtCore.QSize(445, 225))

        openButton = QPushButton("Open Video")
        openButton.setToolTip("Open Video File")
        openButton.setStatusTip("Open Video File")
        openButton.setFixedHeight(24)
        openButton.setIconSize(btnSize)
        openButton.setFont(QFont("Noto Sans", 8))
        openButton.setIcon(
            QIcon.fromTheme("document-open", QIcon("D:/_Qt/img/open.png")))
        openButton.clicked.connect(self.abrir)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedHeight(24)
        self.playButton.setIconSize(btnSize)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont("Noto Sans", 7))
        self.statusBar.setFixedHeight(14)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        #controlLayout.addWidget(openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        #layout.setMinmumSize(QtCore.QSize(445, 225))
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.statusBar)

        self.setLayout(layout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)
        self.statusBar.showMessage("Ready")

    def abrir(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Selecciona los mediose", ".",
            "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")

        if fileName != '':
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.statusBar.showMessage(fileName)
            self.play()

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.statusBar.showMessage("Error: " + self.mediaPlayer.errorString())
コード例 #20
0
class Config(QWidget):
    def __init__(self):
        super(Config, self).__init__()
        config_group = QtWidgets.QGroupBox(u"参数配置")
        lineconfig_group = QtWidgets.QGroupBox(u"线条风格配置")
        axisconfig_group = QtWidgets.QGroupBox(u"坐标轴风格配置")
        lineshow_group = QtWidgets.QGroupBox(u"线条风格预览")
        result_group = QtWidgets.QGroupBox(u"结果展示")

        # 当前绘图结果
        self.fig = None

        # 当前绘图总数据保存
        # 坐标轴信息
        self.min_x = 0.
        self.max_x = 1.
        self.min_y = 0.
        self.max_y = 1.
        self.x_text = u'The number of retrived samples'
        self.y_text = u'precision @ 256 bins'
        self.x_tick_list = [0., 0.5, 1.]
        self.x_label_list = ['0', '0.5', '1.0']
        self.y_tick_list = [0., 0.5, 1.]
        self.y_label_list = ['0', '0.5', '1.0']
        # 已有曲线信息
        self.formula_list = []
        self.ls_list = []
        self.lc_list = []
        self.lt_list = []
        self.mark_list = []
        self.mark_density_list = []

        # 当前绘图曲线元数据保存
        self.ls = '-'
        self.mark = 'o'
        self.formula = 'y=x**2'
        self.lc = '#00ff00'
        self.lt = 'Our Method'
        self.md = 5

        # 状态栏
        self.statusBar = QStatusBar()
        self.statusBar.setFont(QFont(u'华文楷体', 10))
        self.statusBar.showMessage(u"准备就绪")

        # 编辑公式
        self.math = QLineEdit()
        self.math.setPlaceholderText(u'y=x**2')
        self.math.setClearButtonEnabled(True)

        # 线条风格
        self.linestyle = QComboBox()
        self.line_list = ["-", "--", "-.", ":"]
        for each in self.line_list:
            self.linestyle.addItem(each)

        # 标记风格
        self.markerstyle = QComboBox()
        self.marker_list = [
            ".", ",", "o", "v", "^", "<", ">", "1", "2", "3", "4"
            "s", "p", "*", "h", "H", "+", "x", "D", "d", "|", "_"
        ]
        for each in self.marker_list:
            self.markerstyle.addItem(each)

        # 设置线条标签名称
        self.label = QLineEdit()
        self.label.setPlaceholderText(u'Our Method')
        self.label.setClearButtonEnabled(True)

        # 设置线条颜色
        self.lineColor = QPushButton('更改线条颜色')
        self.lineColor.setToolTip("点击此按钮将更改线条颜色!")
        self.lineColor.setStatusTip("点击此按钮将更改线条颜色!")
        self.lineColor.clicked.connect(self.changeColor)
        self.lineColor.resize(self.lineColor.sizeHint())
        self.lineColor.installEventFilter(self)

        # 设置标记密集程度
        self.markDensity = QSlider(Qt.Horizontal)
        self.markDensity.setMinimum(1)
        self.markDensity.setMaximum(50)
        self.markDensity.setValue(5)
        self.markDensity.installEventFilter(self)

        # 横坐标轴范围
        self.x_scale = QLineEdit()
        self.x_scale.setPlaceholderText(u'0,1')
        self.x_scale.setClearButtonEnabled(True)

        # 纵坐标轴范围
        self.y_scale = QLineEdit()
        self.y_scale.setPlaceholderText(u'0,1')
        self.y_scale.setClearButtonEnabled(True)

        # 横坐标轴标签名称
        self.x_label = QLineEdit()
        self.x_label.setPlaceholderText(u'The number of retrived samples')
        self.x_label.setClearButtonEnabled(True)

        # 纵坐标轴标签名称
        self.y_label = QLineEdit()
        self.y_label.setPlaceholderText(u'precision @ 256 bins')
        self.y_label.setClearButtonEnabled(True)

        # 横坐标刻度数量
        self.x_ticks = QLineEdit()
        self.x_ticks.setPlaceholderText(u'100')
        self.x_ticks.setClearButtonEnabled(True)

        # 纵坐标刻度数量
        self.y_ticks = QLineEdit()
        self.y_ticks.setPlaceholderText(u'100')
        self.y_ticks.setClearButtonEnabled(True)

        # 线条风格预览按钮
        self.lineview = QPushButton(u'预览')
        self.lineview.setToolTip("线条预览!")
        self.lineview.setStatusTip("线条预览!")
        self.lineview.clicked.connect(self.showLine)
        self.lineview.installEventFilter(self)

        # 布局设置
        main_layout = QVBoxLayout()

        # 参数外层布局
        config_outer_layout = QVBoxLayout()

        # 参数内层布局配置
        config_inner_layout = QHBoxLayout()
        config_inner_layout.addWidget(lineconfig_group)
        config_inner_layout.setStretchFactor(lineconfig_group, 1)
        config_inner_layout.addWidget(axisconfig_group)
        config_inner_layout.setStretchFactor(axisconfig_group, 1)
        config_inner_layout.addWidget(lineshow_group)
        config_inner_layout.setStretchFactor(lineshow_group, 1)

        # 线条布局
        line_layout = QFormLayout()
        line_layout.addRow(u'编辑公式', self.math)
        line_layout.addRow(u'线条风格', self.linestyle)
        line_layout.addRow(u'标记风格', self.markerstyle)
        line_layout.addRow(u'标签名称', self.label)
        line_layout.addRow(u'颜色配置', self.lineColor)
        line_layout.addRow(u'标记密度', self.markDensity)
        lineconfig_group.setLayout(line_layout)

        # 坐标轴布局
        tick_layout = QFormLayout()
        tick_layout.addRow(u'横坐标轴范围', self.x_scale)
        tick_layout.addRow(u'纵坐标轴范围', self.y_scale)
        tick_layout.addRow(u'横坐标轴标签名称', self.x_label)
        tick_layout.addRow(u'纵坐标轴标签名称', self.y_label)
        tick_layout.addRow(u'横坐标刻度数量', self.x_ticks)
        tick_layout.addRow(u'纵坐标刻度数量', self.y_ticks)
        axisconfig_group.setLayout(tick_layout)

        # 预览布局
        view = QVBoxLayout()

        # 预览显示
        self.view_face = QMainWindow()
        view.addWidget(self.view_face)
        # 预览按钮
        view.addWidget(self.lineview)
        lineshow_group.setLayout(view)

        # 中层按钮定义
        # 按钮一:显示最终结果
        # 按钮二:添加新的线条
        # 按钮三:删除最近一条线条
        # 按钮四:保存图像
        self.showresult = QPushButton(u'刷新视图')
        self.showresult.setToolTip(u'刷新视图!')
        self.showresult.clicked.connect(self.resultShow)
        self.showresult.installEventFilter(self)

        self.addline = QPushButton(u'新增线条')
        self.addline.setToolTip(u'新增一条曲线!')
        self.addline.clicked.connect(self.addLine)
        self.addline.installEventFilter(self)

        self.removeline = QPushButton(u'删除线条')
        self.removeline.setToolTip(u'删除最近一条曲线!')
        self.removeline.clicked.connect(self.removeLine)
        self.removeline.installEventFilter(self)

        self.savefig = QPushButton(u'保存结果')
        self.savefig.setToolTip(u'将当前结果保存为高清图片!')
        self.savefig.clicked.connect(self.saveFig)
        self.savefig.installEventFilter(self)

        # 中层按钮布局
        center_layout = QHBoxLayout()
        center_layout.addWidget(self.showresult)
        center_layout.addWidget(self.addline)
        center_layout.addWidget(self.removeline)
        center_layout.addWidget(self.savefig)

        # 第三层按钮定义
        file_layout = QHBoxLayout()
        left_layout = QHBoxLayout()
        leftl_layout = QFormLayout()
        self.x_file_path = QLineEdit()
        self.x_file_path.setFixedHeight(20)
        leftl_layout.addRow(u"X轴:", self.x_file_path)
        leftr_layout = QVBoxLayout()
        x_file_option = QPushButton("选择")
        x_file_option.setFixedWidth(35)
        x_file_option.setFixedHeight(20)
        x_file_option.clicked.connect(self.xFile)
        leftr_layout.addWidget(x_file_option)
        left_layout.addLayout(leftl_layout)
        left_layout.addLayout(leftr_layout)

        right_layout = QHBoxLayout()
        rightl_layout = QFormLayout()
        self.y_file_path = QLineEdit()
        self.y_file_path.setFixedHeight(20)
        rightl_layout.addRow(u"Y轴:", self.y_file_path)
        rightr_layout = QVBoxLayout()
        y_file_option = QPushButton("选择")
        y_file_option.setFixedWidth(35)
        y_file_option.setFixedHeight(20)
        y_file_option.clicked.connect(self.yFile)
        rightr_layout.addWidget(y_file_option)
        right_layout.addLayout(rightl_layout)
        right_layout.addLayout(rightr_layout)

        self.selection = QCheckBox(u"自适应")

        okbt = QPushButton(u"确定")
        okbt.clicked.connect(self.xyPlot)

        file_layout.addLayout(left_layout)
        file_layout.addLayout(right_layout)
        file_layout.addWidget(self.selection)
        file_layout.addWidget(okbt)

        # 设置布局中控件的间距
        left_layout.setSpacing(3)
        right_layout.setSpacing(3)
        file_layout.setSpacing(20)

        # 下层状态栏
        bottom_layout = QVBoxLayout()
        bottom_layout.addWidget(self.statusBar)

        config_outer_layout.addItem(config_inner_layout)
        config_outer_layout.addItem(center_layout)
        config_outer_layout.addItem(file_layout)
        config_outer_layout.addItem(bottom_layout)

        config_group.setLayout(config_outer_layout)

        # 结果展示栏,设置为mainWindow
        result = QVBoxLayout()
        self.result = QMainWindow()
        result.addWidget(self.result)
        result_group.setLayout(result)

        main_layout.addWidget(config_group)
        main_layout.setStretchFactor(config_group, 1)
        main_layout.addWidget(result_group)
        main_layout.setStretchFactor(result_group, 2)
        self.setLayout(main_layout)

        cp = QDesktopWidget().availableGeometry().center()
        window_width = int(cp.x() * 2 * 0.7)
        window_height = int(cp.y() * 2 * 0.7)
        self.setGeometry(cp.x() - window_width // 2,
                         cp.y() - window_height // 2, window_width,
                         window_height)

    def changeColor(self):
        col = QColorDialog.getColor()
        if col.isValid():
            self.lc = col.name()
            self.showLine()

    def showLine(self):
        # self.view_face.setFixedWidth(230)
        # self.view_face.setSizePolicy(self.view_face.sizeHint())
        # 获取参数
        try:
            x_scale_text = self.x_scale.text()
            if x_scale_text == "":
                x_scale_text = self.x_scale.placeholderText()
            self.min_x, self.max_x = [
                float(k.strip()) for k in x_scale_text.strip().split(',')
            ]
        except Exception as ex:
            pass

        self.formula = self.math.text()
        if self.formula == "":
            self.formula = self.math.placeholderText()
        self.ls = self.linestyle.currentText()
        self.mark = self.markerstyle.currentText()
        self.lt = self.label.text()
        if self.lt == "":
            self.lt = self.label.placeholderText()
        self.md = self.markDensity.value()

        x0 = np.linspace(self.min_x, self.max_x, 100)
        try:
            formula_str = self.formula.split('=')[1]
            y0 = [eval(formula_str) for x in x0]
        except Exception as ex:
            return
        plt.cla()
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        ax.set_xlim(self.min_x, self.max_x)
        ax.plot(x0,
                y0,
                color=self.lc,
                ls=self.ls,
                marker=self.mark,
                label=self.lt,
                markevery=self.md)
        plt.subplots_adjust(left=0.17,
                            bottom=0.17,
                            right=0.9,
                            top=0.9,
                            hspace=0.1,
                            wspace=0.3)
        ax.legend(loc='best')
        self.fig = fig
        canvas = FigureCanvas(fig)
        self.view_face.setCentralWidget(canvas)

    def resultShow(self):
        try:
            x_scale_text = self.x_scale.text()
            if x_scale_text == "":
                x_scale_text = self.x_scale.placeholderText()
            self.min_x, self.max_x = [
                float(k.strip()) for k in x_scale_text.strip().split(',')
            ]
        except Exception as ex:
            pass

        try:
            y_scale_text = self.y_scale.text()
            if y_scale_text == "":
                y_scale_text = self.y_scale.placeholderText()
            self.min_y, self.max_y = [
                float(k.strip()) for k in y_scale_text.strip().split(',')
            ]
        except Exception as ex:
            pass

        self.x_text = self.x_label.text()
        if self.x_text == "":
            self.x_text = self.x_label.placeholderText()
        self.y_text = self.y_label.text()
        if self.y_text == "":
            self.y_text = self.y_label.placeholderText()

        try:
            x_tick_str = self.x_ticks.text()
            if x_tick_str == "":
                x_tick_str = self.x_ticks.placeholderText()
            self.x_tick_list = np.linspace(self.min_x, self.max_x,
                                           int(x_tick_str.strip()))
            self.x_label_list = self.x_tick_list
        except Exception as ex:
            pass

        try:
            y_tick_str = self.y_ticks.text()
            if y_tick_str == "":
                y_tick_str = self.y_ticks.placeholderText()
            self.y_tick_list = np.linspace(self.min_y, self.max_y,
                                           int(y_tick_str.strip()))
            self.y_label_list = self.y_tick_list
        except Exception as ex:
            pass

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        for index in range(len(self.formula_list)):
            x0 = np.linspace(self.min_x, self.max_x, 100)
            y0 = [eval(self.formula_list[index].split('=')[1]) for x in x0]
            ax.plot(x0,
                    y0,
                    color=self.lc_list[index],
                    ls=self.ls_list[index],
                    marker=self.mark_list[index],
                    markevery=self.mark_density_list[index],
                    label=self.lt_list[index])
        ax.legend(loc='best')
        ax.set_xticks(self.x_tick_list)
        ax.set_xticklabels(self.x_label_list)
        ax.set_yticks(self.y_tick_list)
        ax.set_yticklabels(self.y_label_list)
        ax.set_xlabel(self.x_text)
        ax.set_ylabel(self.y_text)
        ax.set_xlim(self.min_x, self.max_x)
        ax.set_ylim(self.min_y, self.max_y)
        self.fig = fig
        canvas = FigureCanvas(fig)
        self.result.setCentralWidget(canvas)

    def addLine(self):
        try:
            x = 1
            math_txt = self.math.text()
            if math_txt == "":
                math_txt = self.math.placeholderText()
            temp = eval(math_txt.split('=')[1])
            self.formula_list.append(math_txt)
            self.ls_list.append(self.linestyle.currentText())
            self.mark_list.append(self.markerstyle.currentText())
            label_txt = self.label.text()
            if label_txt == "":
                label_txt = self.label.placeholderText()
            self.lt_list.append(label_txt)
            self.lc_list.append(self.lc)
            self.mark_density_list.append(self.md)
            self.resultShow()
        except Exception as ex:
            pass

    def removeLine(self):
        try:
            assert (len(self.formula_list) != 0)
            self.formula_list.pop()
            self.ls_list.pop()
            self.mark_list.pop()
            self.lt_list.pop()
            self.lc_list.pop()
            self.mark_density_list.pop()
            self.resultShow()
        except Exception as ex:
            pass

    def xFile(self):
        filename, filetype = QFileDialog.getOpenFileName(self, "选取文件", "./",\
         "Text Files (*.txt);;Python Files (*.npy)")
        if filename != "":
            self.x_file_path.setText(filename)

    def yFile(self):
        filename, filetype = QFileDialog.getOpenFileName(self, "选取文件", "./",\
         "Text Files (*.txt);;Python Files (*.npy)")
        if filename != "":
            self.y_file_path.setText(filename)

    def xyPlot(self):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        xfile = self.x_file_path.text()
        yfile = self.y_file_path.text()
        x_arr = None
        y_arr = None
        if xfile and yfile:
            if not os.path.exists(xfile) or not os.path.exists(yfile):
                return
            xtype = os.path.splitext(xfile)[1]
            ytype = os.path.splitext(yfile)[1]
            if xtype != ytype:
                return
            if xtype.lower() == '.txt':
                try:
                    with open(xfile) as fp:
                        xdata = [[each.strip() for each in line.split(',')]
                                 for line in fp.readlines()]
                    with open(yfile) as fp:
                        ydata = [[each.strip() for each in line.split(',')]
                                 for line in fp.readlines()]
                    x_arr = np.array(xdata, dtype=np.float)
                    y_arr = np.array(ydata, dtype=np.float)
                    if x_arr.shape != y_arr.shape:
                        return
                except Exception as ex:
                    pass
            elif xtype.lower() == '.npy':
                try:
                    x_arr = np.load(xfile)
                    y_arr = np.load(yfile)
                    if x_arr.shape != y_arr.shape:
                        return
                except Exception as ex:
                    pass

            if self.selection.checkState():
                rd = np.random.RandomState(1234)
                color_list = rd.rand(x_arr.shape[0], 3)
                for index in range(x_arr.shape[0]):
                    ax.plot(x_arr[index], y_arr[index], color=color_list[index],\
                     ls=rd.choice(self.line_list), marker=rd.choice(self.marker_list))
                self.fig = fig
                canvas = FigureCanvas(fig)
                self.result.setCentralWidget(canvas)
        else:
            pass

    def saveFig(self):
        dialog = QFileDialog()
        filename, filetype = dialog.getSaveFileName(self, "图像保存", "./result.png"\
                        ,"All Files (*);;JPEG Files (*.jpg);;PNG Files (*.png);;SVG Files (*.svg)")
        self.fig.set_size_inches(8, 6)
        if filename != "" and self.fig:
            plt.savefig(filename, dpi=80)
            self.resultShow()

    def eventFilter(self, obj, event):
        if event.type() == QEvent.HoverEnter:
            if obj == self.lineColor:
                self.statusBar.showMessage(u"点击此按钮将更改线条颜色!")
                return False
            elif obj == self.markDensity:
                value = self.markDensity.value()
                self.statusBar.showMessage(str(value))
                return False
            elif obj == self.lineview:
                self.statusBar.showMessage(u"线条预览!")
                return False
            elif obj == self.showresult:
                self.statusBar.showMessage(u"刷新当前视图,重新显示图片!")
                return False
            elif obj == self.addline:
                self.statusBar.showMessage(u'新增一条曲线!')
                return False
            elif obj == self.removeline:
                self.statusBar.showMessage(u'删去最近的一条曲线!')
                return False
            elif obj == self.savefig:
                self.statusBar.showMessage(u'将当前结果保存为高清图片!')
                return False
        elif event.type() == 2 or event.type() == 129:
            if obj == self.markDensity:
                value = self.markDensity.value()
                self.statusBar.showMessage(str(value))
                self.showLine()
                return False
            else:
                return False
        else:
            return False