HerokuR15 使用多线程 python Flask 应用程序时出错

发布于 2025-01-11 18:33:26 字数 4721 浏览 0 评论 0原文

我正在做一个输出增强图像的网络应用程序。它在本地系统中运行良好。但在服务器端引发 R15 错误。在此处输入图像描述

我使用多线程来平衡工作流程。

app.py

from __future__ import division, print_function
# coding=utf-8
import os,cv2,uuid,threading
import numpy as np
from gan import *
from splits import Splits
from deliver import Deliver
# Flask utils
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename

app=Flask(__name__)

@app.route('/', methods=['GET','POST'])
def index():
    print("index Loaded")
    return render_template('index.html')

@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        f = request.files['file-ip-1']
        email=request.form['email']
        print(email)
        user_root=f'{email}_{uuid.uuid4()}'
        print(user_root)
        os.makedirs('web',exist_ok=True)
        os.mkdir(os.path.join('web', user_root))
        file_path = os.path.join('web',user_root, secure_filename(f.filename))
        print(file_path)
        f.save(file_path)
        t=threading.Thread(target=runn,args=(file_path,email,user_root)).start()
    return render_template('submit.html')

def runn(file_path,email,user_root):
    print("runn Loaded")
    s=Splits()
    tokens,h,w,ext = s.get_tokens(file_path,user_root)
    print('Tokens created')
    print(len(tokens),w,h,ext)
    d=gan.main(user_root)
    if d:
        print('resoultions created')
        i=s.get_image('outputs/',w,ext,user_root)
        print(i,email)

        D=Deliver().send_email(email,i,user_root)

    else:
        print("Error")



if __name__ == '__main__':
    app.run(debug=False,threaded=True)

从使用 srgan 执行图像增强操作的 d=gan.main(user_root) 行中获取错误。 gan.py

import argparse
import cv2
import glob
import os
from basicsr.archs.rrdbnet_arch import RRDBNet

from realesrgan import RealESRGANer
from realesrgan.archs.srvgg_arch import SRVGGNetCompact

class gan:
        
    def main(user_root):
        try:
            

            
            model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
            netscale = 4
            model_name = 'RealESRGAN_x4plus'
            # determine model paths
            model_path = os.path.join('experiments/pretrained_models', model_name + '.pth')
            if not os.path.isfile(model_path):
                model_path = os.path.join('realesrgan/weights', model_name + '.pth')
        
            # restorer
            upsampler = RealESRGANer(
                scale=netscale,
                model_path=model_path,
                model=model,
                tile=0,
                tile_pad=10,
                pre_pad=0,
                )

            os.makedirs(f'outputs', exist_ok=True)
            os.makedirs(f'outputs/{user_root}', exist_ok=True)

            if os.path.isfile(f'inputs/{user_root}'):
                paths = [f'inputs/{user_root}/']
            else:
                paths = sorted(glob.glob(os.path.join(f'inputs/{user_root}', '*')))

            for idx, path in enumerate(paths):
                imgname, extension = os.path.splitext(os.path.basename(path))
                print('Processing {}.{}'.format(imgname, extension))
                print('Testing', idx, imgname)

                img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
                if len(img.shape) == 3 and img.shape[2] == 4:
                    img_mode = 'RGBA'
                else:
                    img_mode = None

                try:
                    output, _ = upsampler.enhance(img, outscale=4)

                except RuntimeError as error:
                    print('Error', error)
                    print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')
                else:
                    ext='auto'
                    if ext == 'auto':
                        extension = extension[1:]
                    else:
                        extension = ext
                    if img_mode == 'RGBA':  # RGBA images should be saved in png format
                        extension = 'png'
                    save_path = os.path.join('outputs',user_root, f'{imgname}.{extension}')
                    cv2.imwrite(save_path, output)
                    print('Saved', save_path)
                    print('Done')
            return True
        except Exception as e:
            print(e)
            return False

