stable-diffusion-webui icon indicating copy to clipboard operation
stable-diffusion-webui copied to clipboard

[Bug]: /sdapi/v1/txt2img endpoint not working

Open Darklobi opened this issue 1 year ago • 25 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues and checked the recent builds/commits

What happened?

Today when i tried to use my discord bot to make some requests to the endpoint /sdapi/v1/txt2img, i kept getting the error: "There is no current event loop in thread 'AnyIO worker thread'." Last successful generations were around 48h ago.

Steps to reproduce the problem

  1. Start fast-stable-diffusion colab version by TheLastBen colab
  2. . Make a post request using to the endpoint /sdapi/v1/txt2img (or using any other tool like Postman) 1234 12345

What should have happened?

Generate image and return success response json body with image path

Commit where the problem happens

https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/955df7751eef11bb7697e2d77f6b8a6226b21e13

What platforms do you use to access the UI ?

Other/Cloud

What browsers do you use to access the UI ?

Google Chrome

Command Line Arguments

no

List of extensions

no

Console logs

API error: POST: https://41209b1e8d4c8c9c05.gradio.live/sdapi/v1/txt2img {'error': 'RuntimeError', 'detail': '', 'body': '', 'errors': "There is no current event loop in thread 'AnyIO worker thread'."}
╭───────────────────── Traceback (most recent call last) ──────────────────────╮
│ /usr/local/lib/python3.9/dist-packages/anyio/streams/memory.py:94 in receive │
│                                                                              │
│ /usr/local/lib/python3.9/dist-packages/anyio/streams/memory.py:89 in         │
│ receive_nowait                                                               │
╰──────────────────────────────────────────────────────────────────────────────╯
WouldBlock

During handling of the above exception, another exception occurred:

╭───────────────────── Traceback (most recent call last) ──────────────────────╮
│ /usr/local/lib/python3.9/dist-packages/starlette/middleware/base.py:43 in    │
│ call_next                                                                    │
│                                                                              │
│ /usr/local/lib/python3.9/dist-packages/anyio/streams/memory.py:114 in        │
│ receive                                                                      │
╰──────────────────────────────────────────────────────────────────────────────╯
EndOfStream

During handling of the above exception, another exception occurred:

