程序使用Python语言编写,实现如下功能:截图,通过微软数学的接口识别出latex代码,自动复制到剪贴板
本程序借鉴了https://www.52pojie.cn/thread-1179096-1-1.html(@Captain-Li)的思路和接口,并放出源代码。
以下为import,用到了:requests,time,json,pybase64,PIL,pyperclip,win10toast(下文有详细解释)
import requests
import time
import json
import pybase64
from PIL import Image, ImageGrab
import pyperclip
from win10toast import ToastNotifier
以下为截图功能实现,监控剪贴板中是否有图片,利用PIL库功能实现
[Python] 纯文本查看 复制代码 def GetPhotoFromGrab():
im = ImageGrab.grabclipboard()
if isinstance(im, Image.Image):
with open(r"C:\SnipasteBackup\1.png", "w+"):
im.save(r"C:\SnipasteBackup\1.png")
return 0
else:
return 1
以下为识别功能实现以及接口(接口可以详细看那位大佬的帖子):
这里我用了Pybase64库,因为原生的base64总是提示我错误信息:“number of data characters (217) cannot be 1 more than a multiple of 4”,试了几个办法也没有奏效
timestamp是时间戳,用的是原生的time库
[Python] 纯文本查看 复制代码 def GetLatex():
with open(r"C:\SnipasteBackup\1.png", "rb") as f:
Image_data = pybase64.b64encode(f.read())
url = "https://www.bing.com/cameraexp/api/v1/getlatex"
headers = {
"Host": "www.bing.com",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Math/1 CFNetwork/1121.2.2 Darwin/19.3.0",
}
base64 = Image_data.decode('utf-8')
data = {
"data": base64,
"inputForm": "Image",
"clientInfo": {
"app": "Math",
"platform": "ios",
"configuration": "UnKnown",
"version": "1.8.0",
"mkt": "zh-cn"
},
"timestamp": int(time.time())
}
Html = requests.post(url, headers=headers, json=data)
Result = json.loads(Html.text)
if Result["latex"] != '':
return Result["latex"]
else:
return 1
以下为主函数逻辑:
用了一个win10toast库,用于提示识别成功,在右下角弹出一个提示框
以及pyperclip库,将识别后的代码复制到剪贴板
[Python] 纯文本查看 复制代码 def main():
print(r"调用微软数学接口,识别latex文本并复制")
print(time.asctime(time.localtime(time.time())))
print(r"当前截图保存在C:\SnipasteBackup下")
print(r"已开始监听剪贴板,每3秒尝试进行1次识别")
print(r"--------------------------------")
i = 1
print("\n等待图片输入......")
while True:
s1 = GetPhotoFromGrab()
if s1 == 0:
s2 = GetLatex()
if s2 == 1:
# print("未识别到有效文字")
time.sleep(3)
else:
print("---------------------------------")
print("第{}次识别,时间戳:{}".format(i, time.strftime("%Y-%m-%d %X", time.localtime())))
i += 1
print("代码如下:{}".format(s2))
toaster = ToastNotifier()
toaster.show_toast("识别完成",
"代码已复制到剪贴板",
icon_path=None,
duration=2)
print("---------------------------------")
print("已复制至剪贴板中")
pyperclip.copy("$ " + s2 + " $")
time.sleep(5)
# print(1)
else:
time.sleep(3)
s1 = s2 = ''
本人小白一枚,论坛的各位大佬见笑了。
不提供成品程序。 |