Пример #1
0
def pixmap_to_bytes(pixmap):
    """Converts a pixmap to a byte array for easy comparisons"""
    array = QByteArray()
    buffer = QBuffer(array)
    buffer.open(QIODevice.WriteOnly)
    pixmap.save(buffer, "PNG")
    return array
Пример #2
0
    def __init__(self):
        super().__init__()
        self.buffer = QBuffer()
        self.buffer.open(QBuffer.ReadWrite)
        self.setupUI()

        self.model = QModel(self)
        self.model.start()
Пример #3
0
    def requestStarted(self, request):
        if request.requestUrl() == "testpy:hello":
            request.redirect("testpy:goodbye")
            return

        self.buffer = QBuffer()
        self.buffer.setData("Really nice goodbye text.")
        self.buffer.aboutToClose.connect(self.buffer.deleteLater)
        request.reply("text/plain;charset=utf-8", self.buffer)
class TestSchemeHandler(QWebEngineUrlSchemeHandler):
    def requestStarted(self, request):
        if request.requestUrl() == "testpy:hello":
            request.redirect("testpy:goodbye")
            return

        self.buffer = QBuffer()
        self.buffer.setData(py3k.b("Really nice goodbye text."))
        self.buffer.aboutToClose.connect(self.buffer.deleteLater)
        request.reply(py3k.b("text/plain;charset=utf-8"), self.buffer)
Пример #5
0
def encode_image(image: QImage) -> str:
    image_bytes = QByteArray()
    buffer = QBuffer(image_bytes)
    buffer.open(QIODevice.WriteOnly)

    # writes pixmap into bytes in PNG format
    image.save(buffer, "PNG")  # type: ignore
    encoded_bytes = image_bytes.toBase64()
    codec = QTextCodec.codecForName(b"UTF-8")
    encoded_string = codec.toUnicode(encoded_bytes)
    return encoded_string
Пример #6
0
 def readImageQR(self, image):
     buffer = QBuffer()
     buffer.open(QBuffer.ReadWrite)
     image.save(buffer, "BMP")
     pillow_image = Image.open(io.BytesIO(buffer.data()))
     barcodes = pyzbar.decode(pillow_image,
                              symbols=[pyzbar.ZBarSymbol.QRCODE])
     if barcodes:
         self.qr_data_available.emit(barcodes[0].data.decode('utf-8'))
         return True
     else:
         return False
Пример #7
0
    def __init__(self, parent=None):
        super(NetworkConnectionClass, self).__init__(parent=parent)
        #self.CommandSocket = QTcpSocket()
        self.CommandSocket = QUdpSocket()
        self.CommandSocket.bind(QHostAddress("192.168.100.2"), 2323)
        self.CommandSocket.connected.connect(self.EventConnectedHandle)
        self.CommandSocket.readyRead.connect(self.RecieveData)

        #self.CommandSocket.connectToHost("192.168.100.5",2323,QIODevice.ReadWrite)
        #self.CommandSocket.connectToHost("127.0.0.1",2323,QIODevice.ReadWrite)
        #self.CommandSocket.connectToHost("192.168.20.196",2323,QIODevice.ReadWrite)
        #print("NETWORK - ",self.CommandSocket.localAddress(),self.CommandSocket.peerAddress())

        self.Display = WindowNetworkConnection()

        self.NetworkDataArray = QByteArray()
        self.NetworkDataArray.resize(2000)
        self.SignalDataRec.connect(self.Display.PrintData)

        self.BufferWrite = QBuffer(self.NetworkDataArray)
        self.BufferWrite.open(QBuffer.WriteOnly)

        self.BufferRead = QBuffer(self.NetworkDataArray)
        self.BufferRead.open(QBuffer.ReadOnly)

        self.ReadDataStream = QDataStream(self.BufferRead)
        self.ReadDataStream.setByteOrder(QDataStream.LittleEndian)

        self.WriteDataStream = QDataStream(self.BufferWrite)
        self.WriteDataStream.setByteOrder(QDataStream.LittleEndian)

        self.SocketDataStream = QDataStream(self.CommandSocket)
        self.SocketDataStream.setByteOrder(QDataStream.LittleEndian)

        self.Timer = QTime()
        self.Timer.start()

        self.BufferRead.seek(0)
        self.BufferWrite.seek(0)

        self.LimitBufferSize = 2000
        self.MinTransferUnit = 7
        self.MaxTransferUnit = 18
        self.bytesAvailable = 0
        self.Display.ui.pushButton.clicked.connect(self.SendData)

        #===================================================== WRITE BUFFER
        self.SendBuffer = QByteArray()
Пример #8
0
 def to_base64(self, w=32, h=32):
     """Return icon as base64 to make it work with html"""
     pix = self.pixmap(w, h)
     data = QByteArray()
     buff = QBuffer(data)
     pix.save(buff, "PNG")
     return data.toBase64().data().decode()
Пример #9
0
 def mousePressEvent(self, event):
     super(SnapWindow, self).mousePressEvent(event)
     if event.button() == QtCore.Qt.MouseButton.LeftButton:
         self.scale_ratio()
         self.QDrag = QDrag(self)
         self.QMimeData = QMimeData()
         self.imgdata = QByteArray()
         imgbuffer = QBuffer(self.imgdata)
         imgbuffer.open(QIODevice.WriteOnly)
         
         self.original_snap.save(imgbuffer, "PNG")
         
         self.QMimeData.setImageData(self.imgdata)
         self.QMimeData.setData("image/png", self.imgdata)
         self.QDrag.setMimeData(self.QMimeData)
         self.QDrag.setPixmap(self.dragicon)
         dropaction = self.QDrag.exec_(Qt.CopyAction)
