1010import traceback
1111import venv
1212
13- import platformdirs
1413from clarifai_grpc .grpc .api import resources_pb2 , service_pb2
1514from 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 ()
0 commit comments