104104# used internally to set constants that are shared between separate processes. They are not meant to be
105105# to be overriden by the user.
106106os .environ ["_TFL_SOURCE_CODE_DIR" ] = dirs .TFL_SOURCE_CODE_DIR
107- # The temporary image directory for transformerlab (default; per-request overrides computed in routes)
108- temp_image_dir = storage .join (get_workspace_dir (), "temp" , "images" )
109- os .environ ["TLAB_TEMP_IMAGE_DIR" ] = str (temp_image_dir )
110107
111108
112109@asynccontextmanager
113110async def lifespan (app : FastAPI ):
114111 """Docs on lifespan events: https://fastapi.tiangolo.com/advanced/events/"""
115112 # Do the following at API Startup:
116113 print_launch_message ()
114+ # Initialize directories early
115+ from transformerlab .shared import dirs as shared_dirs
116+
117+ await shared_dirs .initialize_dirs ()
118+
119+ # Set the temporary image directory for transformerlab (computed async)
120+ temp_image_dir = storage .join (await get_workspace_dir (), "temp" , "images" )
121+ os .environ ["TLAB_TEMP_IMAGE_DIR" ] = str (temp_image_dir )
117122 # Validate cloud credentials early - fail fast if missing
118123 validate_cloud_credentials ()
119- galleries .update_gallery_cache ()
124+ await galleries .update_gallery_cache ()
120125 spawn_fastchat_controller_subprocess ()
121126 await db .init () # This now runs Alembic migrations internally
122127 print ("✅ SEED DATA" )
123128 # Initialize experiments
124- seed_default_experiments ()
129+ await seed_default_experiments ()
125130 # Seed default admin user
126131 await seed_default_admin_user ()
127132 # Cancel any running jobs
128- cancel_in_progress_jobs ()
133+ await cancel_in_progress_jobs ()
129134
130135 # Create buckets for all existing teams if TFL_API_STORAGE_URI is enabled
131136 if os .getenv ("TFL_API_STORAGE_URI" ):
@@ -362,7 +367,7 @@ async def server_worker_start(
362367 # then we check to see if we are an experiment
363368 elif experiment_id is not None :
364369 try :
365- experiment = experiment_get (experiment_id )
370+ experiment = await experiment_get (experiment_id )
366371 experiment_config = (
367372 experiment ["config" ]
368373 if isinstance (experiment ["config" ], dict )
@@ -394,15 +399,15 @@ async def server_worker_start(
394399 model_architecture = model_architecture
395400
396401 plugin_name = inference_engine
397- plugin_location = lab_dirs .plugin_dir_by_name (plugin_name )
402+ plugin_location = await lab_dirs .plugin_dir_by_name (plugin_name )
398403
399404 model = model_name
400405 if model_filename is not None and model_filename != "" :
401406 model = model_filename
402407
403408 if adaptor != "" :
404409 # Resolve per-request workspace if multitenant
405- workspace_dir = get_workspace_dir ()
410+ workspace_dir = await get_workspace_dir ()
406411 adaptor = f"{ workspace_dir } /adaptors/{ secure_filename (model )} /{ adaptor } "
407412
408413 params = [
@@ -419,14 +424,14 @@ async def server_worker_start(
419424 json .dumps (inference_params ),
420425 ]
421426
422- job_id = job_create (type = "LOAD_MODEL" , status = "STARTED" , job_data = "{}" , experiment_id = experiment_id )
427+ job_id = await job_create (type = "LOAD_MODEL" , status = "STARTED" , job_data = "{}" , experiment_id = experiment_id )
423428
424429 print ("Loading plugin loader instead of default worker" )
425430
426431 from lab .dirs import get_global_log_path
427432
428- with storage .open (get_global_log_path (), "a" ) as global_log :
429- global_log .write (f"🏃 Loading Inference Server for { model_name } with { inference_params } \n " )
433+ async with await storage .open (await get_global_log_path (), "a" ) as global_log :
434+ await global_log .write (f"🏃 Loading Inference Server for { model_name } with { inference_params } \n " )
430435
431436 # Pass organization_id as environment variable to subprocess
432437 from transformerlab .shared .request_context import get_current_org_id
@@ -447,8 +452,8 @@ async def server_worker_start(
447452 if exitcode == 99 :
448453 from lab .dirs import get_global_log_path
449454
450- with storage .open (get_global_log_path (), "a" ) as global_log :
451- global_log .write (
455+ async with await storage .open (await get_global_log_path (), "a" ) as global_log :
456+ await global_log .write (
452457 "GPU (CUDA) Out of Memory: Please try a smaller model or a different inference engine. Restarting the server may free up resources.\n "
453458 )
454459 return {
@@ -458,20 +463,20 @@ async def server_worker_start(
458463 if exitcode is not None and exitcode != 0 :
459464 from lab .dirs import get_global_log_path
460465
461- with storage .open (get_global_log_path (), "a" ) as global_log :
462- global_log .write (f"Error loading model: { model_name } with exit code { exitcode } \n " )
463- job = job_get (job_id )
466+ async with await storage .open (await get_global_log_path (), "a" ) as global_log :
467+ await global_log .write (f"Error loading model: { model_name } with exit code { exitcode } \n " )
468+ job = await job_get (job_id )
464469 error_msg = None
465470 if job and job .get ("job_data" ):
466471 error_msg = job ["job_data" ].get ("error_msg" )
467472 if not error_msg :
468473 error_msg = f"Exit code { exitcode } "
469- job_update_status (job_id , "FAILED" , experiment_id = experiment_id , error_msg = error_msg )
474+ await job_update_status (job_id , "FAILED" , experiment_id = experiment_id , error_msg = error_msg )
470475 return {"status" : "error" , "message" : error_msg }
471476 from lab .dirs import get_global_log_path
472477
473- with storage .open (get_global_log_path (), "a" ) as global_log :
474- global_log .write (f"Model loaded successfully: { model_name } \n " )
478+ async with await storage .open (await get_global_log_path (), "a" ) as global_log :
479+ await global_log .write (f"Model loaded successfully: { model_name } \n " )
475480 return {"status" : "success" , "job_id" : job_id }
476481
477482
@@ -630,7 +635,9 @@ def run():
630635 )
631636
632637 if args .https :
633- cert_path , key_path = ensure_persistent_self_signed_cert ()
638+ import asyncio
639+
640+ cert_path , key_path = asyncio .run (ensure_persistent_self_signed_cert ())
634641 uvicorn .run (
635642 "api:app" , host = args .host , port = args .port , log_level = "warning" , ssl_certfile = cert_path , ssl_keyfile = key_path
636643 )
0 commit comments