Пример #10
0
    def load_string(self, string, parent=None):
        """Load a UI file from a string and return the widget"""
        data = QByteArray(string.encode('utf-8'))
        buf = QBuffer(data)
        ui = self.load(buf, parent)

        # Perform any custom processing on the ui
        self.process_ui(ui)
        return ui
Пример #11
0
 def testWrite(self):
     text = 'foobar'
     doc = QTextDocument(text)
     b = QBuffer()
     b.open(QBuffer.ReadWrite)
     writer = QTextDocumentWriter(b, "plaintext")
     writer.write(doc)
     b.close()
     self.assertEqual(b.buffer(), text)
Пример #12
0
 def prnt(self, screenShot: QPixmap):
     buffer = QBuffer()
     buffer.open(QBuffer.ReadWrite)
     screenShot.save(buffer, 'png')
     data = buffer.data().data()
     res = self.client.basicGeneral(data)
     if 'words_result_num' in res.keys():
         print('[ INFO ] 识别成功')
         text = ''
         result = res['words_result']
         d = {
             '单选题': self.ui.rad_1,
             '多选题': self.ui.rad_2,
             '填空题': self.ui.rad_3,
             '问答题': self.ui.rad_4,
             '判断题': self.ui.rad_14,
             '分析题': self.ui.rad_5,
             '解答题': self.ui.rad_5,
             '计算题': self.ui.rad_5,
             '证明题': self.ui.rad_5,
         }
         for words in result:
             ques_type = False
             for k in d.keys():
                 if k in words['words']:
                     ques_type = True
                     print('[ INFO ] 题目类型:', k)
                     d[k].setChecked(True)
                     d[k].repaint()
                     break
             if not ques_type:
                 text += words['words']
         text = text.replace('(', '(').replace(')', ')').replace(
             '?', '?').replace(',', ',')
         print('[ INFO ] 题目:', text)
         self.ui.questLineEdit.setText(text)
         self.ui.questLineEdit.repaint()
         self.ui.searchButton.click()
     else:
         print('[ INFO ] 识别失败')
Пример #13
0
    def _create_tooltip(self, anchor: str) -> str:
        path = Path(anchor)
        suffix = path.suffix
        if suffix in ('.txt', '.py', '.html', '.xml'):
            data = self._read_file(path)
            if data:
                file_buf = data.decode('utf-8')
                if suffix == '.html':
                    return file_buf
                else:
                    return f'<pre>{file_buf}</pre>'
        elif suffix in ('.png', '.jpg'):
            image = self._read_image(path)
            if image:
                buffer = QBuffer()
                buffer.open(QIODevice.WriteOnly)
                pixmap = QPixmap.fromImage(image)
                pixmap.save(buffer, "PNG")
                data = bytes(buffer.data().toBase64()).decode()
                return f'<img src="data:image/png;base64,{data}">'

        return f'<p>{anchor}</p>'
Пример #14
0
    def testRefCountOfTOutputDevice(self):
        generator = QSvgGenerator()
        iodevice1 = QBuffer()
        refcount1 = getrefcount(iodevice1)

        generator.setOutputDevice(iodevice1)

        self.assertEqual(generator.outputDevice(), iodevice1)
        self.assertEqual(getrefcount(generator.outputDevice()), refcount1 + 1)

        iodevice2 = QBuffer()
        refcount2 = getrefcount(iodevice2)

        generator.setOutputDevice(iodevice2)

        self.assertEqual(generator.outputDevice(), iodevice2)
        self.assertEqual(getrefcount(generator.outputDevice()), refcount2 + 1)
        self.assertEqual(getrefcount(iodevice1), refcount1)

        del generator

        self.assertEqual(getrefcount(iodevice2), refcount2)
Пример #15
0
 def load_finished(self, state):
     pixmap = self.engine.grab()
     self.image = QByteArray()
     buf = QBuffer(self.image)
     buf.open(QIODevice.WriteOnly)
     pixmap.save(buf, "PNG")
     buf.close()
     self.quit()
Пример #16
0
    def save_library(self):
        global pc_lib
        global pc_ui

        directory, ext = QtWidgets.QFileDialog.getSaveFileName(
            self, 'Save Files', os.path.dirname(__file__),
            "Pose Library(*.poslib)", '*.poslib')

        if directory is not '':
            for entry in pc_lib:
                # Convert Pixmap to Byte Array
                byte_array = QByteArray()
                buffer = QBuffer(byte_array)
                buffer.open(QIODevice.WriteOnly)
                entry["preview"].save(buffer, 'PNG')
                encoded = buffer.data().toBase64()
                entry["preview"] = encoded.data().decode("utf8")
            # Write data to file
            f = open(directory, "w")
            f.write(json.dumps(pc_lib))
            f.close()
            # Reload the pose libary
            load_library(directory)
