2020-12-18

Python调用Mathpix API 自制Mathpix snipping (每月1000次免费!!!)

申请账号的方法,参见下面链接:
https://blog.csdn.net/weixin_44984664/article/details/105242426

其博客的完整代码在这里:
https://github.com/Joshua-li-yi/img2latex

可以下载保存,但其中的代码不能运行。

以Mathpix API说明文档为基础,参考上面博客的界面,整合出下面代码,在Anaconda下调试成功,操作系统是Win10。

在Anaconda的你设定默认目录下建一个子目录img,把上面博客完整代码中的copy.png、edit.png复制到目录img就可以了。

对于PyQt5.QtWidgets界面模块,我也不熟悉,未能修改,有兴趣有能力的朋友可以自行修改。

#不保存文件,直接识别公式
#申请账号的方法,参见下面链接,但其中的代码不能运行,我在其基础上弄活了。
#https://blog.csdn.net/weixin_44984664/article/details/105242426

import sys
import os
import base64
import requests
import json
import PyQt5.QtGui
import PyQt5.QtCore
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QWidget, QGridLayout, QLineEdit
from PyQt5.QtCore import Qt
from PIL import Image,ImageGrab
import pyperclip
import matplotlib.pyplot as plt
from io import BytesIO

env = os.environ


class Img2Latex(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 800, 700)
        self.setWindowTitle('Img2Latex')

        # copy latex
        self.Latex1copyBtn = QPushButton()
        self.Latex2copyBtn = QPushButton()
        self.Latex3copyBtn = QPushButton()
        # set copy btn icon
        self.Latex1copyBtn.setIcon(PyQt5.QtGui.QIcon(r"img/copy.png"))
        self.Latex2copyBtn.setIcon(PyQt5.QtGui.QIcon(r"img/copy.png"))
        self.Latex3copyBtn.setIcon(PyQt5.QtGui.QIcon(r"img/copy.png"))

        # edit latex
        self.Latex1EditBtn = QPushButton()
        self.Latex2EditBtn = QPushButton()
        self.Latex3EditBtn = QPushButton()
        # set edit btn icon
        self.Latex1EditBtn.setIcon(PyQt5.QtGui.QIcon(r"img/edit.png"))
        self.Latex2EditBtn.setIcon(PyQt5.QtGui.QIcon(r"img/edit.png"))
        self.Latex3EditBtn.setIcon(PyQt5.QtGui.QIcon(r"img/edit.png"))

        # img to latex convert btn
        self.img2latexBtn = QPushButton('convert')

        # show the picture on clipboard
        self.imgLable = QLabel()

        # show the formula in latex
        self.Latex1Edit = QLineEdit()
        self.Latex2Edit = QLineEdit()
        self.Latex3Edit = QLineEdit()
        self.Latex1Edit.setEnabled(False)
        self.Latex2Edit.setEnabled(False)
        self.Latex3Edit.setEnabled(False)

        # # show the convert latex result
        # self.reviewImgLable = QLabel()
        # self.reviewImgLable.setStyleSheet("border: 2px solid red")

        grid = QGridLayout()
        grid.setSpacing(20)

        # 排版
        grid.addWidget(self.imgLable, 1, 0, 5, 3)

        grid.addWidget(self.img2latexBtn,6,0,1,2)

        grid.addWidget(self.Latex1Edit, 7, 0)
        grid.addWidget(self.Latex1copyBtn, 7, 1)
        # grid.addWidget(self.Latex1EditBtn, 7, 2)

        grid.addWidget(self.Latex2copyBtn, 8, 1)
        grid.addWidget(self.Latex2Edit, 8, 0)
        # grid.addWidget(self.Latex2EditBtn, 8, 2)

        grid.addWidget(self.Latex3copyBtn, 9, 1)
        grid.addWidget(self.Latex3Edit, 9, 0)
        # grid.addWidget(self.Latex3EditBtn, 9, 2)

        # grid.addWidget(self.reviewImgLable, 10, 0, 4, 3)

        self.setLayout(grid)

        # sign and slot

        # img to latex convert
        self.img2latexBtn.clicked.connect(self.convert)

        # copy latex
        self.Latex1copyBtn.clicked.connect(self.copyLatex1)
        self.Latex2copyBtn.clicked.connect(self.copyLatex2)
        self.Latex3copyBtn.clicked.connect(self.copyLatex3)
       

        # beautify the window
        self.Beautify()
        self.show()

    def Beautify(self):
        self.setWindowOpacity(1)  # 设置窗口透明度 0.9
        # self.setAttribute(qtpy.QtCore.Qt.WA_TranslucentBackground) # 设置窗口背景透明
        # self.setWindowFlag(qtpy.QtCore.Qt.FramelessWindowHint) # 隐藏边框
        pe = PyQt5.QtGui.QPalette()
        self.setAutoFillBackground(True)
        # pe.setColor(PyQt5.QtGui.QPalette.Window, Qt.Black)  #设置背景色
        pe.setColor(PyQt5.QtGui.QPalette.Background, Qt.black)
        self.setPalette(pe)
        
        self.imgLable.setStyleSheet(
            ''' QLabel{
                border: 2px solid red;
                border-radius:15px;
                padding:2px 4px;
                background-color:#aaa;
            }''')
        
        self.Latex1Edit.setStyleSheet(
            '''QLineEdit{
                border:1px solid gray;
                border-radius:10px;
                padding:2px 4px;
                background-color:#ddd;
                height:35px;
                font-color:black;
                font-weight:1000;
                font-size:24px
            }''')
        self.Latex2Edit.setStyleSheet(
            '''QLineEdit{
                border:1px solid gray;
                border-radius:10px;
                padding:2px 4px;
                background-color:#ddd;
                height:35px;
                font-color:black;
                font-weight:1000;
                font-size:24px
            }''')
        self.Latex3Edit.setStyleSheet(
            '''QLineEdit{
                border:1px solid gray;
                border-radius:10px;
                padding:2px 4px;
                background-color:#ddd;
                height:35px;
                font-color:black;
                font-weight:1000;
                font-size:24px
            }''')

        self.Latex1copyBtn.setStyleSheet(
            '''QPushButton{
                border:1px solid gray;
                border-radius:4px;
                padding:5px 5px;
                height:35px

            }''')
        self.Latex2copyBtn.setStyleSheet(
            '''QPushButton{
                border:1px solid gray;
                border-radius:4px;
                padding:5px 5px;
                height:35px
            }''')
        self.Latex3copyBtn.setStyleSheet(
            '''QPushButton{
                border:1px solid gray;
                border-radius:4px;
                padding:5px 5px;
                height:35px
            }''')

        self.img2latexBtn.setStyleSheet(
            '''QPushButton{
             (   border:2px solid gray;
                border-radius:10px;
                padding:5px 5px;
                height:35px   
                background-color:#555;
                font-size:24px;
                font-color:#fff;
                font-weight:700;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            }''')
        
   
    def convert(self):
        
        image_uri=self.grapclipboard()  
        
        if image_uri:
        
            r = requests.post("https://api.mathpix.com/v3/text",
                data=json.dumps({'src': image_uri}),
                headers={"app_id": "你的id", "app_key": "你的密码",
                             "Content-type": "application/json"})

            #print(json.dumps(json.loads(r.text), indent=4, sort_keys=True))

            rd = json.loads(r.text)
            latex1 = rd["latex_styled"]        
            print(latex1)        
            latex2 = '$' + latex1 + '$'
            latex3 = '$$' + latex1 + '$$'
            self.Latex1Edit.setText(latex1)
            self.Latex2Edit.setText(latex2)
            self.Latex3Edit.setText(latex3)

    def copyLatex1(self):
        # get the latex formula
        text = self.Latex1Edit.text()
        # copy it to clipboard
        pyperclip.copy(text)

    def copyLatex2(self):
        text = self.Latex2Edit.text()
        pyperclip.copy(text)

    def copyLatex3(self):
        text = self.Latex3Edit.text()
        pyperclip.copy(text)
        
     # 识别剪贴板公式
    def grapclipboard(self):
        im = ImageGrab.grabclipboard()
        
        if isinstance(im, Image.Image):
            px = im.load()
            #展示图片
            self.imgLable.setPixmap(QApplication.clipboard().pixmap())
            
            img_buffer = BytesIO()
            w, h = im.size
            # image.thumbnail((128, 128))
            im.save(img_buffer, format='JPEG', quality=95)
            byte_data = img_buffer.getvalue()                        
            base64_str = base64.b64encode(byte_data)            
            msg = str(base64_str)
            image_uri = 'data:image/png;base64,' + msg[2:-2]
            return image_uri
            
        elif im:#如果是文件名
            for filename in im:
                try:
                    print("filename: %s" % filename)  
                    #提取图片文件并展示
                    self.imgLable.setPixmap(PyQt5.QtGui.QPixmap(filename))
                    image_uri = "data:image/png;base64," + base64.b64encode(open(filename, "rb").read()).decode()
                    return image_uri
                except IOError:
                    pass #ignore this file
                else:
                    print("ImageList: size : %s, mode: %s" % (im.size, im.mode)) 
        else:
            print("clipboard is empty.")
            return 

    #
    # 为程序添加快捷键
    #
    # 可以自己定义
    def keyPressEvent(self, event):
        if (event.key() == Qt.Key_T)and(event.modifiers() == Qt.AltModifier):
            self.convert()
        if (event.key() == Qt.Key_C)and(event.modifiers() == Qt.AltModifier):
            self.copyLatex3()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Img2Latex()
    sys.exit(app.exec_())

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值