Skip to content

Commit fc13600

Browse files
committed
use optional import
1 parent 50a8551 commit fc13600

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

clarifai/client/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
MAX_RANGE_SIZE, MIN_CHUNK_SIZE, MIN_RANGE_SIZE,
2525
MODEL_EXPORT_TIMEOUT, RANGE_SIZE, TRAINABLE_MODEL_TYPES)
2626
from clarifai.errors import UserError
27+
from clarifai.runners.utils import video_utils
2728
from clarifai.urls.helper import ClarifaiUrlHelper
2829
from clarifai.utils.logging import logger
2930
from clarifai.utils.misc import BackoffIterator
@@ -1204,7 +1205,6 @@ def stream_by_video_file(self,
12041205
# by getting the original start time ffprobe and either sending that to the model so it can adjust
12051206
# with the ts of the first frame (too fragile to do all of this adjustment in the client input stream)
12061207
# or by adjusting the timestamps in the output stream
1207-
from clarifai.runners.utils import video_utils
12081208
stream = video_utils.convert_to_streamable(filepath)
12091209

12101210
# TODO accumulate reads to fill the chunk size

clarifai/runners/utils/video_utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
import tempfile
44
import threading
55

6-
import av
76
import requests
87

98
from clarifai.runners.utils import stream_utils
9+
from clarifai.utils.misc import optional_import
10+
11+
av = optional_import("av", pip_package="av")
1012

1113

1214
def stream_frames_from_url(url, download_ok=True):

clarifai/utils/misc.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import importlib
12
import os
23
import re
34
import uuid
@@ -6,6 +7,29 @@
67
from clarifai.errors import UserError
78

89

10+
def optional_import(module_name: str, pip_package: str = None):
11+
"""Import a module if it exists.
12+
Otherwise, return an object that will raise an error when accessed.
13+
"""
14+
try:
15+
return importlib.import_module(module_name)
16+
except ImportError:
17+
return _MissingModule(module_name, pip_package=pip_package)
18+
19+
20+
class _MissingModule:
21+
"""Object that raises an error when accessed."""
22+
23+
def __init__(self, module_name, pip_package=None):
24+
self.module_name = module_name
25+
self.message = f"Module `{module_name}` is not installed."
26+
if pip_package:
27+
self.message += f" Please install it with `pip install {pip_package}`."
28+
29+
def __getattr__(self, name):
30+
raise ImportError(self.message)
31+
32+
933
class Chunker:
1034
"""Split an input sequence into small chunks."""
1135

0 commit comments

Comments
 (0)