Пример #17
0
    def QImageToBase64(image: QImage,
                       format: str = "jpeg",
                       width: int = 1080,
                       with_header: bool = True) -> str:
        byte_array = QByteArray()
        buffer = QBuffer(byte_array)
        image.scaledToWidth(width).save(buffer, format)

        result = ""
        if with_header:
            result += "data:image/%s;base64," % format

        result += str(byte_array.toBase64())[2:-1]

        return result
 def from_scene(cls, scene):
     buffer = QBuffer()
     generator = QSvgGenerator()
     generator.setOutputDevice(buffer)
     scene_rect = scene.sceneRect()
     generator.setViewBox(scene_rect)
     painter = QPainter(generator)
     scene.render(painter, scene_rect, scene_rect)
     painter.end()
     buffer.open(QBuffer.ReadOnly)
     renderer = cls(buffer.readAll())
     buffer.close()
     renderer.scene = scene
     return renderer
def load_gif(gif_name):
    _, ext = (os.path.splitext(gif_name))
    full_path = os.path.join(get_icon_dir_path(ext[1:]), gif_name)
    if os.path.exists(full_path):
        gif_byte_array = QByteArray(open(full_path, 'rb').read())
        gif_buffer = QBuffer(gif_byte_array)

        q_movie = QMovie(full_path)
        q_movie.setFormat(QByteArray(b'GIF'))
        q_movie.setDevice(gif_buffer)
        q_movie.setCacheMode(QMovie.CacheAll)
        q_movie.setSpeed(100)
        q_movie.jumpToFrame(0)

        return q_movie
    raise FileNotFoundError
Пример #20
0
Файл: qt.py Проект: whs/runekit
def qpixmap_to_np(im: QPixmap) -> np.ndarray:
    # from PIL.ImageQt.fromqimage
    buffer = QBuffer()
    buffer.open(QIODevice.ReadWrite)
    if im.hasAlphaChannel():
        im.save(buffer, "png")
    else:
        im.save(buffer, "ppm")

    npbuf = np.frombuffer(buffer.data(), "<B")
    buffer.close()

    out = cv2.imdecode(npbuf, cv2.IMREAD_UNCHANGED)
    if out.shape[2] == 3:
        # Add alpha channel
        out = np.pad(out, ((0, 0), (0, 0), (0, 1)), constant_values=0xFF)

    return out
Пример #21
0
    def show_qr_code(self):
        buffer_png = QBuffer()
        buffer_png.open(QIODevice.ReadWrite)

        self.text = self.le_qr_code.text()
        self.fg_color = self.btn_fg.palette().button().color().name()
        self.bg_color = self.btn_bg.palette().button().color().name()
        self.scale = self.sb_scale.value()

        qrcode = pyqrcode.create(self.text)
        qrcode.png(file=buffer_png,
                   scale=self.scale,
                   module_color=self.fg_color,
                   background=self.bg_color)

        pixmap_png = QPixmap()
        pixmap_png.loadFromData(buffer_png.buffer())
        self.lb_qr_img_info.setText(
            f'QR Code com {pixmap_png.width()}x{pixmap_png.height()}')
        self.lb_qr_img.setPixmap(pixmap_png)
        buffer_png.close()

        self.btn_save_qr.setEnabled(True)
