yoooooger

This commit is contained in:
yooooger 2025-09-02 11:50:56 +08:00
parent 4ee4d26e48
commit 33c0817169

View File

@ -1,19 +1,16 @@
import logging,os,uuid,asyncio,torch
# sanic imports
from sanic import Sanic, json, Blueprint,response from sanic import Sanic, json, Blueprint,response
from sanic.exceptions import Unauthorized from sanic.exceptions import Unauthorized
from sanic.response import json as json_response from sanic.response import json as json_response
from sanic_cors import CORS from sanic_cors import CORS
import numpy as np # ourself imports
import logging from ai_image import process_images
import uuid
import os,traceback
import asyncio
from ai_image import process_images # 你实现的图片处理函数
from queue import Queue
from map_find import map_process_images from map_find import map_process_images
from yolo_train import auto_train,query_progress from yolo_train import auto_train,query_progress
import torch from yolo_photo import map_process_images_with_progress
from yolo_photo import map_process_images_with_progress # 引入你的处理函数
# 日志配置 # set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -51,8 +48,8 @@ async def token_and_resource_check(request):
return None # 允许请求继续 return None # 允许请求继续
################################################################################################################################################################################################## ################################################################# set up app and blueprints ########################################################################################################
#创建Sanic应用 # create app and cors
app = Sanic("ai_Service_v2") app = Sanic("ai_Service_v2")
CORS(app) # 允许跨域请求 CORS(app) # 允许跨域请求
task_progress = {} task_progress = {}
@ -196,14 +193,14 @@ async def run_image_processing(task_id, urls, yaml_name, bucket_name, bucket_dir
task_progress[task_id]["progress"] = 100 task_progress[task_id]["progress"] = 100
task_progress[task_id]["result"] = str(e) task_progress[task_id]["result"] = str(e)
# YOLO检测API # YOLO detect API
@yolo_tile_blueprint.post("/picture") @yolo_tile_blueprint.post("/picture")
async def yolo_detect_api(request): async def yolo_detect_api(request):
try: try:
detect_data = request.json detect_data = request.json
# 解析必要字段 #
image_list = detect_data.get("image_list") image_list = detect_data.get("image_list")
yolo_model = detect_data.get("yolo_model", "best.pt") yolo_model = detect_data.get("yolo_model", "best.pt")
class_filter = detect_data.get("class", None) class_filter = detect_data.get("class", None)
@ -215,11 +212,11 @@ async def yolo_detect_api(request):
if not minio_info: if not minio_info:
return json_response({"status": "error", "message": "MinIO information is required"}, status=400) return json_response({"status": "error", "message": "MinIO information is required"}, status=400)
# 创建临时文件夹 # Create a temporary directory for input and output images
input_folder = f"./temp_input_{str(uuid.uuid4())}" input_folder = f"./temp_input_{str(uuid.uuid4())}"
output_folder = f"./temp_output_{str(uuid.uuid4())}" output_folder = f"./temp_output_{str(uuid.uuid4())}"
# 执行图像处理 # Execute the image processing in a separate thread to avoid blocking the event loop
result = await asyncio.to_thread( result = await asyncio.to_thread(
process_images, process_images,
yolo_model=yolo_model, yolo_model=yolo_model,
@ -230,7 +227,7 @@ async def yolo_detect_api(request):
minio_info=minio_info minio_info=minio_info
) )
# 返回处理结果 # return the result as JSON response
return json_response(result) return json_response(result)
except Exception as e: except Exception as e:
@ -240,12 +237,12 @@ async def yolo_detect_api(request):
"message": f"Internal server error: {str(e)}" "message": f"Internal server error: {str(e)}"
}, status=500) }, status=500)
# YOLO自动训练 # YOLO auto_train API
@yolo_tile_blueprint.post("/train") @yolo_tile_blueprint.post("/train")
async def yolo_train_api(request): async def yolo_train_api(request):
""" """
自动训练模型 auto_train
输入 JSON: input JSON:
{ {
"db_host": str, "db_host": str,
"db_database": str, "db_database": str,
@ -260,7 +257,7 @@ async def yolo_train_api(request):
"class_names": Optional[List[str]], "class_names": Optional[List[str]],
"project_name": str "project_name": str
} }
输出 JSON: output JSON:
return { return {
"status": "success", "status": "success",
"message": "Train finished", "message": "Train finished",
@ -271,18 +268,15 @@ async def yolo_train_api(request):
} }
""" """
try: try:
# 修改为直接访问 request.json 而不是调用它
data = request.json data = request.json
if not data: if not data:
return json_response({"status": "error", "message": "data is required"}, status=400) return json_response({"status": "error", "message": "data is required"}, status=400)
# Do the training in a separate thread to avoid blocking the event loop
# 执行图像处理
result = await asyncio.to_thread( result = await asyncio.to_thread(
auto_train, auto_train,
data data
) )
# 返回处理结果 # return the result as JSON response
return json_response(result) return json_response(result)
except Exception as e: except Exception as e:
@ -292,14 +286,14 @@ async def yolo_train_api(request):
"message": f"Internal server error: {str(e)}" "message": f"Internal server error: {str(e)}"
}, status=500) }, status=500)
# 查询训练进度接口 # access the training progress
@yolo_tile_blueprint.get("/progress/<project_name>") @yolo_tile_blueprint.get("/progress/<project_name>")
async def yolo_train_progress(request, project_name): async def yolo_train_progress(request, project_name):
''' '''
输入参数: input:
如果想查询最新一次训练GET /yolo/progress/my_project if want to query the latest progress: GET /yolo/progress/my_project
如果想查询某次特定时间GET /yolo/progress/my_project?run_time=20250902_1012 if want to query the progress at a specific time: GET /yolo/progress/my_project?run_time=20250902_1012
输出 JSON: output JSON:
{ {
"status": "ok", "status": "ok",
"run_time": "20250902_1012", "run_time": "20250902_1012",
@ -312,7 +306,11 @@ async def yolo_train_progress(request, project_name):
} }
} }
''' '''
run_time = request.args.get("run_time") # 可选参数 run_time = request.args.get("run_time") # get the run_time from the query string
# query the progress from the database
if not run_time:
run_time = None # if not provided, query the latest progress
result = await asyncio.to_thread(query_progress, project_name, run_time) result = await asyncio.to_thread(query_progress, project_name, run_time)
return json_response(result) return json_response(result)