本文主要是介绍umi-ocr识别文件夹所有文件并导入数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近有个需求是识别身份证所有信息。所以调用umi-ocr接口并写入mysql
import os
import glob
from time import sleep
import requests
import json
import pymysql
import tkinter as tk
from tkinter import ttkfrom sympy import truedef write_to_database(image_path, response_text, db_config):with pymysql.connect(**db_config) as conn:with conn.cursor() as cursor:sql = "INSERT INTO image_records (path, text) VALUES (%s, %s)"cursor.execute(sql, (image_path, response_text))conn.commit()def get_image_paths(directory, extensions=['.jpg', '.png']):image_paths = []for ext in extensions:pattern = os.path.join(directory, f'*{ext}')image_paths.extend(glob.glob(pattern))return image_pathsdef send_http_post_request(url, data, headers=None, auth=None):default_headers = {'Content-Type': 'application/json'}if headers is not None:headers = {**default_headers, **headers}else:headers = default_headersjson_data = json.dumps(data)response = requests.post(url, data=json_data, headers=headers, auth=auth)return responsedef returndata(directory, db_config):# 使用os.walk遍历目录for root, dirs, files in os.walk(directory):for filename in files:sleep(0.2)# 构建完整的文件路径file_path = os.path.join(root, filename)# 准备发送的数据post_data = ["--path", file_path]try:# 发送HTTP POST请求response = send_http_post_request("http://127.0.0.1:1224/argv", post_data)# 获取响应文本并替换换行符response_text = response.text.replace('\n', ',').replace('\t','')# 将响应写入数据库write_to_database(file_path, response_text, db_config)except Exception as e:# 打印异常信息,或者根据需要处理异常print(f"Error processing file {file_path}: {e}")return truedef on_click():global entry_directorydirectory = entry_directory.get()db_host = '127.0.0.1'db_port = 3306db_user = 'root'db_password = '123456'db_name = 'xxxxx'db_config = {'host': db_host,'port': db_port,'user': db_user,'password': db_password,'db': db_name}status = returndata(directory, db_config)if status:window.destroy()def main():global windowwindow = tk.Tk()window.title("OCR识别导入")window.geometry("400x200") # 设置窗口大小(可根据需要调整)# 添加标签和输入框label_directory = ttk.Label(window, text="请输入文件夹目录:", style="TLabel")label_directory.grid(row=0, column=0, padx=10, pady=(10, 5), sticky="w")global entry_directoryentry_directory = ttk.Entry(window, width=30, style="TEntry")entry_directory.grid(row=0, column=1, padx=(0, 10), pady=(10, 5), sticky="ew")# 添加执行按钮button_execute = ttk.Button(window, text="Execute", command=on_click, style="TButton")button_execute.grid(row=1, column=0, columnspan=2, padx=10, pady=10, ipadx=10, sticky="ew")window.mainloop()if __name__ == '__main__':main()
之后再利用
python -m pip install pyinstallerpython -m PyInstaller -F -w --compress test.py 打包成可执行程序
这篇关于umi-ocr识别文件夹所有文件并导入数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!