Пример #22
0
        def plot_dataset(dataset, color_map, scale_labels):
            # Only generate the brush once for each unique value
            lookup_table = {
                x: pg.mkBrush(color_map.map(x))
                for x in numpy.unique(dataset)
            }
            brushes = [lookup_table[x] for x in dataset.data]

            scale_widget.setGradient(color_map.getGradient())
            scale_widget.setLabels(scale_labels)

            # Generate Plot
            plot = plot_item.plot(data_x,
                                  data_y,
                                  pen=None,
                                  symbolPen=None,
                                  symbolBrush=brushes,
                                  pxMode=False,
                                  symbolSize=scale_factors,
                                  symbol=pixel_paths)

            plot_item.getViewWidget().parent().grab()
            volcview_img = plot_item.getViewWidget().parent().grab()
            self._view_extents = vbox.viewRange()

            file_bytes = QByteArray()
            file_buffer = QBuffer(file_bytes)
            file_buffer.open(QIODevice.WriteOnly)
            volcview_img.save(file_buffer, "PNG")
            file_buffer.close()

            file_stream = BytesIO(file_bytes)
            pil_img = Image.open(file_stream)

            # find coverage percent(ish)
            width, height = pil_img.size
            total_count = width * height  # Should be 800,000, unless we changed the size of the images.

            # dump into a numpy array to count grey pixels
            as_array = numpy.array(pil_img)

            # the grey value we use is 238, so if all elements of axis 2 are 238,
            # then the pixel is grey.
            is_grey = numpy.all(as_array == 238, axis=2)
            # number that is False is non-grey, or covered, pixels
            # Not quite true due to scale bar, borders, etc.
            unique, counts = numpy.unique(is_grey, return_counts=True)
            non_grey = dict(zip(unique, counts))[False]

            covered_percent = non_grey / total_count

            # Don't send the image to volcview unless it has at least 15% coverage.
            # Allow 2% for the scale bar and other features.
            threshold = .17
            if sector['pixelSize'] == 5:
                threshold = .06

            if covered_percent > threshold:
                self._add_coastlines(pil_img)

                raw_data = QByteArray()
                buffer = QBuffer(raw_data)

                if not gen_cloud and not self._data_type in ('VIIRS'):
                    # "Save" the percentile bar to a bytes buffer, in PNG format
                    buffer.open(QIODevice.WriteOnly)
                    _percentContainer.grab().save(buffer, "PNG")
                    buffer.close()

                    # Use a bytes IO object to "read" the image into a PIL object
                    img_stream = BytesIO(raw_data)
                    with Image.open(img_stream) as img:
                        pil_img.paste(img, (5, 5), mask=img)

                # Add the scale bar and timestamp.
                scale_top = pil_img.height

                buffer.open(QIODevice.WriteOnly)
                scale_widget.grab()  # why? WHYYYYYYYY????
                scale_widget.grab().save(buffer, "PNG")
                buffer.close()

                img_stream = BytesIO(raw_data)
                with Image.open(img_stream) as img:
                    scale_top = pil_img.height - img.height - 10
                    pil_img.paste(img, (25, scale_top), mask=img)

                # Add the timestamp
                buffer.open(QIODevice.WriteOnly)
                date_label.grab().save(buffer, "PNG")
                buffer.close()

                img_stream = BytesIO(raw_data)
                with Image.open(img_stream) as img:
                    pil_img.paste(img, (pil_img.width - img.width - 51,
                                        scale_top - img.height - 5),
                                  mask=img)

                # Save an archive image
                logging.debug("Saving archive image for %s", band)
                filename = f"{self._file_date.strftime('%Y_%m_%d_%H%M%S')}-{band}-{self._data_type}.png"
                save_file = os.path.join(config.FILE_BASE, 'VolcView',
                                         sector['name'], filename)
                os.makedirs(os.path.dirname(save_file), exist_ok=True)
                pil_img.save(save_file, format='PNG')
                file_stream = BytesIO()
                # "Save" the image to memory in PNG format
                pil_img.save(file_stream, format='PNG')
                file_stream.seek(0)  # Go back to the begining for reading out
                logging.debug("Uploading image for %s", band)
                if not DEBUG:
                    self._volcview_upload(file_stream, sector, band)
                else:
                    logging.debug("******Pretending to send to volc view")

                    print("TEST UPLOAD", sector['name'], filename, "***200***")

                logging.debug("Image upload complete")

                if DEBUG:
                    # This is just Debugging code to save the generated
                    # image to disk for local analysis.
                    # Feel free to change file paths to something more
                    # appropriate if desired.
                    print(f"^^^^SAVING IMAGE FOR FILE TO DISK^^^")
                    dest_dir = f"/tmp/VolcViewImages/{sector['sector']}"
                    os.makedirs(dest_dir, exist_ok=True)
                    dest_file = f"{self._data_type}-{band}-{self._file_date.strftime('%Y_%m_%d_%H%M%S')}.png"
                    dest_path = os.path.join(dest_dir, dest_file)
                    file_stream.seek(0)
                    with open(dest_path, 'wb') as f:
                        f.write(file_stream.read())
                ###################
            else:
                logging.info("Not enough coverage to bother with")

            plot_item.removeItem(plot)
Пример #23
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.buffer = QBuffer()
        self.buffer.open(QBuffer.ReadWrite)
        self.setupUI()

        self.model = QModel(self)
        self.model.start()

    """ USER INTERFACE SETUP """
    def setupUI(self):
        # WINDOW SETUP
        self.setWindowTitle("Keras.QuickDraw")
        self.setMinimumSize(QSize(800, 600))
        self.setFixedSize(QSize(800, 600))
        self.setWindowIcon(QIcon("favicon.ico"))

        # INITIALIZE: WINDOW CENTRAL
        self.widget_central = QWidget(self)
        self.widget_central.setObjectName("Window Central")
        self.widget_central.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.layout_central = QBoxLayout(QBoxLayout.TopToBottom, self.widget_central)
        self.setCentralWidget(self.widget_central)

        # INITIALIZE: CENTRAL HEADER
        self.widget_header = QWidget(self.widget_central)
        self.widget_header.setObjectName("Widget Header")
        self.widget_header.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.widget_header_indicater = QLabel(parent = self.widget_header)
        self.widget_header_caption   = QLabel("(TARGET)", self.widget_header)
        self.widget_header_counter   = QLabel(parent = self.widget_header)
        
        self.layout_header = QBoxLayout(QBoxLayout.LeftToRight, self.widget_header)
        self.layout_header.addWidget(self.widget_header_indicater, 0, Qt.AlignLeft)
        self.layout_header.addWidget(self.widget_header_caption  , 1, Qt.AlignCenter)
        self.layout_header.addWidget(self.widget_header_counter  , 0, Qt.AlignRight)

        # INITIALIZE: CENTRAL CANVAS
        self.widget_canvas = QCanvas(self.widget_central, self)
        self.widget_canvas.setObjectName("Widget Canvas")
        self.widget_canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # INITIALIZE: CENTRAL BUTTONS
        self.widget_footer = QWidget(self.widget_central)
        self.widget_footer.setObjectName("Widget Footer")
        self.widget_footer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.widget_footer_clear = QPushButton("Clear", self.widget_footer)
        self.widget_footer_clear.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.widget_footer_clear.clicked.connect(self.widget_canvas.resetCanvas)
        self.widget_footer_undo  = QPushButton("Undo", self.widget_footer)
        self.widget_footer_undo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.widget_footer_undo.clicked.connect(self.widget_canvas.undoCanvas)

        self.layout_footer = QBoxLayout(QBoxLayout.LeftToRight, self.widget_footer)
        self.layout_footer.addWidget(self.widget_footer_undo, 0)
        self.layout_footer.addWidget(self.widget_footer_clear, 0)
        self.layout_footer.setMargin(0)

        # LAYOUT: HEADER + CANVAS + FOOTER -> CENTRAL WINDOW CENTRAL
        self.layout_central.addWidget(self.widget_header, 0)
        self.layout_central.addWidget(self.widget_canvas, 1, Qt.AlignCenter)
        self.layout_central.addWidget(self.widget_footer, 0)

        self.show()

    """ EVENT: SAVING CANVAS (QThread ALTERNATIVE) """
    def paintEvent(self, event: QPaintEvent) -> None:
        # SCREENSHOT WIDGET OF QPaintDevice, SUCH AS QBITMAP
        self.widget_canvas.render(self.widget_canvas.pixmap())
        if self.isVisible:
            self.buffer.reset()
            self.widget_canvas.pixmap().save(self.buffer, "BMP")
        return super().paintEvent(event)

    """ EVENT: CLOSING MAINWINDOW """
    def closeEvent(self, event: QCloseEvent) -> None:
        self.model.terminate()
        self.model.wait()
        self.buffer.close()
        return super().closeEvent(event)
