Search code examples
pythonpython-asynciogenerative-adversarial-networkosc

Using OSC to update sliders in GANSpace


I'm trying to update the sliders in interactive.py from GANSpace with messages from python-osc. Ideally the on_draw function should run after receiving a series of OSC messages. But I'm having trouble with implementing it, because the serve.forever() function is blocking and i can't figure out how to implement the async version.

When i do like this:

def set_slider_osc(addr, args):
    print("[{0}] ~ {1}".format(args, addr))
    #print(re.split('/',addr)[2])
    if "/0" in addr:
        ui_state.sliders[0].set(args)
    if "/1" in addr:
        ui_state.sliders[1].set(args)

async def loop():
    while not pending_close:
        root.update()
        app.update()
        on_draw()
        reposition_toolbar()
        await asyncio.sleep(0)


async def init_main():
    setup_model()
    setup_ui()
    resample_latent()

    pending_close = False
    
    dispatcher = dispatcher.Dispatcher()
    dispatcher.map("/Chroma/*", set_slider_osc)
    
    server = AsyncIOOSCUDPServer(("127.0.0.1", 8000), dispatcher, asyncio.get_event_loop())
    transport, protocol = await server.create_serve_endpoint()  # Create datagram endpoint and start serving

    await loop()  # Enter main loop of program

    transport.close()  # Clean up serve endpoint
    root.destroy()

#
if __name__=='__main__':
    await init_main()

I get the error that i try to run 'await' outside a function and another way i tried it seemed like there already was a main loop running and therefore couldn't run a new..

I know it's allot to aks people to install GANSpace, but hope someone may shine some light on how one could do this.


Solution

  • await cannot be used outside of a function defined with async def. You are trying to use it outside a function. The fix is to run init_main in an event loop.

    import asyncio
    asyncio.run(init_main())