image_classfication_controller.py 1.86 KB
import os
import shutil
from flask import request, Blueprint
import requests
from flaskr.biz.identify_service import IdentifyService
from flaskr.biz.image_classification_service import ImageClassificationService

# 创建一个蓝图
classfication_bp = Blueprint("images_classfication", __name__)


# 在蓝图中定义路由和视图函数
@classfication_bp.route("/identify", methods=["POST"])
def identify():
    network_img_path = request.get_json()["img_path"]
    print("network_img_path===", network_img_path)
    filename = IdentifyService().generate_random_filename()
    print("network_img_path", network_img_path)
    extension = IdentifyService().get_extension(network_img_path)
    complete_filename = f"{filename}.{extension}"
    response = requests.get(network_img_path)
    path = os.path.join(
        IdentifyService().get_project_root(), "images", complete_filename
    )
    with open(path, "wb") as file:
        file.write(response.content)
    print("File downloaded successfully." + path)
    (a, b) = ImageClassificationService("data/modelFile/my_model03.h5").doClassfication(
        path
    )
    # 预测完以后删除文件
    print("预测完以后删除文件" + path)
    os.remove(path)
    print(a, b)
    return a


@classfication_bp.route("/upload", methods=["POST"])
def upload():
    file = request.files["file"]  # 获取上传的文件
    file.save("uploads/" + file.filename)  # 保存文件到指定路径
    local_img_path = "./uploads/" + file.filename
    print("local_img_path===", local_img_path)
    (a, b) = ImageClassificationService("data/modelFile/my_model03.h5").doClassfication(
        local_img_path
    )
    # 预测完以后删除文件
    print("预测完以后删除文件" + local_img_path)
    os.remove(local_img_path)
    print(a, b)
    return a


@classfication_bp.route("/register")
def register():
    return "Register Page"