Пример #24
0
        def plot_dataset(dataset, color_map, scale_labels):
            # Only generate the brush once for each unique value
            lookup_table = {x: pg.mkBrush(color_map.map(x)) for x in numpy.unique(dataset)}
            brushes = [lookup_table[x] for x in dataset.data]

            scale_widget.setGradient(color_map.getGradient())
            scale_widget.setLabels(scale_labels)

            # Generate Plot
            plot = plot_item.plot(data_x, data_y,
                                  pen=None,
                                  symbolPen=None,
                                  symbolBrush=brushes,
                                  pxMode=False,
                                  symbolSize=scale_factors,
                                  symbol=pixel_paths)

            plot_item.getViewWidget().parent().grab()
            volcview_img = plot_item.getViewWidget().parent().grab()
            self._view_extents = vbox.viewRange()

            file_bytes = QByteArray()
            file_buffer = QBuffer(file_bytes)
            file_buffer.open(QIODevice.WriteOnly)
            volcview_img.save(file_buffer, "PNG")
            file_buffer.close()

            file_stream = BytesIO(file_bytes)
            pil_img = Image.open(file_stream)

            # find coverage percent(ish)
            width, height = pil_img.size
            total_count = width * height  # Should be 800,000, unless we changed the size of the images.

            # dump into a numpy array to count grey pixels
            as_array = numpy.array(pil_img)

            # the grey value we use is 238, so if all elements of axis 2 are 238,
            # then the pixel is grey.
            is_grey = numpy.all(as_array == 238, axis=2)
            # number that is False is non-grey, or covered, pixels
            # Not quite true due to scale bar, borders, etc.
            unique, counts = numpy.unique(is_grey, return_counts=True)
            non_grey = dict(zip(unique, counts))[False]

            covered_percent = non_grey / total_count

            # Don't send the image to volcview unless it has at least 15% coverage.
            # Allow 2% for the scale bar and other features.
            threshold = .17
            if sector['pixelSize'] == 5:
                threshold = .06

            if covered_percent > threshold:
                self._add_coastlines(pil_img)

                raw_data = QByteArray()
                buffer = QBuffer(raw_data)

                if not gen_cloud and not self._data_type in ('VIIRS'):
                    # "Save" the percentile bar to a bytes buffer, in PNG format
                    buffer.open(QIODevice.WriteOnly)
                    _percentContainer.grab().save(buffer, "PNG")
                    buffer.close()

                    # Use a bytes IO object to "read" the image into a PIL object
                    img_stream = BytesIO(raw_data)
                    with Image.open(img_stream) as img:
                        pil_img.paste(img,
                                      (5, 5),
                                      mask = img)

                # Add the scale bar and timestamp.
                scale_top = pil_img.height

                buffer.open(QIODevice.WriteOnly)
                scale_widget.grab()  # why? WHYYYYYYYY????
                scale_widget.grab().save(buffer, "PNG")
                buffer.close()

                img_stream = BytesIO(raw_data)
                with Image.open(img_stream) as img:
                    scale_top = pil_img.height - img.height - 10
                    pil_img.paste(img, (25, scale_top), mask = img)

                # Add the timestamp
                buffer.open(QIODevice.WriteOnly)
                date_label.grab().save(buffer, "PNG")
                buffer.close()

                img_stream = BytesIO(raw_data)
                with Image.open(img_stream) as img:
                    pil_img.paste(img,
                                  (pil_img.width - img.width - 51,
                                   scale_top - img.height - 5),
                                  mask = img)

                # Save an archive image
                logging.debug("Saving archive image for %s", band)
                os.makedirs(os.path.dirname(save_file), exist_ok = True)
                pil_img.save(save_file, format = 'PNG')

            else:
                logging.info("Not enough coverage to bother with")

            plot_item.removeItem(plot)
Пример #25
0
 def on_success(self, request, content_type, reply):
     body = QBuffer(parent=request)
     body.setData(reply)
     request.reply(content_type, body)
