Delwin Mathew commited on
Commit
2382f1d
·
1 Parent(s): 1437552

use life cycle

Browse files
Files changed (1) hide show
  1. app.py +12 -5
app.py CHANGED
@@ -1,32 +1,39 @@
1
  from fastapi import FastAPI
2
  from pydantic import BaseModel
3
  import spacy
 
4
 
5
  app = FastAPI()
6
 
7
  # Global variable to store the model
8
  nlp = None
9
 
10
- @app.on_event("startup")
 
 
 
 
 
 
 
11
  async def load_model():
12
  """
13
  Event to load the NLP model into memory on application startup.
14
  """
15
  global nlp
16
- nlp = spacy.load("en_core_web_sm") # Replace with your model and loading logic
17
  print("NLP model loaded successfully.")
18
 
19
- @app.on_event("shutdown")
20
  async def cleanup():
21
  """
22
  Event to clean up resources on application shutdown (if needed).
23
  """
24
  global nlp
25
- nlp = None # Free memory (if necessary)
26
  print("NLP model unloaded.")
27
 
28
 
29
-
30
  class NERRequest(BaseModel):
31
  chunks: list[str]
32
 
 
1
  from fastapi import FastAPI
2
  from pydantic import BaseModel
3
  import spacy
4
+ from contextlib import asynccontextmanager
5
 
6
  app = FastAPI()
7
 
8
  # Global variable to store the model
9
  nlp = None
10
 
11
+
12
+ @asynccontextmanager
13
+ async def lifespan(app: FastAPI):
14
+ await load_model()
15
+ yield
16
+ await cleanup()
17
+
18
+
19
  async def load_model():
20
  """
21
  Event to load the NLP model into memory on application startup.
22
  """
23
  global nlp
24
+ nlp = spacy.load("en_core_web_sm")
25
  print("NLP model loaded successfully.")
26
 
27
+
28
  async def cleanup():
29
  """
30
  Event to clean up resources on application shutdown (if needed).
31
  """
32
  global nlp
33
+ nlp = None
34
  print("NLP model unloaded.")
35
 
36
 
 
37
  class NERRequest(BaseModel):
38
  chunks: list[str]
39