|
1 | 1 | import atexit
|
2 | 2 | import wcocr
|
3 | 3 | import os
|
| 4 | +import sys |
4 | 5 | from flask import Flask, request, jsonify
|
5 | 6 | from werkzeug.datastructures.file_storage import FileStorage
|
6 | 7 | import uuid
|
|
9 | 10 | # 创建 Flask 应用
|
10 | 11 | app = Flask(__name__)
|
11 | 12 |
|
12 |
| -# 设置图片保存目录 |
13 |
| -UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "img") |
14 |
| - |
15 | 13 | # 设置允许上传的文件类型
|
16 | 14 | ALLOWED_EXTENSIONS = ("jpg", "jpeg", "png", "bmp", "tif")
|
17 | 15 |
|
18 | 16 |
|
| 17 | +def get_save_dir() -> str: |
| 18 | + # 图片保存目录 |
| 19 | + if getattr(sys, "frozen", False): |
| 20 | + # 如果是打包后的可执行文件 |
| 21 | + return os.path.join(os.path.dirname(sys.executable), "img") |
| 22 | + else: |
| 23 | + # 如果是脚本运行 |
| 24 | + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "img") |
| 25 | + |
| 26 | + |
19 | 27 | def find_wechat_path():
|
20 | 28 | script_dir = os.path.dirname(os.path.abspath(__file__))
|
21 | 29 | common_paths = os.path.join(script_dir, "path")
|
@@ -68,11 +76,13 @@ def save_file(file: FileStorage) -> str:
|
68 | 76 | # 生成唯一文件名
|
69 | 77 | new_filename = uuid.uuid4().hex + "." + file.filename.split(".")[-1]
|
70 | 78 |
|
| 79 | + save_dir = get_save_dir() |
| 80 | + |
71 | 81 | # 保存图片
|
72 |
| - if not os.path.exists(UPLOAD_FOLDER): |
73 |
| - os.mkdir(UPLOAD_FOLDER) |
| 82 | + if not os.path.exists(save_dir): |
| 83 | + os.mkdir(save_dir) |
74 | 84 |
|
75 |
| - file_path = os.path.join(UPLOAD_FOLDER, new_filename) |
| 85 | + file_path = os.path.join(save_dir, new_filename) |
76 | 86 | file.save(file_path)
|
77 | 87 |
|
78 | 88 | return file_path
|
@@ -108,9 +118,11 @@ def upload_image():
|
108 | 118 | # # 设置端口
|
109 | 119 | # app.run(host="0.0.0.0", port=5001)
|
110 | 120 |
|
111 |
| -if __name__ == '__main__': |
| 121 | +if __name__ == "__main__": |
112 | 122 | wechat_ocr_init()
|
113 |
| - server = pywsgi.WSGIServer(('127.0.0.1', 5000), app) |
| 123 | + print("start listen 127.0.0.1:5000 0.0.0.0:5000") |
| 124 | + print("example : POST 127.0.0.1:5000/upload_ocr") |
| 125 | + server = pywsgi.WSGIServer(("127.0.0.1", 5000), app) |
114 | 126 | server.serve_forever()
|
115 |
| - server0 = pywsgi.WSGIServer(('0.0.0.0', 5000), app) |
| 127 | + server0 = pywsgi.WSGIServer(("0.0.0.0", 5000), app) |
116 | 128 | server0.serve_forever()
|
0 commit comments