Пример #26
0
    def get_raw(self):
        '''
        Get the scene information. (can be be save in .pii)

        Return
        ------
        out: (dict)
            Dictionary of scene date to be save in .pii file.
        '''
        image_data = str()
        pixmap = self._backgroundNode.pixmap()
        # Extract Image Data
        if not pixmap.isNull():
            buffer = QBuffer()
            buffer.open(QIODevice.WriteOnly)
            pixmap.save(buffer, "PNG")
            # Image Data
            image_data = bytes(buffer.data().toBase64()).decode('ascii')

        nodeList = []
        for each in self._scene.items():
            if type(each) == PickNode:
                textColor = each.defaultTextColor()
                bgColor = each.Background
                item = {
                    PIIPick.TYPE:
                    PIINode.PICK,
                    PIIPick.TEXT:
                    each.toPlainText(),
                    PIIPick.SIZE:
                    each.font().pointSize(),
                    PIIPick.POSITION: (each.pos().x(), each.pos().y()),
                    PIIPick.COLOR:
                    (textColor.red(), textColor.green(), textColor.blue()),
                    PIIPick.BACKGROUND:
                    (bgColor.red(), bgColor.green(), bgColor.blue()),
                    PIIPick.SELECTION:
                    each.Items,
                    PIIPick.SHAPE:
                    each.Shape
                }
                nodeList.append(item)
            elif type(each) == ButtonNode:
                textColor = each.defaultTextColor()
                bgColor = each.Background
                item = {
                    PIIButton.TYPE:
                    PIINode.BUTTON,
                    PIIButton.TEXT:
                    each.toPlainText(),
                    PIIButton.SIZE:
                    each.font().pointSize(),
                    PIIButton.POSITION: (each.pos().x(), each.pos().y()),
                    PIIButton.COLOR:
                    (textColor.red(), textColor.green(), textColor.blue()),
                    PIIButton.BACKGROUND:
                    (bgColor.red(), bgColor.green(), bgColor.blue()),
                    PIIButton.COMMAND:
                    each.Command,
                    PIIButton.COMMANDTYPE:
                    each.CommandsType
                }
                nodeList.append(item)

        rawData = {
            PII.VERSION: "1.0.0",
            PII.BACKGROUND: image_data,
            PII.NODES: nodeList
        }
        return rawData
Пример #27
0
class NetworkConnectionClass(QtCore.QObject):
    SignalDataRec = Signal(str, int)
    SignalFrameDataAvailable = Signal()

    def __init__(self, parent=None):
        super(NetworkConnectionClass, self).__init__(parent=parent)
        #self.CommandSocket = QTcpSocket()
        self.CommandSocket = QUdpSocket()
        self.CommandSocket.bind(QHostAddress("192.168.100.2"), 2323)
        self.CommandSocket.connected.connect(self.EventConnectedHandle)
        self.CommandSocket.readyRead.connect(self.RecieveData)

        #self.CommandSocket.connectToHost("192.168.100.5",2323,QIODevice.ReadWrite)
        #self.CommandSocket.connectToHost("127.0.0.1",2323,QIODevice.ReadWrite)
        #self.CommandSocket.connectToHost("192.168.20.196",2323,QIODevice.ReadWrite)
        #print("NETWORK - ",self.CommandSocket.localAddress(),self.CommandSocket.peerAddress())

        self.Display = WindowNetworkConnection()

        self.NetworkDataArray = QByteArray()
        self.NetworkDataArray.resize(2000)
        self.SignalDataRec.connect(self.Display.PrintData)

        self.BufferWrite = QBuffer(self.NetworkDataArray)
        self.BufferWrite.open(QBuffer.WriteOnly)

        self.BufferRead = QBuffer(self.NetworkDataArray)
        self.BufferRead.open(QBuffer.ReadOnly)

        self.ReadDataStream = QDataStream(self.BufferRead)
        self.ReadDataStream.setByteOrder(QDataStream.LittleEndian)

        self.WriteDataStream = QDataStream(self.BufferWrite)
        self.WriteDataStream.setByteOrder(QDataStream.LittleEndian)

        self.SocketDataStream = QDataStream(self.CommandSocket)
        self.SocketDataStream.setByteOrder(QDataStream.LittleEndian)

        self.Timer = QTime()
        self.Timer.start()

        self.BufferRead.seek(0)
        self.BufferWrite.seek(0)

        self.LimitBufferSize = 2000
        self.MinTransferUnit = 7
        self.MaxTransferUnit = 18
        self.bytesAvailable = 0
        self.Display.ui.pushButton.clicked.connect(self.SendData)

        #===================================================== WRITE BUFFER
        self.SendBuffer = QByteArray()

        #=====================================================