╭───────────────────── Traceback (most recent call last) ──────────────────────╮
│ /content/gdrive/MyDrive/sd/stable-diffusion-webui/modules/api/api.py:145 in  │
│ exception_handling                                                           │
│                                                                              │
│   144 │   │   try:                                                           │
│ ❱ 145 │   │   │   return await call_next(request)                            │
│   146 │   │   except Exception as e:                                         │
│                                                                              │
│ ╭───────────────────────────────── locals ─────────────────────────────────╮ │
│ │        call_next = <function                                             │ │
│ │                    BaseHTTPMiddleware.__call__.<locals>.call_next at     │ │
│ │                    0x7f45ac0faf70>                                       │ │
│ │                e = RuntimeError("There is no current event loop in       │ │
│ │                    thread 'AnyIO worker thread'.")                       │ │
│ │ handle_exception = <function api_middleware.<locals>.handle_exception at │ │
│ │                    0x7f45ac638dc0>                                       │ │
│ │          request = <starlette.requests.Request object at 0x7f45ac0b2790> │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯ │
│                                                                              │
│ /usr/local/lib/python3.9/dist-packages/starlette/middleware/base.py:46 in    │
│ call_next                                                                    │
│                                                                              │
│                           ... 25 frames hidden ...                           │
│                                                                              │
│ /usr/lib/python3.9/asyncio/locks.py:81 in __init__                           │
│                                                                              │
│    80 │   │   if loop is None:                                               │
│ ❱  81 │   │   │   self._loop = events.get_event_loop()                       │
│    82 │   │   else:                                                          │
│                                                                              │
│ ╭──────────────────────────── locals ─────────────────────────────╮          │
│ │ loop = None                                                     │          │
│ │ self = <asyncio.locks.Lock object at 0x7f45ac06b0a0 [unlocked]> │          │
│ ╰─────────────────────────────────────────────────────────────────╯          │
│                                                                              │
│ /usr/lib/python3.9/asyncio/events.py:642 in get_event_loop                   │
│                                                                              │
│   641 │   │   if self._local._loop is None:                                  │
│ ❱ 642 │   │   │   raise RuntimeError('There is no current event loop in thre │
│   643 │   │   │   │   │   │   │      % threading.current_thread().name)      │
│                                                                              │
│ ╭───────────────────────────────── locals ─────────────────────────────────╮ │
│ │ self = <asyncio.unix_events._UnixDefaultEventLoopPolicy object at        │ │
│ │        0x7f45adf50820>                                                   │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯ │
╰──────────────────────────────────────────────────────────────────────────────╯
RuntimeError: There is no current event loop in thread 'AnyIO worker thread'.

Additional information

No response

Darklobi avatar Mar 27 '23 15:03 Darklobi

same here, must be a new thing

cbg342 avatar Mar 27 '23 18:03 cbg342

Can confirm, just updated my webui installation and it broke the API I guess I have to downgrade then...

MeemeeLab avatar Mar 28 '23 04:03 MeemeeLab

Same

ousinkou avatar Mar 28 '23 06:03 ousinkou

same

shalin-okada avatar Mar 28 '23 09:03 shalin-okada

I also encountered the same problem.

prp-e avatar Mar 28 '23 09:03 prp-e

Same error on Colab. On local Windows PC - OK (just done fresh install).

vaalberith avatar Mar 28 '23 10:03 vaalberith

yep. same issue in colab

tooothl3ss avatar Mar 28 '23 11:03 tooothl3ss

If this problem is on colab, it's a Linux problem I believe since I try to make the API work on my server. Isn't there any solution?

prp-e avatar Mar 28 '23 13:03 prp-e

Could anyone solve this?

prp-e avatar Mar 28 '23 15:03 prp-e

any solution for colab?

dinilvalsan avatar Mar 28 '23 19:03 dinilvalsan

i didnt find anything yet

Darklobi avatar Mar 28 '23 20:03 Darklobi

sry wrong button

Darklobi avatar Mar 28 '23 20:03 Darklobi

Same here. I'm using 'git checkout 9377092a892687a8ae43ba5f7df44f0929ab2997' as a temporary solution

LuizHenriqueKS avatar Mar 29 '23 02:03 LuizHenriqueKS

I have the same problem

SuperKsa avatar Mar 29 '23 06:03 SuperKsa

Another workaround while keeping the latest commit is to edit the modules/api/api.py. I don't think this is a good solution though, so I don't want to make a PR.

diff --git a/modules/api/api.py b/modules/api/api.py
index 518b2a61..a9cef928 100644
--- a/modules/api/api.py
+++ b/modules/api/api.py
@@ -29,6 +29,7 @@ from modules import devices
 from typing import List
 import piexif
 import piexif.helper
+import asyncio
 
 def upscaler_to_index(name: str):
     try:
@@ -276,6 +277,15 @@ class Api:
         return script_args
 
     def text2imgapi(self, txt2imgreq: StableDiffusionTxt2ImgProcessingAPI):
+        try:
+            loop = asyncio.get_event_loop()
+        except RuntimeError as e:
+            if str(e).startswith('There is no current event loop in thread'):
+                loop = asyncio.new_event_loop()
+                asyncio.set_event_loop(loop)
+            else:
+                raise
+
         script_runner = scripts.scripts_txt2img
         if not script_runner.scripts:
             script_runner.initialize_scripts(False)

MeemeeLab avatar Mar 29 '23 23:03 MeemeeLab

same

briva avatar Mar 30 '23 00:03 briva

@MeemeeLab solution worked... thanks for this.

dinilvalsan avatar Mar 30 '23 05:03 dinilvalsan

until some1 fix this issue, @MeemeeLab solution is working fine, thanks for the help.

Darklobi avatar Mar 31 '23 09:03 Darklobi

The issue is in the source code.

def get_event_loop(self):
    """Get the event loop.
    This may be None or an instance of EventLoop.
    """
    if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
        self.set_event_loop(self.new_event_loop())

    if self._local._loop is None:
        raise RuntimeError('There is no current event loop in thread %r.'
                            % threading.current_thread().name)

    return self._local._loop

WALL-E avatar Apr 02 '23 02:04 WALL-E

The issue is in the source code.

def get_event_loop(self):
    """Get the event loop.
    This may be None or an instance of EventLoop.
    """
    if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
        self.set_event_loop(self.new_event_loop())

    if self._local._loop is None:
        raise RuntimeError('There is no current event loop in thread %r.'
                            % threading.current_thread().name)

    return self._local._loop

I belive it's internal code of asyncio, there's should be a mistake in the code, not in the library.

MeemeeLab avatar Apr 02 '23 08:04 MeemeeLab

Is there any solution to fix the error on colab?

Vuhiep190297 avatar Apr 05 '23 15:04 Vuhiep190297

Is there any solution to fix the error?

lzghades avatar Apr 07 '23 11:04 lzghades

Experiencing this issue on img2img generation as well txt2img. @MeemeeLab worked but needed to add that code snippet into both functions.

bennettwbrown avatar Apr 08 '23 10:04 bennettwbrown

Same

Doublefire-Chen avatar Apr 13 '23 08:04 Doublefire-Chen

It's been quite long since this problem has been persisting in the /sdapi/v1/txt2img

somya-15 avatar Apr 13 '23 10:04 somya-15

May I ask you to solve this problem yet? I'm also having this troublesome problem now

Pan-dz avatar Apr 23 '23 09:04 Pan-dz

Its back to normal thanks.

Darklobi avatar May 02 '23 13:05 Darklobi