|
| 1 | +import atexit |
1 | 2 | import wcocr
|
2 | 3 | import os
|
3 |
| -from docx import Document |
4 |
| -from docx.shared import Pt |
5 |
| -from docx.oxml.ns import qn |
6 |
| -from colorama import init, Fore, Style |
| 4 | +from flask import Flask, request, jsonify |
| 5 | +from werkzeug.datastructures.file_storage import FileStorage |
| 6 | +import uuid |
| 7 | + |
| 8 | +# 创建 Flask 应用 |
| 9 | +app = Flask(__name__) |
| 10 | + |
| 11 | +# 设置图片保存目录 |
| 12 | +UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + "/img" |
| 13 | + |
| 14 | +# 设置允许上传的文件类型 |
| 15 | +ALLOWED_EXTENSIONS = ("jpg", "jpeg", "png", "bmp", "tif") |
| 16 | + |
7 | 17 |
|
8 | 18 | def find_wechat_path():
|
9 | 19 | script_dir = os.path.dirname(os.path.abspath(__file__))
|
10 |
| - common_paths = os.path.join(script_dir, 'path') |
| 20 | + common_paths = os.path.join(script_dir, "path") |
11 | 21 | if os.path.exists(common_paths):
|
12 | 22 | return common_paths
|
13 | 23 | else:
|
14 | 24 | print(f"The path folder does not exist at {common_paths}.")
|
15 | 25 | return None
|
16 | 26 |
|
| 27 | + |
17 | 28 | def find_wechatocr_exe():
|
18 | 29 | script_dir = os.path.dirname(os.path.abspath(__file__))
|
19 |
| - wechatocr_path = os.path.join(script_dir, 'path', 'WeChatOCR', 'WeChatOCR.exe') |
| 30 | + wechatocr_path = os.path.join(script_dir, "path", "WeChatOCR", "WeChatOCR.exe") |
20 | 31 | if os.path.isfile(wechatocr_path):
|
21 | 32 | return wechatocr_path
|
22 | 33 | else:
|
23 | 34 | print(f"The WeChatOCR.exe does not exist at {wechatocr_path}.")
|
24 | 35 | return None
|
25 | 36 |
|
26 |
| -def wechat_ocr(image_path): |
| 37 | + |
| 38 | +def wechat_ocr_init(): |
27 | 39 | wechat_path = find_wechat_path()
|
28 | 40 | wechatocr_path = find_wechatocr_exe()
|
29 | 41 | if not wechat_path or not wechatocr_path:
|
30 |
| - return [] # 返回空结果 |
31 |
| - |
| 42 | + raise Exception("WeChatOCR.exe not found.") |
| 43 | + |
32 | 44 | wcocr.init(wechatocr_path, wechat_path)
|
| 45 | + |
| 46 | + |
| 47 | +def wechat_ocr(image_path): |
| 48 | + |
33 | 49 | result = wcocr.ocr(image_path)
|
34 | 50 | texts = []
|
35 | 51 |
|
36 |
| - for temp in result['ocr_response']: |
37 |
| - text = temp['text'] |
| 52 | + for temp in result["ocr_response"]: |
| 53 | + text = temp["text"] |
38 | 54 | if isinstance(text, bytes):
|
39 |
| - text = text.decode('utf-8', errors='ignore') |
| 55 | + text = text.decode("utf-8", errors="ignore") |
40 | 56 | texts.append(text)
|
41 |
| - |
| 57 | + |
42 | 58 | return texts
|
43 | 59 |
|
44 |
| -def save_to_docx(texts, output_path): |
45 |
| - doc = Document() |
46 | 60 |
|
47 |
| - for text in texts: |
48 |
| - # 添加段落并设置宋体字体 |
49 |
| - paragraph = doc.add_paragraph() |
50 |
| - run = paragraph.add_run(text) |
51 |
| - run.font.name = '宋体' |
| 61 | +def save_file(file: FileStorage) -> str: |
52 | 62 |
|
53 |
| - # 设置字体为宋体 (兼容中文设置) |
54 |
| - r = run._element |
55 |
| - r.rPr.rFonts.set(qn('w:eastAsia'), '宋体') |
| 63 | + # 检查文件类型 |
| 64 | + if not file.filename.split(".")[-1] in ALLOWED_EXTENSIONS: |
| 65 | + return "" |
56 | 66 |
|
57 |
| - # 设置字体大小为五号字体 (10.5 磅) |
58 |
| - run.font.size = Pt(10.5) |
59 |
| - |
60 |
| - doc.save(output_path) |
| 67 | + # 生成唯一文件名 |
| 68 | + new_filename = uuid.uuid4().hex + "." + file.filename.split(".")[-1] |
61 | 69 |
|
62 |
| -def process_all_images(): |
63 |
| - script_dir = os.path.dirname(os.path.abspath(__file__)) |
64 |
| - src_folder = os.path.join(script_dir, 'src') |
65 |
| - docx_folder = os.path.join(script_dir, 'docx') |
66 |
| - |
67 |
| - if not os.path.exists(docx_folder): |
68 |
| - os.makedirs(docx_folder) |
69 |
| - |
70 |
| - # 支持的图像格式 |
71 |
| - image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tif') |
72 |
| - |
73 |
| - # 遍历 src 文件夹及其所有子文件夹 |
74 |
| - for root, dirs, files in os.walk(src_folder): |
75 |
| - for file in files: |
76 |
| - if file.lower().endswith(image_extensions): |
77 |
| - image_path = os.path.join(root, file) |
78 |
| - relative_path = os.path.relpath(root, src_folder) |
79 |
| - docx_folder_path = os.path.join(docx_folder, relative_path) |
80 |
| - |
81 |
| - # 确保 docx 文件夹路径存在 |
82 |
| - if not os.path.exists(docx_folder_path): |
83 |
| - os.makedirs(docx_folder_path) |
84 |
| - |
85 |
| - # 处理图片文件 |
86 |
| - print(Fore.GREEN + f"正在处理: {os.path.relpath(image_path, script_dir)}" + Style.RESET_ALL) |
87 |
| - texts = wechat_ocr(image_path) |
88 |
| - image_name = os.path.splitext(file)[0] |
89 |
| - output_docx = os.path.join(docx_folder_path, f'{image_name}_OCR.docx') |
90 |
| - save_to_docx(texts, output_docx) |
91 |
| - # 显示相对路径 |
92 |
| - relative_docx_path = os.path.relpath(output_docx, script_dir) |
93 |
| - print(f"OCR 结果已保存到: {relative_docx_path}\n") |
94 |
| - |
95 |
| -if __name__ == '__main__': |
96 |
| - init(autoreset=True) # 初始化 colorama |
97 |
| - process_all_images() |
98 |
| - print(Fore.RED + "全部文件处理完成,请按 Enter 键退出……" + Style.RESET_ALL) |
99 |
| - input() |
| 70 | + # 保存图片 |
| 71 | + if not os.path.exists(UPLOAD_FOLDER): |
| 72 | + os.mkdir(UPLOAD_FOLDER) |
| 73 | + |
| 74 | + file_path = os.path.join(UPLOAD_FOLDER, new_filename) |
| 75 | + file.save(file_path) |
| 76 | + |
| 77 | + return file_path |
| 78 | + |
| 79 | + |
| 80 | +# 定义上传图片路由 |
| 81 | +@app.route("/upload_ocr", methods=["POST"]) |
| 82 | +def upload_image(): |
| 83 | + # 检查请求是否包含文件 |
| 84 | + if "file" not in request.files: |
| 85 | + return jsonify({"code": 400, "msg": "没有上传文件"}) |
| 86 | + |
| 87 | + # 获取上传的文件 |
| 88 | + file = request.files["file"] |
| 89 | + if file.filename == "": |
| 90 | + return jsonify({"code": 400, "msg": "没有选择文件"}) |
| 91 | + |
| 92 | + file_path = save_file(file) |
| 93 | + if file_path == "": |
| 94 | + return jsonify({"code": 400, "msg": "不支持的文件类型"}) |
| 95 | + |
| 96 | + texts = wechat_ocr(file_path) |
| 97 | + |
| 98 | + # 返回上传成功信息 |
| 99 | + return jsonify({"code": 200, "msg": "上传成功", "data": texts}) |
| 100 | + |
| 101 | +# 释放 |
| 102 | +atexit.register(wcocr.destroy) |
| 103 | + |
| 104 | +if __name__ == "__main__": |
| 105 | + wechat_ocr_init() |
| 106 | + # 设置端口 |
| 107 | + app.run(host="0.0.0.0", port=5001) |
0 commit comments