Update app.py
Browse files
app.py
CHANGED
@@ -1,208 +1,220 @@
|
|
1 |
-
|
2 |
-
from
|
3 |
-
from
|
4 |
-
|
5 |
-
|
6 |
-
import
|
7 |
-
import
|
8 |
-
import
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
'
|
22 |
-
'
|
23 |
-
'
|
24 |
-
'
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
img_path_converted =
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
result_dir = os.path.
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
gr.
|
115 |
-
|
116 |
-
|
117 |
-
)
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
os.
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
from flask import Flask, request, jsonify, send_from_directory, render_template
|
3 |
+
from flask_cors import CORS
|
4 |
+
from ultralytics import YOLO
|
5 |
+
import gradio as gr
|
6 |
+
from threading import Thread
|
7 |
+
import os
|
8 |
+
import uuid
|
9 |
+
import logging
|
10 |
+
from PIL import Image
|
11 |
+
|
12 |
+
# 配置日志记录
|
13 |
+
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
14 |
+
|
15 |
+
# 创建 Flask 应用
|
16 |
+
app = Flask(__name__, static_folder='static')
|
17 |
+
CORS(app)
|
18 |
+
|
19 |
+
# 定义模型路径
|
20 |
+
models = {
|
21 |
+
'追踪': 'models/yolov8n.pt',
|
22 |
+
'检测': 'models/danzhu.pt',
|
23 |
+
'分类': 'models/yolov8n-cls.pt',
|
24 |
+
'姿势': 'models/yolov8n-pose.pt',
|
25 |
+
'分割': 'models/yolov8n-seg.pt'
|
26 |
+
}
|
27 |
+
|
28 |
+
model_instances = {}
|
29 |
+
|
30 |
+
def load_model(model_path):
|
31 |
+
"""加载模型"""
|
32 |
+
try:
|
33 |
+
logging.info(f"正在从 {model_path} 加载模型...")
|
34 |
+
model = YOLO(model_path)
|
35 |
+
logging.info(f"模型从 {model_path} 成功加载")
|
36 |
+
return model
|
37 |
+
except Exception as e:
|
38 |
+
logging.error(f"从 {model_path} 加载模型失败: {e}")
|
39 |
+
return None
|
40 |
+
|
41 |
+
def convert_image_format(img_path, target_format='JPEG'):
|
42 |
+
"""转换图像格式"""
|
43 |
+
try:
|
44 |
+
with Image.open(img_path) as img:
|
45 |
+
if img.mode != 'RGB':
|
46 |
+
img = img.convert('RGB')
|
47 |
+
base_name, _ = os.path.splitext(img_path)
|
48 |
+
target_path = f"{base_name}.{target_format.lower()}"
|
49 |
+
img.save(target_path, format=target_format)
|
50 |
+
logging.info(f"图像格式成功转换为 {target_format},保存到 {target_path}")
|
51 |
+
return target_path
|
52 |
+
except Exception as e:
|
53 |
+
logging.error(f"图像格式转换失败: {e}")
|
54 |
+
raise
|
55 |
+
|
56 |
+
def predict(model_name, img_path):
|
57 |
+
"""进行预测"""
|
58 |
+
try:
|
59 |
+
if model_name not in models:
|
60 |
+
logging.error("选择的模型无效。")
|
61 |
+
return "选择的模型无效。"
|
62 |
+
|
63 |
+
model_path = models[model_name]
|
64 |
+
if model_name not in model_instances:
|
65 |
+
model_instances[model_name] = load_model(model_path)
|
66 |
+
model = model_instances[model_name]
|
67 |
+
|
68 |
+
if model is None:
|
69 |
+
logging.error("由于连接错误,模型未加载。")
|
70 |
+
return "由于连接错误,模型未加载。"
|
71 |
+
|
72 |
+
unique_name = str(uuid.uuid4())
|
73 |
+
save_dir = './runs/detect'
|
74 |
+
os.makedirs(save_dir, exist_ok=True)
|
75 |
+
logging.info(f"保存目录: {save_dir}")
|
76 |
+
|
77 |
+
# 转换图像格式
|
78 |
+
img_path_converted = convert_image_format(img_path, 'JPEG')
|
79 |
+
img_path_converted = os.path.normpath(img_path_converted)
|
80 |
+
logging.info(f"对 {img_path_converted} 进行预测...")
|
81 |
+
|
82 |
+
results = model.predict(img_path_converted, save=True, project=save_dir, name=unique_name, device='cpu')
|
83 |
+
logging.info(f"预测结果: {results}")
|
84 |
+
|
85 |
+
result_dir = os.path.join(save_dir, unique_name)
|
86 |
+
result_dir = os.path.normpath(result_dir)
|
87 |
+
logging.info(f"结果目录: {result_dir}")
|
88 |
+
|
89 |
+
if not os.path.exists(result_dir):
|
90 |
+
logging.error(f"结果目录 {result_dir} 不存在")
|
91 |
+
return "未找到预测结果。"
|
92 |
+
|
93 |
+
# 查找预测结果文件
|
94 |
+
predicted_img_path = None
|
95 |
+
for file in os.listdir(result_dir):
|
96 |
+
if file.lower().endswith(('.jpeg', '.jpg')):
|
97 |
+
predicted_img_path = os.path.join(result_dir, file)
|
98 |
+
break
|
99 |
+
|
100 |
+
if predicted_img_path:
|
101 |
+
logging.info(f"找到预测图像: {predicted_img_path}")
|
102 |
+
return predicted_img_path
|
103 |
+
else:
|
104 |
+
logging.error(f"在 {result_dir} 中未找到预测图像")
|
105 |
+
return "未找到预测结果。"
|
106 |
+
except Exception as e:
|
107 |
+
logging.error(f"预测过程中出错: {e}")
|
108 |
+
return f"预测过程中出错: {e}"
|
109 |
+
|
110 |
+
# 定义 Gradio 界面
|
111 |
+
iface = gr.Interface(
|
112 |
+
fn=predict,
|
113 |
+
inputs=[
|
114 |
+
gr.Dropdown(choices=list(models.keys()), label="选择模型"),
|
115 |
+
gr.Image(type="filepath", label="输入图像")
|
116 |
+
],
|
117 |
+
outputs=gr.Image(type="filepath", label="输出图像")
|
118 |
+
)
|
119 |
+
|
120 |
+
@app.route('/')
|
121 |
+
def home():
|
122 |
+
"""主页"""
|
123 |
+
return render_template('index.html')
|
124 |
+
|
125 |
+
@app.route('/request', methods=['POST'])
|
126 |
+
def handle_request():
|
127 |
+
"""处理请求"""
|
128 |
+
try:
|
129 |
+
selected_model = request.form.get('model')
|
130 |
+
if selected_model not in models:
|
131 |
+
logging.error("选择的模型无效。")
|
132 |
+
return jsonify({'error': '选择的模型无效。'}), 400
|
133 |
+
|
134 |
+
model_path = models[selected_model]
|
135 |
+
if selected_model not in model_instances:
|
136 |
+
model_instances[selected_model] = load_model(model_path)
|
137 |
+
model = model_instances[selected_model]
|
138 |
+
|
139 |
+
if model is None:
|
140 |
+
logging.error("由于连接错误,模型未加载。")
|
141 |
+
return jsonify({'error': '由于连接错误,模型未加载。'}), 500
|
142 |
+
|
143 |
+
img = request.files.get('img')
|
144 |
+
if img is None:
|
145 |
+
logging.error("未提供图像。")
|
146 |
+
return jsonify({'error': '未提供图像。'}), 400
|
147 |
+
|
148 |
+
img_name = str(uuid.uuid4()) + '.jpg'
|
149 |
+
img_path = os.path.join('./img', img_name)
|
150 |
+
os.makedirs(os.path.dirname(img_path), exist_ok=True)
|
151 |
+
img.save(img_path)
|
152 |
+
logging.info(f"图像已保存到: {img_path}")
|
153 |
+
|
154 |
+
save_dir = './runs/detect'
|
155 |
+
os.makedirs(save_dir, exist_ok=True)
|
156 |
+
unique_name = str(uuid.uuid4())
|
157 |
+
logging.info(f"对 {img_path} 进行预测...")
|
158 |
+
results = model.predict(img_path, save=True, project=save_dir, name=unique_name, device='cpu')
|
159 |
+
logging.info(f"预测结果: {results}")
|
160 |
+
|
161 |
+
result_dir = os.path.join(save_dir, unique_name)
|
162 |
+
|
163 |
+
# 查找预测结果文件
|
164 |
+
predicted_img_path = None
|
165 |
+
for file in os.listdir(result_dir):
|
166 |
+
if file.endswith('.jpeg') or file.endswith('.jpg'):
|
167 |
+
predicted_img_path = os.path.join(result_dir, file)
|
168 |
+
break
|
169 |
+
|
170 |
+
if predicted_img_path:
|
171 |
+
img_url = f'/get/{unique_name}/{os.path.basename(predicted_img_path)}'
|
172 |
+
return jsonify({'message': '预测成功!', 'img_path': img_url})
|
173 |
+
else:
|
174 |
+
saved_files = os.listdir(result_dir)
|
175 |
+
logging.error(f"保存目录中包含文件: {saved_files}")
|
176 |
+
return jsonify({'error': '未找到预测结果。'}), 500
|
177 |
+
except Exception as e:
|
178 |
+
logging.error(f"处理请求时出错: {e}")
|
179 |
+
return jsonify({'error': f'处理过程中发生错误: {e}'}), 500
|
180 |
+
|
181 |
+
@app.route('/get/<unique_name>/<filename>')
|
182 |
+
def get_image(unique_name, filename):
|
183 |
+
"""获取图像"""
|
184 |
+
try:
|
185 |
+
return send_from_directory(os.path.join('runs/detect', unique_name), filename)
|
186 |
+
except Exception as e:
|
187 |
+
logging.error(f"提供文件时出错: {e}")
|
188 |
+
return jsonify({'error': '文件未找到。'}), 404
|
189 |
+
|
190 |
+
def run_gradio():
|
191 |
+
"""运行 Gradio 界面"""
|
192 |
+
logging.info("启动 Gradio 界面...")
|
193 |
+
iface.launch(share=True) # 设置 share=True 以便公开访问
|
194 |
+
|
195 |
+
def run_flask():
|
196 |
+
"""运行 Flask 应用"""
|
197 |
+
logging.info("启动 Flask 应用...")
|
198 |
+
app.run(host="0.0.0.0", port=5000)
|
199 |
+
|
200 |
+
if __name__ == '__main__':
|
201 |
+
# 启动 Flask 和 Gradio 线程
|
202 |
+
gradio_thread = Thread(target=run_gradio)
|
203 |
+
flask_thread = Thread(target=run_flask)
|
204 |
+
|
205 |
+
gradio_thread.start()
|
206 |
+
flask_thread.start()
|
207 |
+
|
208 |
+
gradio_thread.join()
|
209 |
+
flask_thread.join()
|
210 |
+
'''
|
211 |
+
|
212 |
+
from ultralytics import YOLO
|
213 |
+
|
214 |
+
# Load a model
|
215 |
+
model = YOLO("yolov8n.yaml") # build a new model from YAML
|
216 |
+
model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training)
|
217 |
+
model = YOLO("yolov8n.yaml").load("yolov8n.pt") # build from YAML and transfer weights
|
218 |
+
|
219 |
+
# Train the model
|
220 |
+
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)
|