Skip to content

Commit 00ebae0

Browse files
author
David Eigen
committed
revert running-related changes
1 parent 7fbd78c commit 00ebae0

File tree

4 files changed

+30
-76
lines changed

4 files changed

+30
-76
lines changed

clarifai/cli/model.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,9 @@ def download_checkpoints(model_path, out_path):
6868
help=
6969
'Specify how to test the model locally: "env" for virtual environment or "container" for Docker container. Defaults to "env".'
7070
)
71-
@click.option('--pdb', is_flag=True, help='Enable PDB debugging when testing the model locally.')
7271
@click.option(
7372
'--keep_env',
7473
is_flag=True,
75-
default=True,
7674
help=
7775
'Keep the virtual environment after testing the model locally (applicable for virtualenv mode). Defaults to False.'
7876
)
@@ -82,7 +80,7 @@ def download_checkpoints(model_path, out_path):
8280
help=
8381
'Keep the Docker image after testing the model locally (applicable for container mode). Defaults to False.'
8482
)
85-
def test_locally(model_path, pdb=False, keep_env=False, keep_image=False, mode='env'):
83+
def test_locally(model_path, keep_env=False, keep_image=False, mode='env'):
8684
"""Test model locally."""
8785
try:
8886
from clarifai.runners.models import model_run_locally
@@ -91,12 +89,9 @@ def test_locally(model_path, pdb=False, keep_env=False, keep_image=False, mode='
9189
if mode == 'container' and keep_env:
9290
raise ValueError("'keep_env' is applicable only for 'env' mode")
9391

94-
if pdb and mode == "container":
95-
raise ValueError("PDB debugging is not supported in container mode.")
96-
9792
if mode == "env":
9893
click.echo("Testing model locally in a virtual environment...")
99-
model_run_locally.main(model_path, run_model_server=False, keep_env=keep_env, use_pdb=pdb)
94+
model_run_locally.main(model_path, run_model_server=False, keep_env=keep_env)
10095
elif mode == "container":
10196
click.echo("Testing model locally inside a container...")
10297
model_run_locally.main(
@@ -130,7 +125,6 @@ def test_locally(model_path, pdb=False, keep_env=False, keep_image=False, mode='
130125
@click.option(
131126
'--keep_env',
132127
is_flag=True,
133-
default=True,
134128
help=
135129
'Keep the virtual environment after testing the model locally (applicable for virtualenv mode). Defaults to False.'
136130
)

clarifai/runners/models/model_builder.py

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,6 @@ def create_model_instance(self, load_model=True):
104104
model.load_model()
105105
return model
106106

107-
def create_error_model_instance(self, exception: Exception):
108-
"""
109-
Create an instance of the model class that just raises the given exception.
110-
"""
111-
return ErrorModel(exception)
112-
113107
def _validate_folder(self, folder):
114108
if folder == ".":
115109
folder = "" # will getcwd() next which ends with /
@@ -647,24 +641,6 @@ def monitor_model_build(self):
647641
return False
648642

649643

650-
class ErrorModel(ModelClass):
651-
652-
def __init__(self, exception):
653-
self.exception = exception
654-
655-
def load_model(self):
656-
pass
657-
658-
def predict(self, *args, **kwargs):
659-
raise self.exception from self.exception
660-
661-
def generate(self, *args, **kwargs):
662-
raise self.exception from self.exception
663-
664-
def stream(self, *args, **kwargs):
665-
raise self.exception from self.exception
666-
667-
668644
def upload_model(folder, download_checkpoints, skip_dockerfile):
669645
builder = ModelBuilder(folder)
670646
if download_checkpoints:

clarifai/runners/models/model_run_locally.py

Lines changed: 28 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import traceback
1111
import venv
1212

13-
import platformdirs
1413
from clarifai_grpc.grpc.api import resources_pb2, service_pb2
1514
from clarifai_grpc.grpc.api.status import status_code_pb2, status_pb2
1615

@@ -53,39 +52,37 @@ def _get_env_executable(self):
5352

5453
def create_temp_venv(self):
5554
"""Create a temporary virtual environment."""
56-
venv_key = hashlib.md5(self.model_path.encode('utf-8')).hexdigest()
57-
temp_dir = os.path.join(platformdirs.user_cache_dir('clarifai', 'clarifai'), 'venvs', venv_key)
55+
requirements_hash = self._requirements_hash()
56+
57+
temp_dir = os.path.join(tempfile.gettempdir(), str(requirements_hash))
5858
venv_dir = os.path.join(temp_dir, "venv")
5959

6060
if os.path.exists(temp_dir):
61-
logger.info(f"Using previous virtual environment at {venv_dir}")
61+
logger.info(f"Using previous virtual environment at {temp_dir}")
62+
use_existing_venv = True
6263
else:
63-
logger.info("Creating virtual environment...")
64+
logger.info("Creating temporary virtual environment...")
65+
use_existing_venv = False
6466
venv.create(venv_dir, with_pip=True)
6567
logger.info(f"Created temporary virtual environment at {venv_dir}")
6668

6769
self.venv_dir = venv_dir
6870
self.temp_dir = temp_dir
6971
self.python_executable, self.pip_executable = self._get_env_executable()
7072

73+
return use_existing_venv
74+
7175
def install_requirements(self):
7276
"""Install the dependencies from requirements.txt and Clarifai."""
73-
if os.path.exists(os.path.join(self.temp_dir, "requirements.txt")):
74-
requirements = open(self.requirements_file).read()
75-
installed_requirements = open(os.path.join(self.temp_dir, "requirements.txt")).read()
76-
if requirements == installed_requirements:
77-
logger.info("Requirements already installed.")
78-
return
7977
_, pip_executable = self._get_env_executable()
8078
try:
8179
logger.info(
8280
f"Installing requirements from {self.requirements_file}... in the virtual environment {self.venv_dir}"
8381
)
84-
logger.info("Installing model requirements...")
8582
subprocess.check_call([pip_executable, "install", "-r", self.requirements_file])
83+
logger.info("Installing Clarifai package...")
84+
subprocess.check_call([pip_executable, "install", "clarifai"])
8685
logger.info("Requirements installed successfully!")
87-
with open(os.path.join(self.temp_dir, "requirements.txt"), "w") as f:
88-
f.write(open(self.requirements_file).read())
8986
except subprocess.CalledProcessError as e:
9087
logger.error(f"Error installing requirements: {e}")
9188
self.clean_up()
@@ -180,12 +177,9 @@ def _run_model_inference(self, model):
180177
))
181178

182179
if stream_response:
183-
try:
184-
stream_first_res = next(stream_response)
185-
except StopIteration:
186-
stream_first_res = None
187-
if stream_first_res is None or stream_first_res.outputs[0].status.code != status_code_pb2.SUCCESS:
188-
logger.error(f"Model stream failed: {stream_first_res}")
180+
stream_first_res = next(stream_response)
181+
if stream_first_res.outputs[0].status.code != status_code_pb2.SUCCESS:
182+
logger.error(f"Moddel Prediction failed: {stream_first_res}")
189183
else:
190184
logger.info(
191185
f"Model Prediction succeeded for stream and first response: {stream_first_res}")
@@ -197,7 +191,7 @@ def _run_test(self):
197191
# send an inference.
198192
self._run_model_inference(model)
199193

200-
def test_model(self, use_pdb=False):
194+
def test_model(self):
201195
"""Test the model by running it locally in the virtual environment."""
202196

203197
import_path = repr(os.path.dirname(os.path.abspath(__file__)))
@@ -207,12 +201,8 @@ def test_model(self, use_pdb=False):
207201
f"sys.path.append({import_path}); "
208202
f"from model_run_locally import ModelRunLocally; "
209203
f"ModelRunLocally({model_path})._run_test()")
210-
main_file = tempfile.NamedTemporaryFile(mode="w")
211-
with open(main_file.name, "w") as f:
212-
f.write(command_string)
213204

