|
1 | 1 | import os
|
2 |
| -from types import ModuleType |
3 | 2 | from typing import Union
|
4 | 3 | import dill
|
5 | 4 | import pandas as pd
|
|
8 | 7 | from type_infer.infer import infer_types
|
9 | 8 | from lightwood.api.predictor import PredictorInterface
|
10 | 9 | from lightwood.api.json_ai import generate_json_ai
|
11 |
| -import tempfile |
12 |
| -from lightwood.api.json_ai import code_from_json_ai as _code_from_json_ai |
13 |
| -import importlib.util |
| 10 | +from lightwood.helpers.codegen import code_from_json_ai as _code_from_json_ai, _module_from_code, _predictor_from_code |
14 | 11 | import sys
|
15 |
| -import random |
16 |
| -import string |
17 | 12 | import gc
|
18 | 13 | import time
|
19 | 14 | from lightwood.helpers.log import log
|
@@ -107,10 +102,7 @@ def predictor_from_code(code: str) -> PredictorInterface:
|
107 | 102 |
|
108 | 103 | :returns: A lightwood ``Predictor`` object
|
109 | 104 | """
|
110 |
| - module_name = ''.join(random.choices(string.ascii_uppercase + string.digits, k=12)) |
111 |
| - module_name += str(time.time()).replace('.', '') |
112 |
| - predictor = _module_from_code(code, module_name).Predictor() |
113 |
| - return predictor |
| 105 | + return _predictor_from_code(code) |
114 | 106 |
|
115 | 107 |
|
116 | 108 | def code_from_problem(df: pd.DataFrame, problem_definition: Union[ProblemDefinition, dict]) -> str:
|
@@ -162,31 +154,6 @@ def predictor_from_state(state_file: str, code: str = None) -> PredictorInterfac
|
162 | 154 | return predictor
|
163 | 155 |
|
164 | 156 |
|
165 |
| -def _module_from_code(code: str, module_name: str) -> ModuleType: |
166 |
| - """ |
167 |
| - Create a python module (containing the generated ``Predictor`` class) from the code. This is both a python object and an associated temporary file on your filesystem |
168 |
| -
|
169 |
| - :param code: The ``Predictor``'s code in text form |
170 |
| - :param module_name: The name of the newly created module |
171 |
| -
|
172 |
| - :returns: A python module object |
173 |
| - """ # noqa |
174 |
| - dirname = tempfile.gettempdir() |
175 |
| - filename = os.urandom(24).hex() + str(time.time()).replace('.', '') + '.py' |
176 |
| - path = os.path.join(dirname, filename) |
177 |
| - if 'LIGHTWOOD_DEV_SAVE_TO' in os.environ: |
178 |
| - path = os.environ['LIGHTWOOD_DEV_SAVE_TO'] |
179 |
| - |
180 |
| - with open(path, 'wb') as fp: |
181 |
| - fp.write(code.encode('utf-8')) |
182 |
| - spec = importlib.util.spec_from_file_location(module_name, fp.name) |
183 |
| - temp_module = importlib.util.module_from_spec(spec) |
184 |
| - sys.modules[module_name] = temp_module |
185 |
| - spec.loader.exec_module(temp_module) |
186 |
| - |
187 |
| - return temp_module |
188 |
| - |
189 |
| - |
190 | 157 | def predictor_from_json_ai(json_ai: JsonAI) -> PredictorInterface:
|
191 | 158 | """
|
192 | 159 | Creates a ready-to-train ``Predictor`` object based on the details you specified inside your JsonAI.
|
|
0 commit comments