Beispiel #1
0
class Result(QWidget):
    def __init__(self, parent=None):
        super(Result, self).__init__(parent)
        self.capture = Capture(None)
        self.draw = Canvas(None)
        self.setAcceptDrops(True)
        self.setWindowIcon(QIcon("favicon.ico"))
        # region WindowSettings
        self.setFixedWidth(600)
        self.setWindowTitle("MathPix+")
        self.setWindowFlags(Qt.MSWindowsFixedSizeDialogHint
                            | Qt.WindowCloseButtonHint
                            | Qt.WindowStaysOnTopHint)
        # endregion
        # region Svg
        self.svg_container = QWidget()
        self.svg_container.setFixedSize(QSize(578, 200))
        self.svg = QSvgWidget(self.svg_container)
        # endregion
        # region Info Label
        self.label = QLabel()
        self.label.setFont(QFont("等线", 20))
        self.label.setMaximumHeight(30)
        self.label.setAlignment(Qt.AlignCenter)
        # endregion
        # region Image
        self.img = QLabel()
        self.img.setFixedSize(578, 200)
        self.img.setAlignment(Qt.AlignCenter)
        # endregion
        # region TeX LineEdit
        self.tex = QLineEdit()
        self.tex.setAlignment(Qt.AlignCenter)
        self.tex.setFont(QFont("Cambria Math", 20))
        self.tex.setMaximumHeight(60)
        self.tex.setPlaceholderText("Enter Your Tex Here")
        self.tex.setEchoMode(QLineEdit.Normal)
        self.tex.textChanged.connect(self.on_tex_changed)
        # endregion
        # region PushButtons
        self.save_as_raw_tex = QPushButton("&Raw")
        self.save_as_raw_tex.setFixedHeight(40)
        self.save_as_raw_tex.setFont(QFont("等线", 20))
        self.save_as_raw_tex.clicked.connect(
            lambda: self.copy_tex_to_clipboard(""))
        self.save_as_inline_tex = QPushButton("&Inline")
        self.save_as_inline_tex.setFixedHeight(40)
        self.save_as_inline_tex.setFont(QFont("等线", 20))
        self.save_as_inline_tex.clicked.connect(
            lambda: self.copy_tex_to_clipboard("$"))
        self.save_as_block_tex = QPushButton("&Block")
        self.save_as_block_tex.setFixedHeight(40)
        self.save_as_block_tex.setFont(QFont("等线", 20))
        self.save_as_block_tex.clicked.connect(
            lambda: self.copy_tex_to_clipboard("$$"))
        self.open_img = QPushButton("&Open")
        self.open_img.setFixedHeight(40)
        self.open_img.setFont(QFont("等线", 20))
        self.open_img.clicked.connect(lambda: self.get_tex(self.get_img()))
        self.snap_img = QPushButton("&Snap")
        self.snap_img.setFixedHeight(40)
        self.snap_img.setFont(QFont("等线", 20))
        self.snap_img.clicked.connect(self.capture_img)
        self.draw_img = QPushButton("&Draw")
        self.draw_img.setFixedHeight(40)
        self.draw_img.setFont(QFont("等线", 20))
        self.draw_img.clicked.connect(self.canvas_img)
        # endregion
        # region Layout
        self.copy_hlo = QHBoxLayout()
        self.open_hlo = QHBoxLayout()
        self.copy_hlo.addWidget(self.save_as_raw_tex)
        self.copy_hlo.addWidget(self.save_as_inline_tex)
        self.copy_hlo.addWidget(self.save_as_block_tex)
        self.open_hlo.addWidget(self.open_img)
        self.open_hlo.addWidget(self.snap_img)
        self.open_hlo.addWidget(self.draw_img)
        self.vlo = QVBoxLayout()
        self.vlo.addWidget(self.svg_container)
        self.vlo.addWidget(self.img)
        self.vlo.addWidget(self.label)
        self.vlo.addWidget(self.tex)
        self.vlo.addLayout(self.copy_hlo)
        self.vlo.addLayout(self.open_hlo)
        # endregion
        self.get_tex("")
        self.setLayout(self.vlo)

    def on_tex_changed(self):
        try:
            parser = math_text.MathTextParser('svg')
            parser.parse(r"$" + self.tex.text() + r"$")
        except ValueError:
            self.label.setText("TeX语法不正确")
        else:
            self.label.setText('')
            self.generate_svg(self.tex.text())

    def copy_tex_to_clipboard(self, string):
        clipboard = QApplication.clipboard()
        clipboard.setText(string + self.tex.text() + string)
        self.label.setText("TeX已复制至剪贴板")

    def generate_svg(self, raw_tex):
        fig = Figure(figsize=(5, 4), dpi=300)
        canvas = FigureCanvasAgg(fig)
        fig.text(.5, .5, r"$" + raw_tex + r"$", fontsize=40)
        fig.savefig("output.svg", bbox_inches="tight", facecolor=(1, 1, 1, 0))
        self.svg.load("output.svg")
        renderer = QSvgRenderer('output.svg').defaultSize()
        w = renderer.width()
        h = renderer.height()
        if w / h > 578 / 200:
            display_w = 578
            display_h = int(578 * h / w)
        else:
            display_h = 200
            display_w = int(200 * w / h)
        self.svg.setFixedWidth(display_w)
        self.svg.setFixedHeight(display_h)
        self.svg.setGeometry(
            QRect(289 - int(display_w / 2), 100 - int(display_h / 2),
                  display_w, display_h))

    def get_img(self):
        file_name, file_type = QFileDialog.getOpenFileName(
            self, "选取图片", "./", "所有文件 (*);;图片文件 (*.jpg *.png)")
        print(file_name, file_type)
        return file_name

    def get_tex(self, url=r"limit.jpg"):
        if url == "":
            self.set_data("limit.jpg",
                          r"\lim_{x\rightarrow3}(\frac{x^{2}+9}{x-3})", 1)
            return
        with open(url, 'rb') as pic:
            base64_data = base64.b64encode(pic.read())
            print(base64_data)
        img_url = "data:image/jpg;base64," + base64_data.decode()
        r = requests.post("https://api.mathpix.com/v3/latex",
                          data=json.dumps({'url': img_url}),
                          headers={
                              "app_id": "******",
                              "app_key": "********************************",
                              "Content-type": "application/json"
                          })
        print(json.dumps(json.loads(r.text), indent=4, sort_keys=True))
        try:
            raw_data = json.loads(r.text)
        except AttributeError:
            return
        else:
            if "latex" in raw_data:
                tex = raw_data["latex"]
            else:
                return
            if "latex_confidence" in raw_data:
                confidence = raw_data["latex_confidence"]
            else:
                confidence = 1

            self.set_data(url, tex, confidence)

    def set_data(self, img, tex, con):
        raw_img = QPixmap(img)
        w = raw_img.width()
        h = raw_img.height()
        if w / h > 578 / 200:
            self.img.setPixmap(
                raw_img.scaledToWidth(578, Qt.SmoothTransformation))
        else:
            self.img.setPixmap(
                raw_img.scaledToHeight(200, Qt.SmoothTransformation))

        tex_data = tex
        tex_data = tex_data.replace(r"\\", "\\")
        tex_data = tex_data.replace(' ', '')
        self.tex.setText(tex_data)
        self.generate_svg(tex_data)

        if con < 0.8:
            self.label.setText("置信值低于0.8, 建议进行人工校对 : ")

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls:
            event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        print("dropped")
        url = str(event.mimeData().urls()[0].toLocalFile())
        print(url)
        self.get_tex(url)

    def capture_img(self):
        self.capture.grab_new_img()
        self.capture.show()
        self.capture.captured.connect(lambda: self.get_tex("capture.jpg"))

    def canvas_img(self):
        self.draw.show()
        self.draw.drawn.connect(lambda: self.get_tex("canvas.jpg"))
