Thomas Chardonnens commited on
Commit ·
e62353e
1
Parent(s): 4c7366a
log fastapi errors
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201 unmodified lineimport timefrom typing import Listfrom fastapi import FastAPI, File, Form, UploadFilefrom fastapi.responses import JSONResponse, Responseimport asynciofrom common import SERVER_TMP_PATH, SEIZURE_DETECTION_MODEL_PATHfrom client_server_interface import FHEServer# Load the server object for seizure detectionFHE_SERVER = FHEServer(model_path=SEIZURE_DETECTION_MODEL_PATH)def get_server_file_path(name, user_id):"""Get the correct temporary file path for the server.Args:name (str): The desired file name.user_id (int): The current user's ID.Returns:pathlib.Path: The file path."""return SERVER_TMP_PATH / f"{name}_seizure_detection_{user_id}"# Initialize an instance of FastAPIapp = FastAPI()# Define the default route@app.get("/")def root():return {"message": "Welcome to Your Seizure Detection FHE Server!"}@app.post("/send_input")def send_input(user_id: str = Form(),files: List[UploadFile] = File(),):"""Send the inputs to the server."""# Retrieve the encrypted input image and the evaluation key pathsencrypted_image_path = get_server_file_path("encrypted_image", user_id)evaluation_key_path = get_server_file_path("evaluation_key", user_id)# Write the files using the above pathswith encrypted_image_path.open("wb") as encrypted_image, evaluation_key_path.open("wb") as evaluation_key:encrypted_image.write(files[0].file.read())evaluation_key.write(files[1].file.read())@app.post("/run_fhe")async def run_fhe(user_id: str = Form(),):"""Execute seizure detection on the encrypted input image using FHE."""# Retrieve the encrypted input image and the evaluation key pathsencrypted_image_path = get_server_file_path("encrypted_image", user_id)evaluation_key_path = get_server_file_path("evaluation_key", user_id)# Read the files using the above pathswith encrypted_image_path.open("rb") as encrypted_image_file, evaluation_key_path.open("rb") as evaluation_key_file:encrypted_image = encrypted_image_file.read()evaluation_key = evaluation_key_file.read()# Run the FHE execution in a background taskasync def run_fhe_task():start = time.time()encrypted_output = FHE_SERVER.run(encrypted_image, evaluation_key)fhe_execution_time = round(time.time() - start, 2)# Retrieve the encrypted output pathencrypted_output_path = get_server_file_path("encrypted_output", user_id)# Write the file using the above pathwith encrypted_output_path.open("wb") as encrypted_output_file:encrypted_output_file.write(encrypted_output)return fhe_execution_time# Start the background tasktask = asyncio.create_task(run_fhe_task())# Return a response immediatelyreturn JSONResponse(content={"message": "FHE execution started", "task_id": str(id(task))})@app.get("/fhe_status/{task_id}")async def fhe_status(task_id: str):"""Check the status of an FHE execution task and return the execution time if completed."""for task in asyncio.all_tasks():if str(id(task)) == task_id:if task.done():try:execution_time = task.result()return JSONResponse(content={"status": "completed", "execution_time": execution_time})except Exception as e:return JSONResponse(content={"status": "error", "message": str(e)})else:return JSONResponse(content={"status": "running"})return JSONResponse(content={"status": "not_found"})@app.post("/get_output")def get_output(user_id: str = Form(),):"""Retrieve the encrypted output."""# Retrieve the encrypted output pathencrypted_output_path = get_server_file_path("encrypted_output", user_id)# Read the file using the above pathwith encrypted_output_path.open("rb") as encrypted_output_file:encrypted_output = encrypted_output_file.read()return Response(encrypted_output)1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141 unmodified lineimport timefrom typing import Listfrom fastapi import FastAPI, File, Form, UploadFile, HTTPExceptionfrom fastapi.responses import JSONResponse, Responseimport asynciofrom common import SERVER_TMP_PATH, SEIZURE_DETECTION_MODEL_PATHfrom client_server_interface import FHEServerimport logging# Set up logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Load the server object for seizure detectionFHE_SERVER = FHEServer(model_path=SEIZURE_DETECTION_MODEL_PATH)def get_server_file_path(name, user_id):"""Get the correct temporary file path for the server."""return SERVER_TMP_PATH / f"{name}_seizure_detection_{user_id}"# Initialize an instance of FastAPIapp = FastAPI()@app.get("/")def root():return {"message": "Welcome to Your Seizure Detection FHE Server!"}@app.post("/send_input")async def send_input(user_id: str = Form(),files: List[UploadFile] = File(),):"""Send the inputs to the server."""try:encrypted_image_path = get_server_file_path("encrypted_image", user_id)evaluation_key_path = get_server_file_path("evaluation_key", user_id)async with encrypted_image_path.open("wb") as encrypted_image, evaluation_key_path.open("wb") as evaluation_key:encrypted_image.write(await files[0].read())evaluation_key.write(await files[1].read())return JSONResponse(content={"message": "Input received successfully"}, status_code=200)except Exception as e:logger.error(f"Error in send_input: {str(e)}")raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")@app.post("/run_fhe")async def run_fhe(user_id: str = Form(),):"""Execute seizure detection on the encrypted input image using FHE."""try:encrypted_image_path = get_server_file_path("encrypted_image", user_id)evaluation_key_path = get_server_file_path("evaluation_key", user_id)async with encrypted_image_path.open("rb") as encrypted_image_file, evaluation_key_path.open("rb") as evaluation_key_file:encrypted_image = await encrypted_image_file.read()evaluation_key = await evaluation_key_file.read()async def run_fhe_task():start = time.time()encrypted_output = FHE_SERVER.run(encrypted_image, evaluation_key)fhe_execution_time = round(time.time() - start, 2)encrypted_output_path = get_server_file_path("encrypted_output", user_id)async with encrypted_output_path.open("wb") as encrypted_output_file:await encrypted_output_file.write(encrypted_output)return fhe_execution_timetask = asyncio.create_task(run_fhe_task())return JSONResponse(content={"message": "FHE execution started", "task_id": str(id(task))})except Exception as e:logger.error(f"Error in run_fhe: {str(e)}")raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")@app.get("/fhe_status/{task_id}")async def fhe_status(task_id: str):"""Check the status of an FHE execution task."""try:for task in asyncio.all_tasks():if str(id(task)) == task_id:if task.done():try:execution_time = await taskreturn JSONResponse(content={"status": "completed", "execution_time": execution_time})except Exception as e:logger.error(f"Error in task execution: {str(e)}")return JSONResponse(content={"status": "error", "message": str(e)})else:return JSONResponse(content={"status": "running"})return JSONResponse(content={"status": "not_found"})except Exception as e:logger.error(f"Error in fhe_status: {str(e)}")raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")@app.post("/get_output")async def get_output(user_id: str = Form(),):"""Retrieve the encrypted output."""try:encrypted_output_path = get_server_file_path("encrypted_output", user_id)async with encrypted_output_path.open("rb") as encrypted_output_file:encrypted_output = await encrypted_output_file.read()return Response(content=encrypted_output, media_type="application/octet-stream")except Exception as e:logger.error(f"Error in get_output: {str(e)}")raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
server.py+67-73