batuergun commited on
Commit
9a4ad03
1 Parent(s): c1f9095

api update

Browse files
Files changed (2) hide show
  1. app.py +5 -5
  2. server.py +89 -81
app.py CHANGED
@@ -8,6 +8,11 @@ import gradio as gr
8
  import numpy
9
  import requests
10
  from itertools import chain
 
 
 
 
 
11
 
12
  from common import (
13
  CLIENT_TMP_PATH,
@@ -19,11 +24,6 @@ from common import (
19
  SERVER_URL,
20
  )
21
 
22
- import requests
23
- from requests.adapters import HTTPAdapter
24
- from requests.packages.urllib3.util.retry import Retry
25
- import logging
26
-
27
  # Set up logging
28
  logging.basicConfig(level=logging.DEBUG)
29
  logger = logging.getLogger(__name__)
 
8
  import numpy
9
  import requests
10
  from itertools import chain
11
+ from client_server_interface import FHEClient
12
+ import requests
13
+ from requests.adapters import HTTPAdapter
14
+ from requests.packages.urllib3.util.retry import Retry
15
+ import logging
16
 
17
  from common import (
18
  CLIENT_TMP_PATH,
 
24
  SERVER_URL,
25
  )
26
 
 
 
 
 
 
27
  # Set up logging
28
  logging.basicConfig(level=logging.DEBUG)
29
  logger = logging.getLogger(__name__)
server.py CHANGED
@@ -1,101 +1,109 @@
1
  """Server that will listen for GET and POST requests from the client."""
2
 
3
  import time
 
 
4
  from typing import List
5
- from fastapi import FastAPI, File, Form, UploadFile
 
6
  from fastapi.responses import JSONResponse, Response
 
7
 
8
  from concrete.ml.deployment import FHEModelServer
9
 
10
- from common import (
11
- DEPLOYMENT_DIR,
12
- SERVER_TMP_PATH
13
- )
14
-
15
- # Load the server object for seizure detection
16
- FHE_SERVER = FHEModelServer(DEPLOYMENT_DIR)
17
-
18
- def get_server_file_path(name, user_id):
19
- """Get the correct temporary file path for the server.
20
 
21
- Args:
22
- name (str): The desired file name.
23
- user_id (int): The current user's ID.
24
-
25
- Returns:
26
- pathlib.Path: The file path.
27
- """
28
- return SERVER_TMP_PATH / f"{name}_seizure_detection_{user_id}"
29
-
30
-
31
- # Initialize an instance of FastAPI
32
  app = FastAPI()
33
 
34
- # Define the default route
35
- @app.get("/")
36
- def root():
37
- return {"message": "Welcome to Your Seizure Detection FHE Server!"}
 
 
 
 
 
 
 
 
38
 
 
 
 
39
 
40
  @app.post("/send_input")
41
- def send_input(
42
- user_id: str = Form(),
43
- files: List[UploadFile] = File(),
44
- ):
45
- """Send the inputs to the server."""
46
- # Retrieve the encrypted input image and the evaluation key paths
47
- encrypted_image_path = get_server_file_path("encrypted_image", user_id)
48
- evaluation_key_path = get_server_file_path("evaluation_key", user_id)
49
-
50
- # Write the files using the above paths
51
- with encrypted_image_path.open("wb") as encrypted_image, evaluation_key_path.open(
52
- "wb"
53
- ) as evaluation_key:
54
- encrypted_image.write(files[0].file.read())
55
- evaluation_key.write(files[1].file.read())
56
-
57
 
58
  @app.post("/run_fhe")
59
- def run_fhe(
60
- user_id: str = Form(),
61
- ):
62
  """Execute seizure detection on the encrypted input image using FHE."""
63
- # Retrieve the encrypted input image and the evaluation key paths
64
- encrypted_image_path = get_server_file_path("encrypted_image", user_id)
65
- evaluation_key_path = get_server_file_path("evaluation_key", user_id)
66
-
67
- # Read the files using the above paths
68
- with encrypted_image_path.open("rb") as encrypted_image_file, evaluation_key_path.open(
69
- "rb"
70
- ) as evaluation_key_file:
71
- encrypted_image = encrypted_image_file.read()
72
- evaluation_key = evaluation_key_file.read()
73
-
74
- # Run the FHE execution
75
- start = time.time()
76
- encrypted_output = FHE_SERVER.run(encrypted_image, evaluation_key)
77
- fhe_execution_time = round(time.time() - start, 2)
78
-
79
- # Retrieve the encrypted output path
80
- encrypted_output_path = get_server_file_path("encrypted_output", user_id)
81
-
82
- # Write the file using the above path
83
- with encrypted_output_path.open("wb") as encrypted_output_file:
84
- encrypted_output_file.write(encrypted_output)
85
-
86
- return JSONResponse(content=fhe_execution_time)
87
-
 
 
 
 
 
 
 
88
 
89
  @app.post("/get_output")
90
- def get_output(
91
- user_id: str = Form(),
92
- ):
93
  """Retrieve the encrypted output."""
94
- # Retrieve the encrypted output path
95
- encrypted_output_path = get_server_file_path("encrypted_output", user_id)
96
-
97
- # Read the file using the above path
98
- with encrypted_output_path.open("rb") as encrypted_output_file:
99
- encrypted_output = encrypted_output_file.read()
100
-
101
- return Response(encrypted_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """Server that will listen for GET and POST requests from the client."""
2
 
3
  import time
4
+ import logging
5
+ from pathlib import Path
6
  from typing import List
7
+
8
+ from fastapi import FastAPI, File, Form, UploadFile, HTTPException
9
  from fastapi.responses import JSONResponse, Response
10
+ from fastapi.middleware.cors import CORSMiddleware
11
 
12
  from concrete.ml.deployment import FHEModelServer
13
 
14
+ # Set up logging
15
+ logging.basicConfig(level=logging.INFO)
16
+ logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
17
 
 
 
 
 
 
 
 
 
 
 
 
18
  app = FastAPI()
19
 
20
+ # Add CORS middleware
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"], # Allows all origins
24
+ allow_credentials=True,
25
+ allow_methods=["*"], # Allows all methods
26
+ allow_headers=["*"], # Allows all headers
27
+ )
28
+
29
+ # Initialize the FHE server
30
+ DEPLOYMENT_DIR = Path(__file__).parent / "deployment_files"
31
+ FHE_SERVER = FHEModelServer(DEPLOYMENT_DIR)
32
 
33
+ def get_server_file_path(file_type: str, user_id: str) -> Path:
34
+ """Get the path to a file on the server."""
35
+ return Path(__file__).parent / "server_tmp" / f"{file_type}_{user_id}"
36
 
37
  @app.post("/send_input")
38
+ async def send_input(user_id: str = Form(), files: List[UploadFile] = File(...)):
39
+ """Receive the encrypted input image and the evaluation key from the client."""
40
+ try:
41
+ for file in files:
42
+ file_path = get_server_file_path(file.filename.split("_")[0], user_id)
43
+ with file_path.open("wb") as buffer:
44
+ content = await file.read()
45
+ buffer.write(content)
46
+ return JSONResponse(content={"message": "Files received successfully"})
47
+ except Exception as e:
48
+ logger.error(f"Error in send_input: {str(e)}")
49
+ raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
 
 
 
 
50
 
51
  @app.post("/run_fhe")
52
+ def run_fhe(user_id: str = Form()):
 
 
53
  """Execute seizure detection on the encrypted input image using FHE."""
54
+ logger.info(f"Starting FHE execution for user {user_id}")
55
+ try:
56
+ # Retrieve the encrypted input image and the evaluation key paths
57
+ encrypted_image_path = get_server_file_path("encrypted_image", user_id)
58
+ evaluation_key_path = get_server_file_path("evaluation_key", user_id)
59
+
60
+ # Check if files exist
61
+ if not encrypted_image_path.exists() or not evaluation_key_path.exists():
62
+ raise FileNotFoundError("Required files not found")
63
+
64
+ # Read the files using the above paths
65
+ with encrypted_image_path.open("rb") as encrypted_image_file, evaluation_key_path.open("rb") as evaluation_key_file:
66
+ encrypted_image = encrypted_image_file.read()
67
+ evaluation_key = evaluation_key_file.read()
68
+
69
+ # Run the FHE execution
70
+ start = time.time()
71
+ encrypted_output = FHE_SERVER.run(encrypted_image, evaluation_key)
72
+ fhe_execution_time = round(time.time() - start, 2)
73
+
74
+ # Retrieve the encrypted output path
75
+ encrypted_output_path = get_server_file_path("encrypted_output", user_id)
76
+
77
+ # Write the file using the above path
78
+ with encrypted_output_path.open("wb") as encrypted_output_file:
79
+ encrypted_output_file.write(encrypted_output)
80
+
81
+ logger.info(f"FHE execution completed for user {user_id} in {fhe_execution_time} seconds")
82
+ return JSONResponse(content=fhe_execution_time)
83
+ except Exception as e:
84
+ logger.error(f"Error in run_fhe for user {user_id}: {str(e)}")
85
+ raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
86
 
87
  @app.post("/get_output")
88
+ def get_output(user_id: str = Form()):
 
 
89
  """Retrieve the encrypted output."""
90
+ try:
91
+ # Retrieve the encrypted output path
92
+ encrypted_output_path = get_server_file_path("encrypted_output", user_id)
93
+
94
+ # Check if file exists
95
+ if not encrypted_output_path.exists():
96
+ raise FileNotFoundError("Encrypted output file not found")
97
+
98
+ # Read the file using the above path
99
+ with encrypted_output_path.open("rb") as encrypted_output_file:
100
+ encrypted_output = encrypted_output_file.read()
101
+
102
+ return Response(encrypted_output)
103
+ except Exception as e:
104
+ logger.error(f"Error in get_output for user {user_id}: {str(e)}")
105
+ raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
106
+
107
+ if __name__ == "__main__":
108
+ import uvicorn
109
+ uvicorn.run(app, host="0.0.0.0", port=8000)