Skip to content

Commit f90c6d2

Browse files
authored
fix: use lazy import to avoid extra dependencies (#3940)
* fix: use lazy import to avoid extra dependencies * update * update
1 parent 8e822d1 commit f90c6d2

File tree

9 files changed

+81
-60
lines changed

9 files changed

+81
-60
lines changed

libs/ultra-infer/VERSION_NUMBER

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.1.0
1+
1.1.1

libs/ultra-infer/python/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ tqdm
44
numpy<2
55
# Compatible with paddlex
66
opencv-contrib-python
7+
pyyaml

libs/ultra-infer/python/setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,6 @@ def build_extensions(self):
435435
################################################################################
436436

437437
extras_require["pyonly"] = [
438-
"pyyaml",
439438
"pillow<10.0.0",
440439
"pandas>=0.25.0,<=1.3.5",
441440
"pycocotools",

libs/ultra-infer/python/ultra_infer/py_only/ts/processors.py

Lines changed: 67 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,7 @@
1414

1515
from typing import List, Optional, Union, Dict
1616

17-
import chinese_calendar
18-
import joblib
1917
import numpy as np
20-
import pandas as pd
21-
from pandas.tseries.offsets import DateOffset, Easter, Day
22-
from pandas.tseries import holiday as hd
23-
from sklearn.preprocessing import StandardScaler
2418

2519
from ..base import PyOnlyProcessor
2620

@@ -35,51 +29,6 @@
3529
]
3630

3731
_MAX_WINDOW = 183 + 17
38-
_EASTER_SUNDAY = hd.Holiday("Easter Sunday", month=1, day=1, offset=[Easter(), Day(0)])
39-
_NEW_YEARS_DAY = hd.Holiday("New Years Day", month=1, day=1)
40-
_SUPER_BOWL = hd.Holiday(
41-
"Superbowl", month=2, day=1, offset=DateOffset(weekday=hd.SU(1))
42-
)
43-
_MOTHERS_DAY = hd.Holiday(
44-
"Mothers Day", month=5, day=1, offset=DateOffset(weekday=hd.SU(2))
45-
)
46-
_INDEPENDENCE_DAY = hd.Holiday("Independence Day", month=7, day=4)
47-
_CHRISTMAS_EVE = hd.Holiday("Christmas", month=12, day=24)
48-
_CHRISTMAS_DAY = hd.Holiday("Christmas", month=12, day=25)
49-
_NEW_YEARS_EVE = hd.Holiday("New Years Eve", month=12, day=31)
50-
_BLACK_FRIDAY = hd.Holiday(
51-
"Black Friday",
52-
month=11,
53-
day=1,
54-
offset=[pd.DateOffset(weekday=hd.TH(4)), Day(1)],
55-
)
56-
_CYBER_MONDAY = hd.Holiday(
57-
"Cyber Monday",
58-
month=11,
59-
day=1,
60-
offset=[pd.DateOffset(weekday=hd.TH(4)), Day(4)],
61-
)
62-
63-
_HOLYDAYS = [
64-
hd.EasterMonday,
65-
hd.GoodFriday,
66-
hd.USColumbusDay,
67-
hd.USLaborDay,
68-
hd.USMartinLutherKingJr,
69-
hd.USMemorialDay,
70-
hd.USPresidentsDay,
71-
hd.USThanksgivingDay,
72-
_EASTER_SUNDAY,
73-
_NEW_YEARS_DAY,
74-
_SUPER_BOWL,
75-
_MOTHERS_DAY,
76-
_INDEPENDENCE_DAY,
77-
_CHRISTMAS_EVE,
78-
_CHRISTMAS_DAY,
79-
_NEW_YEARS_EVE,
80-
_BLACK_FRIDAY,
81-
_CYBER_MONDAY,
82-
]
8332

8433

8534
def _cal_year(
@@ -151,12 +100,16 @@ def _cal_weekofyear(
151100
def _cal_holiday(
152101
x: np.datetime64,
153102
):
103+
import chinese_calendar
104+
154105
return float(chinese_calendar.is_holiday(x))
155106

156107

157108
def _cal_workday(
158109
x: np.datetime64,
159110
):
111+
import chinese_calendar
112+
160113
return float(chinese_calendar.is_workday(x))
161114

162115

@@ -192,13 +145,15 @@ def _cal_monthofyear(
192145

193146

194147
def _load_from_one_dataframe(
195-
data: Union[pd.DataFrame, pd.Series],
148+
data: Union["pd.DataFrame", "pd.Series"], # noqa: F821
196149
time_col: Optional[str] = None,
197150
value_cols: Optional[Union[List[str], str]] = None,
198151
freq: Optional[Union[str, int]] = None,
199152
drop_tail_nan: bool = False,
200153
dtype: Optional[Union[type, Dict[str, type]]] = None,
201154
):
155+
import pandas as pd
156+
202157
series_data = None
203158
if value_cols is None:
204159
if isinstance(data, pd.Series):
@@ -261,7 +216,7 @@ def _load_from_one_dataframe(
261216

262217

263218
def _load_from_dataframe(
264-
df: pd.DataFrame,
219+
df: "pd.DataFrame", # noqa: F821
265220
group_id: str = None,
266221
time_col: Optional[str] = None,
267222
target_cols: Optional[Union[List[str], str]] = None,
@@ -350,6 +305,8 @@ def _load_from_dataframe(
350305

351306
def _distance_to_holiday(holiday):
352307
def _distance_to_day(index):
308+
import pandas as pd
309+
353310
holiday_date = holiday.dates(
354311
index - pd.Timedelta(days=_MAX_WINDOW),
355312
index + pd.Timedelta(days=_MAX_WINDOW),
@@ -367,6 +324,8 @@ def _distance_to_day(index):
367324
def _to_time_features(
368325
dataset, freq, feature_cols, extend_points, inplace: bool = False
369326
):
327+
import pandas as pd
328+
370329
new_ts = dataset
371330
if not inplace:
372331
new_ts = dataset.copy()
@@ -405,6 +364,57 @@ def _to_time_features(
405364
)
406365

407366
else:
367+
from pandas.tseries.offsets import DateOffset, Easter, Day
368+
from pandas.tseries import holiday as hd
369+
from sklearn.preprocessing import StandardScaler
370+
371+
_EASTER_SUNDAY = hd.Holiday(
372+
"Easter Sunday", month=1, day=1, offset=[Easter(), Day(0)]
373+
)
374+
_NEW_YEARS_DAY = hd.Holiday("New Years Day", month=1, day=1)
375+
_SUPER_BOWL = hd.Holiday(
376+
"Superbowl", month=2, day=1, offset=DateOffset(weekday=hd.SU(1))
377+
)
378+
_MOTHERS_DAY = hd.Holiday(
379+
"Mothers Day", month=5, day=1, offset=DateOffset(weekday=hd.SU(2))
380+
)
381+
_INDEPENDENCE_DAY = hd.Holiday("Independence Day", month=7, day=4)
382+
_CHRISTMAS_EVE = hd.Holiday("Christmas", month=12, day=24)
383+
_CHRISTMAS_DAY = hd.Holiday("Christmas", month=12, day=25)
384+
_NEW_YEARS_EVE = hd.Holiday("New Years Eve", month=12, day=31)
385+
_BLACK_FRIDAY = hd.Holiday(
386+
"Black Friday",
387+
month=11,
388+
day=1,
389+
offset=[pd.DateOffset(weekday=hd.TH(4)), Day(1)],
390+
)
391+
_CYBER_MONDAY = hd.Holiday(
392+
"Cyber Monday",
393+
month=11,
394+
day=1,
395+
offset=[pd.DateOffset(weekday=hd.TH(4)), Day(4)],
396+
)
397+
398+
_HOLYDAYS = [
399+
hd.EasterMonday,
400+
hd.GoodFriday,
401+
hd.USColumbusDay,
402+
hd.USLaborDay,
403+
hd.USMartinLutherKingJr,
404+
hd.USMemorialDay,
405+
hd.USPresidentsDay,
406+
hd.USThanksgivingDay,
407+
_EASTER_SUNDAY,
408+
_NEW_YEARS_DAY,
409+
_SUPER_BOWL,
410+
_MOTHERS_DAY,
411+
_INDEPENDENCE_DAY,
412+
_CHRISTMAS_EVE,
413+
_CHRISTMAS_DAY,
414+
_NEW_YEARS_EVE,
415+
_BLACK_FRIDAY,
416+
_CYBER_MONDAY,
417+
]
408418
holidays_col = []
409419
for i, H in enumerate(_HOLYDAYS):
410420
v = tf_kcov[time_col].apply(_distance_to_holiday(H))
@@ -448,6 +458,8 @@ def __call__(self, data):
448458

449459
class Normalize(PyOnlyProcessor):
450460
def __init__(self, scale_path, params_info):
461+
import joblib
462+
451463
super().__init__()
452464
self._scaler = joblib.load(scale_path)
453465
self._params_info = params_info
@@ -469,6 +481,8 @@ def __call__(self, data):
469481

470482
class Denormalize(PyOnlyProcessor):
471483
def __init__(self, scale_path, params_info):
484+
import joblib
485+
472486
super().__init__()
473487
self._scaler = joblib.load(scale_path)
474488
self._params_info = params_info

libs/ultra-infer/python/ultra_infer/py_only/vision/processors.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
import numpy as np
1818
import cv2
19-
from PIL import Image
2019

2120
from ..base import PyOnlyProcessor
2221

@@ -375,6 +374,8 @@ def __init__(self, rec_image_shape=(3, 48, 320)):
375374
self.rec_image_shape = rec_image_shape
376375

377376
def pad_(self, img, divable=32):
377+
from PIL import Image
378+
378379
threshold = 128
379380
data = np.array(img.convert("LA"))
380381
if data[..., -1].var() == 0:
@@ -407,6 +408,8 @@ def minmax_size_(
407408
max_dimensions,
408409
min_dimensions,
409410
):
411+
from PIL import Image
412+
410413
if max_dimensions is not None:
411414
ratios = [a / b for a, b in zip(img.size, max_dimensions)]
412415
if any([r > 1 for r in ratios]):
@@ -426,6 +429,8 @@ def minmax_size_(
426429

427430
def norm_img_latexocr(self, img):
428431
# CAN only predict gray scale image
432+
from PIL import Image
433+
429434
shape = (1, 1, 3)
430435
mean = [0.7931, 0.7931, 0.7931]
431436
std = [0.1738, 0.1738, 0.1738]

libs/ultra-infer/python/ultra_infer/ts/anomalydetection/ppts/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
import os
1818
from copy import deepcopy
1919
import numpy as np
20-
import pandas as pd
2120
from typing import List
2221
from dataclasses import dataclass
2322

libs/ultra-infer/python/ultra_infer/ts/forecasting/ppts/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
import os
1818
from copy import deepcopy
1919
import numpy as np
20-
import pandas as pd
2120
from typing import List
2221
from dataclasses import dataclass
2322

@@ -127,6 +126,8 @@ def __init__(self, config, scaler_file):
127126
self._processor_chain = PyOnlyProcessorChain(processors)
128127

129128
def run(self, data):
129+
import pandas as pd
130+
130131
ori_ts = data["ori_ts"]
131132
pred = data["pred"]
132133
if ori_ts.get("past_target", None) is not None:

libs/ultra-infer/python/ultra_infer/vision/ocr/ppocr/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
import tempfile
2222
from dataclasses import dataclass
2323

24-
from tokenizers import Tokenizer as TokenizerFast
2524

2625
from .... import ModelFormat, UltraInferModel
2726
from .... import c_lib_wrap as C
@@ -1880,6 +1879,8 @@ class _PyOnlyFormulaRecognitionResult(object):
18801879

18811880
class LaTeXOCRDecode(object):
18821881
def __init__(self, character_list=None):
1882+
from tokenizers import Tokenizer as TokenizerFast
1883+
18831884
super().__init__()
18841885
character_list = character_list
18851886
temp_path = tempfile.gettempdir()

libs/ultra-infer/python/ultra_infer/vision/segmentation/ppseg/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
from typing import List
2020

2121
import numpy as np
22-
from skimage import morphology
2322

2423
from .... import UltraInferModel, ModelFormat
2524
from .... import c_lib_wrap as C
@@ -299,6 +298,8 @@ def _build_processors(self, config):
299298

300299
class _PyOnlyAnomalyDetectionPostprocessor(object):
301300
def run(self, data):
301+
from skimage import morphology
302+
302303
score_map = data["score_map"]
303304

304305
thred = 0.01

0 commit comments

Comments
 (0)