214-
pdb_args = ["-m", "pdb"] if use_pdb else []
215-
command = [self.python_executable, *pdb_args, main_file.name]
205+
command = [self.python_executable, "-c", command_string]
216206
process = None
217207
try:
218208
logger.info("Testing the model locally...")
@@ -242,13 +232,12 @@ def test_model(self, use_pdb=False):
242232
process.kill()
243233

244234
# run the model server
245-
def run_model_server(self, port=8080, use_pdb=False):
235+
def run_model_server(self, port=8080):
246236
"""Run the Clarifai Runners's model server."""
247237

248-
pdb_args = ["-m", "pdb"] if use_pdb else []
249238
command = [
250-
self.python_executable, *pdb_args, "-m", "clarifai.runners.server", "--model_path",
251-
self.model_path, "--grpc", "--port",
239+
self.python_executable, "-m", "clarifai.runners.server", "--model_path", self.model_path,
240+
"--grpc", "--port",
252241
str(port)
253242
]
254243
try:
@@ -473,19 +462,16 @@ def remove_docker_image(self, image_name):
473462
def clean_up(self):
474463
"""Clean up the temporary virtual environment."""
475464
if os.path.exists(self.temp_dir):
476-
logger.info("Cleaning up virtual environment...")
465+
logger.info("Cleaning up temporary virtual environment...")
477466
shutil.rmtree(self.temp_dir)
478467

479468

480-
def main(
481-
model_path,
482-
run_model_server=False,
483-
inside_container=False,
484-
port=8080,
485-
keep_env=True,
486-
keep_image=False,
487-
use_pdb=False,
488-
):
469+
def main(model_path,
470+
run_model_server=False,
471+
inside_container=False,
472+
port=8080,
473+
keep_env=False,
474+
keep_image=False):
489475

490476
if not os.environ['CLARIFAI_PAT']:
491477
logger.error(
@@ -527,9 +513,9 @@ def main(
527513
if not use_existing_env:
528514
manager.install_requirements()
529515
if run_model_server:
530-
manager.run_model_server(port, use_pdb=use_pdb)
516+
manager.run_model_server(port)
531517
else:
532-
manager.test_model(use_pdb=use_pdb)
518+
manager.test_model()
533519
finally:
534520
if not keep_env:
535521
manager.clean_up()

requirements.txt

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,3 @@ Pillow>=9.5.0
99
tabulate>=0.9.0
1010
fsspec==2024.6.1
1111
click==8.1.7
12-
platformdirs==4.3.6
13-
requests

0 commit comments

Comments
 (0)