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