HumeAI / hume-python-sdk

Python client for Hume AI
https://dev.hume.ai
MIT License
90 stars 24 forks source link

RuntimeError: asyncio.run() cannot be called from a running event loop [web socket code] #40

Closed aureliuszi closed 1 year ago

aureliuszi commented 1 year ago

Hello friendly HumeAI team!

I am trying to run the following code in Jupyter Notebook:

import asyncio

from hume import HumeStreamClient, StreamSocket
from hume.config import FaceConfig

async def main():
    client = HumeStreamClient("<your-api-key>")
    configs = [FaceConfig(identify_faces=True)]
    async with client.connect(configs) as socket:
        socket: StreamSocket
        result = await socket.send_file("<your-image-filepath>")
        print(result)

asyncio.run(main())

But I get this error. Please help!


RuntimeError Traceback (most recent call last) Cell In[9], line 9 6 result = await socket.send_file("raw-social-media-data/bobo.mp4") 7 print(result) ----> 9 asyncio.run(main())

File ~\AppData\Local\Continuum\anaconda3\envs\python38\lib\asyncio\runners.py:33, in run(main, debug)
      9 """Execute the coroutine and return the result.
     10 
     11 This function runs the passed coroutine, taking care of
   (...)
     30     asyncio.run(main())
     31 """
     32 if events._get_running_loop() is not None:
---> 33     raise RuntimeError(
     34         "asyncio.run() cannot be called from a running event loop")
     36 if not coroutines.iscoroutine(main):
     37     raise ValueError("a coroutine was expected, got {!r}".format(main))

RuntimeError: asyncio.run() cannot be called from a running event loop
gregorybchris commented 1 year ago

Good question @aureliuszi! Jupyter has its own async event loop, so you'll need to merge in the Hume streaming event loop.

Hope this example code helps:

import asyncio

from hume import HumeStreamClient, StreamSocket
from hume.config import FaceConfig

async def main():
    client = HumeStreamClient("<your-api-key>")
    configs = [FaceConfig(identify_faces=True)]
    async with client.connect(configs) as socket:
        socket: StreamSocket
        result = await socket.send_file("<your-image-filepath>")
        print(result)

# Jupyter has its own async event loop, so merge main into the Jupyter event loop
loop = asyncio.get_event_loop()
loop.create_task(main())
aureliuszi commented 1 year ago

Wow, thank you so much for this! It is really appreciated!

I am trying to print the results of the analysis but I am still unable to. I tried to modify the code like so but to no avail:

async def main():
    client = HumeStreamClient("api-key")
    configs = [FaceConfig(identify_faces=True)]
    async with client.connect(configs) as socket:
        socket: StreamSocket
        result = await socket.send_file("raw-social-media-data/bobo.mp4")
        print(result)
        **result.download("predictions-local.json")**

loop = asyncio.get_event_loop()
loop.create_task(main()) 
gregorybchris commented 1 year ago

Hi @aureliuszi, calling await socket.send_file() will return the results to you in a dictionary format. There's no need to do result.download(). If you follow the code I sent above, these two lines are all you need to print out the results.

result = await socket.send_file("<your-image-filepath>")
print(result)
gregorybchris commented 1 year ago

One thing to look out for, @aureliuszi, is that exceptions will not be raised from within an asyncio Task. You can use this example to make sure exceptions get printed:

import asyncio

from hume import HumeStreamClient, StreamSocket
from hume.config import FaceConfig

async def main():
    client = HumeStreamClient("<your-api-key>")
    configs = [FaceConfig(identify_faces=True)]
    async with client.connect(configs) as socket:
        socket: StreamSocket

        try:
            result = await socket.send_file("<your-image-filepath>")
        except Exception as exc:
            print(exc)
            raise
        print(result)

loop = asyncio.get_event_loop()
loop.create_task(main())
gregorybchris commented 1 year ago

Since this has been open for a week I'll assume everything is resolved and close this issue