Linux 安装anaconda使用modelscope开源模型进行动物识别

1. 创建anaconda3镜像

docker pull continuumio/anaconda3
docker run -it -d --name anaconda3 continuumio/anaconda3

2. 创建可移动部署容器

2.1 配置环境

conda install pytorch torchvision torchaudio cpuonly -c pytorch

2.2 安装模型

pip install modelscope
pip install opencv-python

如果报错:libGL.so.1: cannot open shared object file: No such file or directory

执行:

apt update
apt install -y libgl1-mesa-glx

2.3 将需要的文件放入容器内

使用docker cp 将脚本文件animal.py ,模型文件cv_resnest101_animal_recognition放入/home目录下。

import sys
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

animal_recognition= pipeline(
            Tasks.animal_recognition,
            model='home/cv_resnest101_animal_recognition')
result = animal_recognition(sys.argv[1])
print(result)

2.4 创建python服务,并测试

创建python_script.py文件,并将该文件放入/home目录下:

docker cp C:\Users\Bnc\Desktop\python_script.py e9d3b8b5970b:/home/
from flask import Flask, request
import subprocess

app = Flask(__name__)

@app.route('/execute_script', methods=['POST'])
def execute_script():
    # 获取请求中的参数
    script_path = request.json.get('script_path')
    script_args = request.json.get('script_args', [])

    try:
        # 使用 subprocess 模块执行对应的 Python 文件,并传递参数
        command = ['python', script_path] + script_args
        result = subprocess.check_output(command, stderr=subprocess.STDOUT, universal_newlines=True)
		# 提取最后一行作为结果输出
        filtered_result = result.strip().split('\n')[-1]
        return filtered_result
    except subprocess.CalledProcessError as e:
        return {'error': str(e)}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

启动python服务:

要后台执行使用命令:

nohup python /home/python_script.py > output.log &

执行脚本测试:

curl -X POST -H "Content-Type: application/json" -d '{"script_path": "/home/animal.py", "script_args": ["https://pailitao-image-recog.oss-cn-zhangjiakou.aliyuncs.com/mufan/img_data/maas_test_data/dog.png"]}' http://127.0.0.1:5000/execute_script

2.5 Java使用http请求调用python服务执行脚本

Python服务在容器的5000端口运行,要在宿主机访问容器内服务,需要将容器内端口映射出来:

docker run -it -d  -p 8010:5000 --privileged=true --name anaconda3 continuumio/anaconda3 bash

Java代码:

import com.alibaba.fastjson.JSON;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class anTes {
    public static void main(String[] args) throws IOException {
        // Flask应用程序的URL
        String url = "http://127.0.0.1:8010/execute_script";
        Map<String, Object> params = new HashMap<>();
        params.put("script_path", "/home/animal.py");
        // 如果有其他参数,也可以添加到 params 中
        List<String> objects = new ArrayList<>();
        objects.add("https://pailitao-image-recog.oss-cn-zhangjiakou.aliyuncs.com/mufan/img_data/maas_test_data/dog.png");
//        objects.add("http://192.168.100.100:8092/group1/default/20240403/11/40/5/1712115624782_undefined.jpg");
        params.put("script_args", objects);
        String jsonParams = JSON.toJSONString(params);

        // 发送POST请求并获取响应
        String response = sendPostRequest(url, jsonParams);

        // 输出响应结果
        System.out.println("Response: " + response);
    }

    private static String sendPostRequest(String urlString, String jsonParams) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为POST
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        // 设置请求头
        connection.setRequestProperty("Content-Type", "application/json");

        // 发送请求参数
        try (OutputStream outputStream = connection.getOutputStream()) {
            byte[] input = jsonParams.getBytes("utf-8");
            outputStream.write(input, 0, input.length);
        }

        // 获取响应
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }
}

执行结果:

2.6 将制作好的容器导出

docker export -o container_anaconda3.tar anaconda3

2.7 将tar包导入其他服务器执行

docker import container_anaconda3.tar continuumio/anaconda3

启动容器,将内部5000端口映射到宿主机8010端口:

docker run -it -d  -p 8010:5000 --privileged=true --name anaconda3 continuumio/anaconda3 bash

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值