Skip to content

Commit d021272

Browse files
author
Diego Ardila
committed
Added nest_asyncio so we can nest asyncio loops inside jupyter notebooks
1 parent 7828066 commit d021272

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

nucleus/__init__.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,11 @@
5555
import logging
5656
import os
5757
import urllib.request
58+
from asyncio.tasks import Task
5859
from typing import Any, Dict, List, Optional, Union
5960

6061
import aiohttp
62+
import nest_asyncio
6163
import pkg_resources
6264
import requests
6365
import tqdm
@@ -67,11 +69,11 @@
6769

6870
from .annotation import (
6971
BoxAnnotation,
72+
CuboidAnnotation,
73+
Point,
7074
PolygonAnnotation,
7175
Segment,
7276
SegmentationAnnotation,
73-
Point,
74-
CuboidAnnotation,
7577
)
7678
from .constants import (
7779
ANNOTATION_METADATA_SCHEMA_KEY,
@@ -81,8 +83,8 @@
8183
DATASET_ID_KEY,
8284
DATASET_ITEM_IDS_KEY,
8385
DEFAULT_NETWORK_TIMEOUT_SEC,
84-
EMBEDDINGS_URL_KEY,
8586
EMBEDDING_DIMENSION_KEY,
87+
EMBEDDINGS_URL_KEY,
8688
ERROR_ITEMS,
8789
ERROR_PAYLOAD,
8890
ERRORS_KEY,
@@ -462,14 +464,20 @@ def get_files(batch):
462464
files_per_request.append(get_files(batch))
463465
payload_items.append(batch)
464466

465-
loop = asyncio.get_event_loop()
466-
responses = loop.run_until_complete(
467-
self.make_many_files_requests_asynchronously(
468-
files_per_request,
469-
f"dataset/{dataset_id}/append",
470-
)
467+
future = self.make_many_files_requests_asynchronously(
468+
files_per_request,
469+
f"dataset/{dataset_id}/append",
471470
)
472471

472+
try:
473+
loop = asyncio.get_running_loop()
474+
except RuntimeError: # no event loop running:
475+
loop = asyncio.new_event_loop()
476+
responses = loop.run_until_complete(future)
477+
else:
478+
nest_asyncio.apply(loop)
479+
return asyncio.run(loop.create_task(future))
480+
473481
def close_files(request_items):
474482
for item in request_items:
475483
# file buffer in location [1][1]

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ requests = "^2.23.0"
3737
tqdm = "^4.41.0"
3838
dataclasses = { version = "^0.7", python = "^3.6.1, <3.7" }
3939
aiohttp = "^3.7.4"
40+
nest-asyncio = "^1.5.1"
4041

4142
[tool.poetry.dev-dependencies]
4243
poetry = "^1.1.5"

0 commit comments

Comments
 (0)