Skip to content

Commit

Permalink
coreml: move prediction onto background thread
Browse files Browse the repository at this point in the history
  • Loading branch information
koush committed Mar 16, 2023
1 parent 5c9f62e commit 1c8ff24
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
4 changes: 2 additions & 2 deletions plugins/coreml/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion plugins/coreml/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@
"devDependencies": {
"@scrypted/sdk": "file:../../sdk"
},
"version": "0.0.26"
"version": "0.0.27"
}
13 changes: 11 additions & 2 deletions plugins/coreml/src/coreml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
import coremltools as ct
import os
from PIL import Image
import asyncio
import concurrent.futures

predictExecutor = concurrent.futures.ThreadPoolExecutor(2, "CoreML-Predict")

def parse_label_contents(contents: str):
lines = contents.splitlines()
Expand Down Expand Up @@ -36,6 +40,7 @@ def __init__(self, nativeId: str | None = None):
labels_contents = scrypted_sdk.zip.open(
'fs/coco_labels.txt').read().decode('utf8')
self.labels = parse_label_contents(labels_contents)
self.loop = asyncio.get_event_loop()

# width, height, channels
def get_input_details(self) -> Tuple[int, int, int]:
Expand All @@ -44,8 +49,12 @@ def get_input_details(self) -> Tuple[int, int, int]:
def get_input_size(self) -> Tuple[float, float]:
return (self.inputwidth, self.inputheight)

def detect_once(self, input: Image.Image, settings: Any, src_size, cvss):
out_dict = self.model.predict({'image': input, 'confidenceThreshold': .2 })
async def detect_once(self, input: Image.Image, settings: Any, src_size, cvss):
# run in executor if this is the plugin loop
if asyncio.get_event_loop() is self.loop:
out_dict = await asyncio.get_event_loop().run_in_executor(predictExecutor, lambda: self.model.predict({'image': input, 'confidenceThreshold': .2 }))
else:
out_dict = self.model.predict({'image': input, 'confidenceThreshold': .2 })

coordinatesList = out_dict['coordinates']

Expand Down

0 comments on commit 1c8ff24

Please sign in to comment.