其他分享
首页 > 其他分享> > 调用Mathpix API 自制Mathpix snipping (每月1000次免费!!!)

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

作者:互联网


相信大家都知道mathpix吧

一款特别的牛逼的img2latex软件

如果有小伙伴不知道的话可以看我之前的博客

超级利器——mathpix 文本、图片公式转md/latex格式

牛逼虽说是牛逼,但是对于普通的用户来说每个月只有50次免费的机会

剩下的还得靠克金……


让我们看一下官网的价格

在这里插入图片描述

虽说这几天美元贬值,但是算下来还是得每月二三十

像我这样节俭的人

……对,我就是穷,能把我咋滴( ﹁ ﹁ ) ~→


但是官方还是非常友好的,开放了API,让像我这样的开发者(qb)有了机遇

看一下API的价格

在这里插入图片描述

每个月前1000次免费!!!

这对于普通人来说真的够用了

下面我通过调用官方给出的API写了个精简版的mathpix snipping


效果

在这里插入图片描述


功能如下


本来还写了latex2img的部分,但是运行的不太稳定

已经把那部分注释掉了,思路是用matplotlib中的自带的显示latex公式,然后将横纵坐标轴去掉

plt.text然后调整一下文字的显示位置和文字的大小等属性


话不多说直接上动画

在这里插入图片描述

看起来效果还不错

下面就是教学时间了

在这里插入图片描述

一、注册API接口账号

先注册一个mathpix的账号

https://dashboard.mathpix.com/login

在这里插入图片描述

然后需要接受一个激活的协议

在这里插入图片描述

下面就是输入信用卡激活了

在这里插入图片描述

之后就可以看到账户的信息啦

在这里插入图片描述

这两个我们待会要用到

接下来就要调用接口了

这里给出官方的接口文档https://docs.mathpix.com

还有有一些API的示例

https://github.com/Mathpix/api-examples

二、敲代码

我用的是python实现的,用pyqt5 做UI界面,再用qss加了一定的美化


结构目录

在这里插入图片描述

用到的包

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 ImageGrab
import pyperclip
import matplotlib.pyplot as plt

核心代码

env = os.environ

default_headers = {
    'app_id': env.get('APP_ID', '你的APP_ID'),
    'app_key': env.get('APP_KEY', '你的APP_KEY'),
    'Content-type': 'application/json'
}

service = 'https://api.mathpix.com/v3/latex'
   	#
    # Return the base64 encoding of an image with the given filename.
    #
	def image_uri(self,filename):
        image_data = open(filename, "rb").read()
        return "data:image/jpg;base64," + base64.b64encode(image_data).decode()

    # Call the Mathpix service with the given arguments, headers, and timeout.
    def latex(self,args, headers=default_headers, timeout=30):
        r = requests.post(service,
                          data=json.dumps(args), headers=headers, timeout=timeout)
        return json.loads(r.text)

    def convert(self):
        
        r = self.latex({
             'src':self.image_uri(r".\img\equa.png"),
             'formats': ['latex_simplified']
        })
        
        print(r['latex_simplified'])
        
        latex1 = r['latex_simplified']
        latex2 = '$' + latex1 + '$'
        latex3 = '$$' + latex1 + '$$'
        self.Latex1Edit.setText(latex1)
        self.Latex2Edit.setText(latex2)
        self.Latex3Edit.setText(latex3)
        
    #
    # 识别剪贴板公式
    #
    def grapclipboard(self):
        im = ImageGrab.grabclipboard()
        im.save(r'.\img\equa.png', 'PNG')
        self.imgLable.setPixmap(PyQt5.QtGui.QPixmap(r'.\img\equa.png'))

完整代码

# coding:utf-8
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 ImageGrab
import pyperclip
import matplotlib.pyplot as plt

env = os.environ

default_headers = {
    'app_id': env.get('APP_ID', '你的APP_ID'),
    'app_key': env.get('APP_KEY', '你的APP_KEY'),
    'Content-type': 'application/json'
}

service = 'https://api.mathpix.com/v3/latex'

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)

        # edit latex
        # self.Latex1EditBtn.clicked.connect(self.Latex1EditImg)
        # self.Latex1Edit.textChanged.connect(self.Latex1EditImg)

        # self.Latex2EditBtn.clicked.connect(self.Latex2EditImg)
        # self.Latex2Edit.textChanged.connect(self.Latex2EditImg)

        # self.Latex3EditBtn.clicked.connect(self.Latex3EditImg)
        # self.Latex3Edit.textChanged.connect(self.Latex3EditImg)

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

    def Beautify(self):
        self.setWindowOpacity(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;
                background-color:#555;
                font-size:24px;
                font-color:#fff;
                font-weight:700;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            }''')

    #
    # Return the base64 encoding of an image with the given filename.
    #

    def image_uri(self,filename):
        image_data = open(filename, "rb").read()
        return "data:image/jpg;base64," + base64.b64encode(image_data).decode()

    # Call the Mathpix service with the given arguments, headers, and timeout.
    def latex(self,args, headers=default_headers, timeout=30):
        r = requests.post(service,
                          data=json.dumps(args), headers=headers, timeout=timeout)
        return json.loads(r.text)

    def convert(self):
        self.grapclipboard()
        r = self.latex({
            'src':self.image_uri(r".\img\equa.png"),
            'formats': ['latex_simplified']
        })
        # print(r['latex_simplified'])
        latex1 = r['latex_simplified']

        # test
        # latex1='111'
        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()
        im.save(r'.\img\equa.png', 'PNG')
        self.imgLable.setPixmap(PyQt5.QtGui.QPixmap(r'.\img\equa.png'))

    #
    # 为程序添加快捷键
    #
	# 可以自己定义
    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_())

篇幅有限latex2img部分我已经去掉了

有兴趣的小伙伴可以在我的github上获得完整版资源

地址
https://github.com/Joshua-li-yi/img2latex

所有的接口调用记录可以在这个地址获取

https://dashboard.mathpix.com/user-data

在这里插入图片描述


三、最后

如果觉得此文对你有帮助,请各位大大们给个三连,让更多的童鞋可以看到

谢谢老铁们的支持~~

标签:latex,Mathpix,self,PyQt5,API,snipping,import,border,def
来源: https://blog.csdn.net/weixin_44984664/article/details/105242426