322 lines
8.1 KiB
Python
322 lines
8.1 KiB
Python
#550W 工具箱
|
|
#所需模块
|
|
#UI库
|
|
import tkinter.filedialog as tf
|
|
import tkinter.messagebox as tm
|
|
import tkinter.constants as Keys
|
|
import tkinter.ttk as ttk
|
|
import tkinter as tk
|
|
import os
|
|
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"]=""#阻止pygame-print
|
|
import pygame
|
|
try:
|
|
pygame.mixer.init()
|
|
except:
|
|
print("PyGame InIt Error")
|
|
#系统库
|
|
import tempfile
|
|
import sys,os
|
|
from io import BytesIO
|
|
import platform
|
|
import getpass
|
|
import psutil
|
|
import shutil
|
|
import traceback
|
|
import ctypes
|
|
import wmi
|
|
u32=ctypes.windll.user32
|
|
#文件库
|
|
import configparser
|
|
import zipfile
|
|
import json
|
|
#编码库
|
|
import binascii
|
|
import hashlib
|
|
import base64
|
|
import uuid
|
|
import re
|
|
#进程库
|
|
from threading import Thread
|
|
import asyncio
|
|
import subprocess
|
|
import pystray
|
|
#时间库
|
|
import datetime,time
|
|
#图像库
|
|
from PIL import Image,ImageTk,ImageDraw
|
|
import cv2
|
|
#网页库
|
|
import urllib
|
|
import flask
|
|
import flask_socketio
|
|
#数学库
|
|
import random
|
|
import numpy
|
|
import math
|
|
import copy
|
|
#音频库
|
|
import pyaudio
|
|
import wave
|
|
|
|
|
|
#基础变量
|
|
temp=os.environ["temp"]
|
|
#Windows管理接口
|
|
WindowsManagementInterface=wmi.WMI()
|
|
|
|
#UUID
|
|
def GUUID():
|
|
return str(uuid.uuid3(uuid.NAMESPACE_DNS, str(random.randint(0, 10000000000000000000))))
|
|
# 读/写/添
|
|
def openw(file, write, mode="1", encoding="UTF-8"):
|
|
if mode == "1" or mode == 1:
|
|
with open(file, "w", encoding=encoding) as f:
|
|
f.write(write)
|
|
elif mode == "2" or mode == 2:
|
|
with open(file, "wb") as f:
|
|
f.write(write)
|
|
|
|
def opena(file, write, mode="1", encoding="UTF-8"):
|
|
if mode == "1" or mode == 1:
|
|
with open(file, "a", encoding=encoding) as f:
|
|
f.write(write)
|
|
elif mode == "2" or mode == 2:
|
|
with open(file, "ab") as f:
|
|
f.write(write)
|
|
|
|
def openr(file, mode="1", encoding="UTF-8"):
|
|
if mode == "1" or mode == 1:
|
|
with open(file, "r", encoding=encoding) as f:
|
|
read = f.read()
|
|
elif mode == "2" or mode == 2:
|
|
with open(file, "rb") as f:
|
|
read = f.read()
|
|
return read
|
|
|
|
def MakeTempFile(write):
|
|
tmp_file = tempfile.NamedTemporaryFile(delete=True)
|
|
tmp_file.write(write)
|
|
tmp_file.close()
|
|
return tmp_file
|
|
|
|
def MakeTempFilePattern(suffix=".tmp",delete=True):
|
|
with tempfile.NamedTemporaryFile(suffix='.png', delete=delete) as tmp_file:
|
|
return tmp_file
|
|
|
|
#MP3播放
|
|
def MP3Play(mp3_path,volume=10,sleep=-1):
|
|
pygame.mixer.music.load(mp3_path) # 加载音乐
|
|
pygame.mixer.music.set_volume(volume)# 设置音量大小0~1的浮点数
|
|
pygame.mixer.music.play() # 播放音频
|
|
if sleep == -1:
|
|
time.sleep(get_duration_wave(mp3_path))
|
|
else:
|
|
time.sleep(sleep)
|
|
|
|
#MP3时间获取
|
|
def get_duration_wave(file_path):
|
|
with wave.open(file_path, "r") as audio_file:
|
|
frame_rate = audio_file.getframerate()
|
|
n_frames = audio_file.getnframes()
|
|
duration = n_frames / float(frame_rate)
|
|
return duration
|
|
|
|
#时间格式化
|
|
def TimeFormat(s,end=""):
|
|
return time.strftime("[%Y/%m/%d %H:%M:%S]: "+str(s)+end, time.localtime())
|
|
|
|
def TimeFormatStr(s="%Y/%m/%d %H:%M:%S",end=""):
|
|
return time.strftime(s+end, time.localtime())
|
|
|
|
def TimeFormatv(make_uuid=True):
|
|
return datetime.datetime.now().strftime("%Y年%m月%d日-%H时%M分%S秒%f毫"+"-"+str(uuid.uuid3(uuid.NAMESPACE_DNS, str(random.randint(0, 10000000000000000000)))))
|
|
|
|
def Is_TrueColorCode(code):
|
|
pattern = re.compile(r'^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$')
|
|
return bool(pattern.match(code))
|
|
|
|
#Base64转图片
|
|
def base64_to_image(base64_str: str) -> Image.Image:
|
|
base64_data = re.sub("^data:image/.+;base64,", "", base64_str)
|
|
byte_data = base64.b64decode(base64_data)
|
|
image_data = BytesIO(byte_data)
|
|
img = Image.open(image_data)
|
|
return img
|
|
|
|
#图片转Base64
|
|
def image_to_base64(image: Image.Image, fmt="png") -> str:
|
|
output_buffer = BytesIO()
|
|
image.save(output_buffer, format=fmt)
|
|
byte_data = output_buffer.getvalue()
|
|
base64_str = base64.b64encode(byte_data).decode("utf-8")
|
|
return f"data:image/{fmt};base64," + base64_str
|
|
|
|
#返回"没有文件"错误类型
|
|
def ReturnFileNotFoundError(InFo,file):
|
|
ERROR=FileNotFoundError(InFo)
|
|
ERROR.filename=file
|
|
|
|
#判断ini文件是否正确
|
|
def IS_INI(ini_file):
|
|
#创建ConfigParser对象
|
|
config = configparser.ConfigParser()
|
|
#读取INI文件
|
|
try:
|
|
#尝试读取
|
|
config.read(ini_file)
|
|
except configparser.Error as e:
|
|
#报错
|
|
return False
|
|
else:
|
|
#没有报错
|
|
return True
|
|
|
|
#ini转字典
|
|
def INI2DICT(ini_file):
|
|
#创建ConfigParser对象
|
|
config = configparser.ConfigParser()
|
|
#读取INI文件
|
|
config.read(ini_file)
|
|
#创建二级字典
|
|
config_dict = {}
|
|
#遍历INI文件的sections
|
|
for section in config.sections():
|
|
#创建子字典
|
|
section_dict = {}
|
|
#遍历每个section中的options
|
|
for option in config.options(section):
|
|
#将选项和值添加到子字典中
|
|
section_dict[option] = config.get(section, option)
|
|
#将子字典添加到二级字典中
|
|
config_dict[section] = section_dict
|
|
#返回文件
|
|
return config_dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def WriteToFile(content, filename):
|
|
with open(filename, "wb") as f:
|
|
f.write(content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#信息结构体
|
|
class InFo:
|
|
def __init__(self):
|
|
pass
|
|
|
|
#异步装饰器
|
|
def asyncs(f):
|
|
def wrapper(*args, **kwargs):
|
|
thr = Thread(target = f, args = args, kwargs = kwargs)
|
|
thr.start()
|
|
return wrapper
|
|
|
|
|
|
#获取多个文件MD5(自匹配)
|
|
def GetFilesMD5(*file_paths):
|
|
md5_list = []
|
|
for file_path in file_paths:
|
|
md5_list.append(GetFileMD5(file_path))
|
|
return md5_list
|
|
|
|
def GetFileMD5(file_name):
|
|
"""
|
|
计算文件的md5
|
|
:param file_name:
|
|
:return:
|
|
"""
|
|
m = hashlib.md5()
|
|
with open(file_name,'rb') as fobj:
|
|
while True:
|
|
data = fobj.read(4096)
|
|
if not data:
|
|
break
|
|
m.update(data)
|
|
return m.hexdigest()
|
|
def GetStrMD5(content):
|
|
"""
|
|
计算字符串md5
|
|
:param content:
|
|
:return:
|
|
"""
|
|
m = hashlib.md5(content)
|
|
return m.hexdigest()
|
|
def GetDirFileMD5(Dir):
|
|
"""
|
|
计算文件夹所有文件(二枝树算法)
|
|
:param Dir:
|
|
:return list:
|
|
"""
|
|
MD5S=[]
|
|
if not os.path.isdir(Dir):
|
|
#No Use raise
|
|
return FileNotFoundError()
|
|
for i in os.listdir(Dir):
|
|
if os.path.isfile(os.path.normpath(Dir+"/"+i)):
|
|
MD5S.append({"FileName":os.path.normpath(Dir+"/"+i),"Type":"File","MD5":GetFileMD5(os.path.normpath(Dir+"/"+i))})
|
|
if os.path.isdir(os.path.normpath(Dir+"/"+i)):
|
|
MD5S.append({"FileName":os.path.normpath(Dir+"/"+i),"Type":"Dir","ChildRen":GetDirFileMD5(os.path.normpath(Dir+"/"+i))})
|
|
return MD5S
|
|
|
|
def IsDirFileMD5(MD5List,Dir,Bind=lambda x:None,sleep=0):
|
|
for i in MD5List:
|
|
s=copy.deepcopy(i)
|
|
s["ChildRen"]="Pass"
|
|
Bind(s["FileName"])
|
|
time.sleep(sleep)
|
|
if i["Type"]=="File":
|
|
if not os.path.isfile(i["FileName"]):
|
|
return False,1,i["FileName"]
|
|
if not GetFileMD5(i["FileName"]) == i["MD5"]:
|
|
return False,2,i["FileName"]
|
|
if i["Type"]=="Dir":
|
|
if not os.path.isdir(i["FileName"]):
|
|
return False,3,i["FileName"]
|
|
Thing=IsDirFileMD5(i["ChildRen"],i["FileName"],Bind,sleep)
|
|
if not Thing[0]:
|
|
return False,4,i["FileName"],Thing
|
|
return (True,1)
|
|
|
|
|
|
#获取所有可用的摄像头设备
|
|
def get_available_cameras():
|
|
camera_list = []
|
|
index = 0
|
|
while True:
|
|
cap = cv2.VideoCapture(index)
|
|
if not cap.read()[0]:
|
|
break
|
|
else:
|
|
camera_list.append(index)
|
|
cap.release()
|
|
index += 1
|
|
return camera_list
|
|
|
|
class Mod_Var():
|
|
def __init__(self):
|
|
self.Global={}
|
|
|
|
|
|
class FileVarToVar():
|
|
def __init__(self,Var):
|
|
N2={}
|
|
if not type(Var) == type({}):
|
|
raise TypeError("Var Not Is Dict")
|
|
for i in Var:
|
|
if len(i) > 2:
|
|
if not i[0:2] == "__":
|
|
if not i[-2:] == "__":
|
|
N2[i]=Var[i]
|
|
self.Global=N2
|
|
ToolsGlobalVar=FileVarToVar(globals())
|
|
ToolsGlobal=ToolsGlobalVar.Global
|