ali docker部属rembg

发布于:2025-09-06 ⋅ 阅读:(21) ⋅ 点赞:(0)
docker run -d \
  --restart unless-stopped \
  -p 9000:9000 \
  -v ~/paddleocr_models:/root/.paddleocr \
  -v /root/projects:/app \
  --name paddleocr2 \
  registry.baidubce.com/paddlepaddle/paddle:2.6.0 \
  bash -c "
    pip install --upgrade pip && \
    pip install paddleocr==2.6.1.3 flask numpy==1.24.3 onnxruntime -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn && \
    pip install \"rembg[cpu]\" -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn && \
    cd /app && \
    python paddleocr_server.py
  "

docker ps
docker stop  56fff29d6161
docker rm  56fff29d6161
docker logs 56fff29d6161
docker exec -it 56fff29d6161 /bin/bash

paddleocr_server.py

from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import uuid
from paddleocr import PaddleOCR
import json
import os
from rembg import remove
import base64

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'


@app.post('/ocr')
def file_upload():
    f = request.files['file']
    uuid1 = str(uuid.uuid1())
    path = uuid1 + f.filename
    f.save(path)

    ocr = PaddleOCR(use_angle_cls=True, lang='ch')  # need to run only once to download and load model into memory
    result = ocr.ocr(path, cls=True)

    content = []
    for idx in range(len(result)):
        res = result[idx]
        for line in res:
            content.append(line)
    print(content)
    os.remove(path)
    strs = json.dumps(content)
    print(strs)
    return strs


@app.post('/rmbg')
def file_upload_rmbg():
    try:
        f = request.files['file']

        # 检查文件名是否为空
        if f.filename == '':
            return jsonify({'error': 'No file selected'}), 400

        # 创建安全的临时目录(如果不存在)
        temp_dir = 'temp_uploads'
        if not os.path.exists(temp_dir):
            os.makedirs(temp_dir)

        # 生成唯一文件名,避免路径遍历攻击
        original_filename = f.filename
        safe_filename = ''.join(c for c in original_filename if c.isalnum() or c in (' ', '.', '_')).rstrip()

        uuid1 = str(uuid.uuid4())  # 使用uuid4更安全
        uuid2 = str(uuid.uuid4())

        input_path = os.path.join(temp_dir, f"{uuid1}_{safe_filename}")
        output_path = os.path.join(temp_dir, f"{uuid2}_{safe_filename}")

        # 保存上传的文件
        f.save(input_path)

        # 处理图片并移除背景
        with open(input_path, 'rb') as i:
            input_data = i.read()
            output_data = remove(input_data)

        # 保存处理后的图片
        with open(output_path, 'wb') as o:
            o.write(output_data)

        # 读取处理后的图片并转换为base64
        with open(output_path, 'rb') as img_file:
            base64_data = base64.b64encode(img_file.read()).decode('utf-8')

        # 清理临时文件
        try:
            os.remove(input_path)
            os.remove(output_path)
        except:
            pass  # 确保即使删除失败也不影响主要功能
        # 返回base64数据
        return jsonify({
            'success': True,
            'image_base64': f"data:image/png;base64,{base64_data}",
            'filename': original_filename
        })

    except Exception as e:
        # 清理可能创建的临时文件
        try:
            if 'input_path' in locals() and os.path.exists(input_path):
                os.remove(input_path)
            if 'output_path' in locals() and os.path.exists(output_path):
                os.remove(output_path)
        except:
            pass

        return jsonify({'error': f'Processing failed: {str(e)}'}), 500

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

运行效果:


网站公告

今日签到

点亮在社区的每一天
去签到