class boot_screen(my_window):
    def __init__(self, parent, launcher):
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.launcher = launcher
        icon_str = "./images/missile.png"
        window_str = "Missile Command"
        self.setWindowTitle(window_str)
        self.add_icon(icon_str)
        self.determine_geometry()
        self.initUI(2, 2)

    def add_widgets(self):
        self.create_grid()
        self.add_usb_image()
        self.add_boot_label()

    def add_boot_label(self):
        self.boot_label = QLabel(parent=self)
        font = QFont('Droid Sans', 16)
        font.setBold(True)
        self.boot_label.setFont(font)
        text_color = QColor()
        text_color.setNamedColor(self.grey)
        pal = QPalette()
        pal.setColor(QPalette.WindowText, text_color)
        self.boot_label.setPalette(pal)
        self.grid.addWidget(self.boot_label, 0, 0, Qt.AlignCenter)
        self.update_boot_label()

    def add_usb_image(self):

        self.usb_image = QSvgWidget(parent=self)
        self.usb_image.image0 = './images/usb-0.svg'
        self.usb_image.image1 = './images/usb-1.svg'
        self.usb_image.max_height = self.h / 2
        self.grid.addWidget(self.usb_image, 1, 0, Qt.AlignHCenter)
        self.spacing_label = QLabel(parent=self)
        self.grid.addWidget(self.spacing_label, 2, 0, Qt.AlignCenter)
        self.update_usb_image()

    def update_usb_image(self):

        if (self.launcher.dev is None):
            self.usb_image.load(self.usb_image.image0)
            self.usb_image.aspect_ratio = 1.0
        else:
            self.usb_image.load(self.usb_image.image1)
            self.usb_image.aspect_ratio = 1.0

        height = self.usb_image.max_height
        width = height * self.usb_image.aspect_ratio
        self.usb_image.setFixedWidth(width)
        self.usb_image.setFixedHeight(height)
        self.animate_svg(self.usb_image)

    def update_boot_label(self):
        if (self.launcher.dev is None):
            self.boot_label.setText("Please insert your Tenx launcher")
        else:
            self.boot_label.setText("Welcome Commander")