我正在编写一个telegram 机器人,它将使用这个稳定的扩散模型生成图像:https://replicate.com/mbentley124/openjourney-img2img

我正在使用复制模块.但是,当有人发送请求时,下面的代码片段会降低机器人的运行速度.

async def txt2img(message, prompt, negative, stepMode, width, height):
print('Generating image for ' + str(message.chat.id))
output = replicate.run(
    "tstramer/midjourney-diffusion:436b051ebd8f68d23e83d22de5e198e0995357afef113768c20f0b6fcef23c8b",
    input={"prompt": "mdjrny-v4 " + prompt, "negative_prompt": negative, "num_inference_steps": stepMode*10, "width": width, "height": height}
)
print(output[0] + '\n')
return await message.answer_photo(output[0])

请帮助使此代码异步,这是可取的添加一个队列.

推荐答案

txt2img不是异步的,因为您正在使用的replicate.run函数是一个阻塞函数,让我们使用类似concurrent.futures的库在单独的线程中调用replicate.run.

就像我下面的例子一样,不要忘记将循环放在代码loop = asyncio.get_event_loop()中的某个位置

import concurrent.futures

async def txt2img(message, prompt, negative, stepMode, width, height):
    print('Generating image for ' + str(message.chat.id))

    def blocking_code():
        return replicate.run(
            "tstramer/midjourney-diffusion:436b051ebd8f68d23e83d22de5e198e0995357afef113768c20f0b6fcef23c8b",
            input={"prompt": "mdjrny-v4 " + prompt, "negative_prompt": negative, 
                   "num_inference_steps": stepMode*10, "width": width, "height": height}
        )

    with concurrent.futures.ThreadPoolExecutor() as executor:
        future = executor.submit(blocking_code)
        output = await loop.run_in_executor(None, future.result)

    print(output[0] + '\n')
    return await message.answer_photo(output[0])

Python相关问答推荐

aiohTTP与pytest的奇怪行为

使用pandas MultiIndex进行不连续 Select

Python:MultiIndex Dataframe到类似json的字典列表

根据多列和一些条件创建新列

如何在Python中按组应用简单的线性回归?

"Discord机器人中缺少所需的位置参数ctx

在编写要Excel的数据透视框架时修复标题行

为什么dict(id=1,**{id:2})有时会引发KeyMessage:id而不是TypMessage?

不允许AMBIMA API请求方法

在Python和matlab中显示不同 colored颜色 的图像

如何自动抓取以下CSV

在Python中处理大量CSV文件中的数据

难以在Manim中正确定位对象

log 1 p numpy的意外行为

Python虚拟环境的轻量级使用

对所有子图应用相同的轴格式

如何将多进程池声明为变量并将其导入到另一个Python文件

python中字符串的条件替换

Python逻辑操作作为Pandas中的条件

使用BeautifulSoup抓取所有链接