#        TestMessage = QByteArray(bytearray.fromhex('A1 A2 A3')); TestMessage2 = QByteArray(bytearray.fromhex('A4 A5 A6'))
#        self.BufferWriteQueue.write(TestMessage); self.BufferWriteQueue.write(TestMessage2)
#        print("BUFFER - ",self.NetworkDataArray)
#        self.Message = MessageData()
#        self.Message << self.NetworkDataStream << self.NetworkDataStream

    def __rshift__(self, Reciever: DataTransferHeader):
        Reciever << self.ReadDataStream
        self.bytesAvailable -= Reciever.UNIT_SIZE
        print("BYTES AVAILABLE - ", self.bytesAvailable)
        #print("     REABUFFER POS - ",self.BufferRead.pos(),'BYTES AVAILABLE - ',self.bytesAvailable,"UNIT SIZE -",Reciever.UNIT_SIZE)
        #print("   READ UNIT -",Reciever.UNIT_SIZE)
        #print("   READ BUFFER POS -",self.BufferRead.pos())
        #print("   READ BUFFER -",self.BufferRead.data().toHex())

        if not self.BufferRead.pos(
        ) < self.LimitBufferSize - self.MaxTransferUnit:
            self.BufferRead.seek(0)
            print("READ BUFFER SEEK TO 0 - ", self.BufferRead.pos())

        return self

    def EventConnectedHandle(self):
        self.SignalDataRec.emit("CONNECTED TO HOST", 0)
        #self.SignalDataRec.emit("192.168.100.5 PORT 2323",0)
        self.SignalDataRec.emit("192.168.20.197 PORT 2323", 0)
        #self.SignalDataRec.emit("BYTES IN REC BUFFER - " + str(self.bytesAvailable))

    def RecieveData(self):
        #self.CommandSocket.receiveDatagram(20)
        HEADER = QByteArray()
        HEADER.resize(2)
        if self.bytesAvailable < self.LimitBufferSize - self.MaxTransferUnit:  #check that memory for packet available
            if self.BufferWrite.pos(
            ) < self.LimitBufferSize - self.MaxTransferUnit:
                (newData, sender,
                 senderPort) = self.CommandSocket.readDatagram(20)

                #newData = self.CommandSocket.read(self.LimitBufferSize - self.bytesAvailable)
                #print("   NEW DATA - ",newData.toHex(),"to POS - ",self.BufferWrite.pos())
                self.BufferWrite.write(newData)
                self.bytesAvailable += newData.size()
                print(self.Timer.restart())
                #print("REC ",data)
                #print("   BUFFER - ",self.BufferWrite.data().toHex())

            else:
                H1 = 0
                H2 = 0
                while self.CommandSocket.bytesAvailable() > 0:
                    H1 = H2
                    H2 = self.SocketDataStream.readInt16()

                    if H1 == 0xF1 and (H2 == 0xD1 or H2 == 0xD2 or H2 == 0xD3
                                       or H2 == 0xC1):
                        self.BufferWrite.seek(0)
                        newData = self.CommandSocket.read(
                            self.LimitBufferSize - self.bytesAvailable)
                        self.WriteDataStream.writeInt16(H1)
                        self.WriteDataStream.writeInt16(H2)
                        print(
                            "=============================================================="
                        )
                        print("SEEK TO 0")
                        print("NEW DATA - ", newData, "to POS - ",
                              self.BufferWrite.pos() - 4)
                        self.BufferWrite.write(newData)
                        self.bytesAvailable += (4 + newData.size())
                        #print("BUFFER - ",self.NetworkDataArray.toHex())
                        break
                    else:
                        self.WriteDataStream.writeInt16(H2)
                        self.bytesAvailable += 1

        #self.SignalDataRec.emit("BYTES IN REC BUFFER - " + str(self.bytesAvailable))

        if (self.bytesAvailable >= self.MinTransferUnit):
            self.SignalFrameDataAvailable.emit()

    def SendData(self):
        Req = ConnectCheckRequest()
        self.SendBuffer.clear()
        self.SendBuffer.resize(Req.MESSAGE_SIZE)

        WriteDataStream = QDataStream(self.SendBuffer, QIODevice.ReadWrite)
        WriteDataStream.setByteOrder(QDataStream.LittleEndian)
        Req >> WriteDataStream

        self.CommandSocket.write(self.SendBuffer)
        self.CommandSocket.waitForBytesWritten(20)
        self.SignalDataRec.emit("CHECK CONNECT - " + str(Req.Connect), 1)

        #self.CommandSocket.write(bytearray(b'TestMessage\r\n'))
        #print("WRITE BUFFER - ",self.SendBuffer.toHex())
        #print("===============================================")

    def HandleErrorSocket(self):
        print("ErrorSocket")