if __name__ == '__main__':
    gan.main()

请帮助我避免运行时出现 R14 和 R15 错误。

Im doing a web app that outputs enhances image. it works good in local system. But raising R15 error on server side.enter image description here

And im using multithreading for balenced workflow.

app.py

from __future__ import division, print_function
# coding=utf-8
import os,cv2,uuid,threading
import numpy as np
from gan import *
from splits import Splits
from deliver import Deliver
# Flask utils
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename

app=Flask(__name__)

@app.route('/', methods=['GET','POST'])
def index():
    print("index Loaded")
    return render_template('index.html')

@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        f = request.files['file-ip-1']
        email=request.form['email']
        print(email)
        user_root=f'{email}_{uuid.uuid4()}'
        print(user_root)
        os.makedirs('web',exist_ok=True)
        os.mkdir(os.path.join('web', user_root))
        file_path = os.path.join('web',user_root, secure_filename(f.filename))
        print(file_path)
        f.save(file_path)
        t=threading.Thread(target=runn,args=(file_path,email,user_root)).start()
    return render_template('submit.html')

def runn(file_path,email,user_root):
    print("runn Loaded")
    s=Splits()
    tokens,h,w,ext = s.get_tokens(file_path,user_root)
    print('Tokens created')
    print(len(tokens),w,h,ext)
    d=gan.main(user_root)
    if d:
        print('resoultions created')
        i=s.get_image('outputs/',w,ext,user_root)
        print(i,email)

        D=Deliver().send_email(email,i,user_root)

    else:
        print("Error")



if __name__ == '__main__':
    app.run(debug=False,threaded=True)

Getting error from this line d=gan.main(user_root) which perform image enhance operation using srgan.
gan.py

import argparse
import cv2
import glob
import os
from basicsr.archs.rrdbnet_arch import RRDBNet

from realesrgan import RealESRGANer
from realesrgan.archs.srvgg_arch import SRVGGNetCompact

class gan:
        
    def main(user_root):
        try:
            

            
            model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
            netscale = 4
            model_name = 'RealESRGAN_x4plus'
            # determine model paths
            model_path = os.path.join('experiments/pretrained_models', model_name + '.pth')
            if not os.path.isfile(model_path):
                model_path = os.path.join('realesrgan/weights', model_name + '.pth')
        
            # restorer
            upsampler = RealESRGANer(
                scale=netscale,
                model_path=model_path,
                model=model,
                tile=0,
                tile_pad=10,
                pre_pad=0,
                )

            os.makedirs(f'outputs', exist_ok=True)
            os.makedirs(f'outputs/{user_root}', exist_ok=True)

            if os.path.isfile(f'inputs/{user_root}'):
                paths = [f'inputs/{user_root}/']
            else:
                paths = sorted(glob.glob(os.path.join(f'inputs/{user_root}', '*')))

            for idx, path in enumerate(paths):
                imgname, extension = os.path.splitext(os.path.basename(path))
                print('Processing {}.{}'.format(imgname, extension))
                print('Testing', idx, imgname)

                img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
                if len(img.shape) == 3 and img.shape[2] == 4:
                    img_mode = 'RGBA'
                else:
                    img_mode = None

                try:
                    output, _ = upsampler.enhance(img, outscale=4)

                except RuntimeError as error:
                    print('Error', error)
                    print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')
                else:
                    ext='auto'
                    if ext == 'auto':
                        extension = extension[1:]
                    else:
                        extension = ext
                    if img_mode == 'RGBA':  # RGBA images should be saved in png format
                        extension = 'png'
                    save_path = os.path.join('outputs',user_root, f'{imgname}.{extension}')
                    cv2.imwrite(save_path, output)
                    print('Saved', save_path)
                    print('Done')
            return True
        except Exception as e:
            print(e)
            return False

if __name__ == '__main__':
    gan.main()

Please help me to avoid R14 and R15 error on runtime.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文