Gaykar commited on
Commit
f912120
·
verified ·
1 Parent(s): bf59648

Update main.py

Browse files

main code changed

Files changed (1) hide show
  1. main.py +21 -8
main.py CHANGED
@@ -1,19 +1,32 @@
1
- import asyncio # Built-in, no pip install needed!
 
2
  from fastapi import FastAPI, UploadFile, File
3
  from cnn_pipeline.pipeline import classify_tumor
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- app = FastAPI(title="Brain Tumor CNN Service")
6
 
7
  @app.post("/classify")
8
  async def classify(file: UploadFile = File(...)):
9
- # 1. This reads the file asynchronously on the Main Event Loop
 
10
  image_bytes = await file.read()
11
 
12
- # 2. Get the running manager (Event Loop)
13
  loop = asyncio.get_running_loop()
14
 
15
- # 3. Offload the heavy CNN model to the background thread pool
16
- # None tells Python to use FastAPI's default pool of worker threads
17
- result = await loop.run_in_executor(None, classify_tumor, image_bytes)
18
 
19
- return result
 
 
 
 
1
+ import asyncio
2
+ from concurrent.futures import ThreadPoolExecutor
3
  from fastapi import FastAPI, UploadFile, File
4
  from cnn_pipeline.pipeline import classify_tumor
5
+ from contextlib import asynccontextmanager
6
+
7
+
8
+ async def lifespan(app: FastAPI):
9
+ yield # The app is running at this point
10
+ executor.shutdown()
11
+
12
+
13
+ app = FastAPI(title="Brain Tumor CNN Service",lifespan=lifespan)
14
+
15
+ # its okay to use thead pool (prototype level) as pytorch surpasses GIL
16
+ executor=ThreadPoolExecutor(max_workers=2)
17
 
 
18
 
19
  @app.post("/classify")
20
  async def classify(file: UploadFile = File(...)):
21
+
22
+ # read the fiel content
23
  image_bytes = await file.read()
24
 
25
+ # get the event Loop
26
  loop = asyncio.get_running_loop()
27
 
 
 
 
28
 
29
+ result = await loop.run_in_executor(executor, classify_tumor, image_bytes)
30
+
31
+ return result
32
+