Пример #28
0
    def changeItem(self,
                   item,
                   newName=None,
                   newDescription=None,
                   newContent=None,
                   newAccess=None,
                   metadataChanges=None):
        assert isinstance(item,
                          CollectionItem), 'item must be a collection item'
        #newName=str(newName)
        #newDescription=str(newDescription)
        #newContent=str(newContent)
        #just in case we have random unicode coming in
        #TODO: check that item belongs to this collection. just in case

        if item.readonly(): raise CollectionReadonlyError()

        # Upgrade version if needed
        self.updateItemIfNeeded(item)

        if newAccess is not None and newAccess != item.access():
            newitem = self.addItem(
                item.name() if newName is None else newName,
                item.description()
                if newDescription is None else newDescription,
                item.content() if newContent is None else newContent,
                newAccess, item.metadata())
            # all auxiliary files MUST BE COPIED before deleting original item
            # icon:
            id, filename = newitem.id().split('@', 1)
            if 'iconpixmap' in item.metadata(
            ) and 'iconfullname' in item.metadata(
            ) and 'icondata' in item.metadata():
                data = {
                    'files': {
                        item.metadata()['iconfullname']: {
                            'content': item.metadata()['icondata']
                        }
                    }
                }
                req = urllib2.Request('https://api.github.com/gists/%s' % id,
                                      json.dumps(data),
                                      headers=self.__headers)
                req.get_method = lambda: 'PATCH'
                code, rep = urlopen_nt(req)
                if (code != 200):
                    if (code == 403): raise InvalidToken('github auth failed')
                    raise CollectionSyncError(
                        "unexpected server return level %d" % code)

            self.removeItem(
                copy.copy(item)
            )  # remove the copy cuz item gets invalidated and we dont want that for original item
            item._name = newitem._name
            item._desc = newitem._desc
            item._meta['raw_url'] = newitem._meta['raw_url']
            item._meta['nettype'] = newitem._meta['nettype']
            item._id = newitem._id
            item._access = newitem._access
            item._readonly = newitem._readonly

            # if access is changed - we have to destroy this gist and create a new one with proper 'public' key
            # Butt Beware - we need to modify item's contents and return it WITHOUT reassigning the item itself
            # That's what we are doing here currently

            return

        if 'nettype' not in item.metadata():
            item.invalidate()
            raise CollectionItemInvalidError(
                'required metadata was not found in the item')

        id, filename = item.id().split('@', 1)
        data = {}
        proceed = False
        if (newName is not None):
            if filename.startswith(
                    'item:'
            ):  # new format. can cause trouble if someone actually called item starting with 'item:'
                data['filename'] = 'item:' + newName
            else:  # old format
                data['filename'] = newName
            proceed = True
        if (newContent is not None):
            data['content'] = newContent
            proceed = True
        if (data != {}):
            data = {'files': {filename: data}}

        if (newDescription is not None):
            data['description'] = ':'.join(
                (item.metadata()['nettype'], newDescription))
            proceed = True

        if proceed:
            req = urllib2.Request('https://api.github.com/gists/%s' % id,
                                  json.dumps(data),
                                  headers=self.__headers)
            req.get_method = lambda: 'PATCH'
            code, rep = urlopen_nt(req)
            if (code != 200):
                if (code == 403): raise InvalidToken('github auth failed')
                raise CollectionSyncError("unexpected server return level %d" %
                                          code)

            gist = json.loads(rep.read())
            newfilenames = gist['files'].keys()
            newfilenames.remove('00_HPASTE_SNIPPET')
            if (len(newfilenames) == 1):
                newfilename = newfilenames[0]
                newname = newfilename
            else:
                itemfileanmes = [
                    x for x in newfilenames if x.startswith("item:")
                ]
                if len(itemfileanmes) != 1:
                    raise CollectionInconsistentError(
                        'something went wrong during item creation: could not find unique item data in gist'
                    )
                newfilename = itemfileanmes[0]
                newname = newfilename.split(':', 1)[1]
            desc = gist['description']
            nettype = ''
            if (':' in desc):
                nettype, desc = desc.split(':', 1)
            item._desc = desc
            item._name = newname
            item._meta['raw_url'] = gist['files'][newfilename]['raw_url']
            item._meta['nettype'] = nettype
            item._id = '%s@%s' % (gist['id'], newfilename)
            item._access = CollectionItem.AccessType.public if gist[
                'public'] else CollectionItem.AccessType.private
            item._readonly = False

        # metadata changes processing
        if metadataChanges:
            metaspecialkeys = [
                'raw_url', 'nettype', 'icondata', 'iconfullname', 'iconpixmap',
                'iconfullname', 'icondata'
            ]
            #if 'icondata' in metadataChanges and ('iconfullname' in item.metadata() or 'iconfullname' in metadataChanges):
            # Shall i implement this case? for when qt is not loaded
            if 'iconpixmap' in metadataChanges and qtAvailable:
                pix = metadataChanges['iconpixmap']
                if pix is None:  # removing pixmap
                    if 'iconpixmap' in item.metadata():
                        data = {
                            'files': {
                                item.metadata()['iconfullname']: None
                            }
                        }
                        req = urllib2.Request(
                            'https://api.github.com/gists/%s' %
                            item.id().split('@', 1)[0],
                            json.dumps(data),
                            headers=self.__headers)
                        req.get_method = lambda: 'PATCH'
                        code, rep = urlopen_nt(req)
                        if (code != 200):
                            if (code == 403):
                                raise InvalidToken('github auth failed')
                            raise CollectionSyncError(
                                "unexpected server return level %d" % code)
                        rep.close()
                        del item._meta['iconpixmap']
                        del item._meta['iconfullname']
                        del item._meta['icondata']
                else:
                    barr = QByteArray()
                    buff = QBuffer(barr)
                    pix.save(buff, "PNG")
                    imagedata = base64.b64encode(barr.data())
                    buff.deleteLater()

                    oldiconname = item.metadata().get('iconfullname', None)
                    newiconname = 'icon:PNG-base64:autoicon'

                    data = {'files': {}}
                    if oldiconname is not None and oldiconname != newiconname:
                        data['files'][oldiconname] = None

                    data['files'][newiconname] = {'content': imagedata}
                    req = urllib2.Request('https://api.github.com/gists/%s' %
                                          item.id().split('@', 1)[0],
                                          json.dumps(data),
                                          headers=self.__headers)
                    req.get_method = lambda: 'PATCH'
                    code, rep = urlopen_nt(req)
                    if (code != 200):
                        if (code == 403):
                            raise InvalidToken('github auth failed')
                        raise CollectionSyncError(
                            "unexpected server return level %d" % code)
                    replydict = json.loads(rep.read())

                    if newiconname not in replydict['files']:
                        raise CollectionSyncError(
                            "icon file was not uploaded properly")

                    globalIconCacher[replydict['files'][newiconname]
                                     ['raw_url']] = imagedata
                    item._meta['iconfullname'] = newiconname
                    item._meta['icondata'] = imagedata
                    item._meta['iconpixmap'] = pix

            for metakey in metadataChanges.keys():
                # All special cases are taken care of, so now just blind copy all remaining changes
                if metakey in metaspecialkeys: continue
                item._meta[metakey] = metadataChanges[metakey]
Пример #29
0
 def load_string(self, string, parent=None):
     """Load a UI file from a string and return the widget"""
     data = QByteArray(string.encode('utf-8'))
     buf = QBuffer(data)
     return self.load(buf, parent)