|
import gradio as gr |
|
from requests import head |
|
from transformer_vectorizer import TransformerVectorizer |
|
from sklearn.feature_extraction.text import TfidfVectorizer |
|
|
|
from concrete.ml.deployment import FHEModelClient |
|
import numpy |
|
import os |
|
from pathlib import Path |
|
import requests |
|
import json |
|
import base64 |
|
import subprocess |
|
import shutil |
|
import time |
|
|
|
|
|
REPO_DIR = Path(__file__).parent |
|
|
|
subprocess.Popen(["uvicorn", "server:app"], cwd=REPO_DIR) |
|
|
|
|
|
time.sleep(5) |
|
|
|
|
|
|
|
ENCRYPTED_DATA_BROWSER_LIMIT = 500 |
|
N_USER_KEY_STORED = 20 |
|
model_names=['financial_rating','legal_rating'] |
|
FHE_MODEL_PATH = "deployment/financial_rating" |
|
FHE_LEGAL_PATH = "deployment/legal_rating" |
|
|
|
|
|
print("Loading the transformer model...") |
|
|
|
|
|
transformer_vectorizer = TransformerVectorizer() |
|
vectorizer = TfidfVectorizer() |
|
|
|
def clean_tmp_directory(): |
|
|
|
|
|
path_sub_directories = sorted([f for f in Path(".fhe_keys/").iterdir() if f.is_dir()], key=os.path.getmtime) |
|
|
|
user_ids = [] |
|
if len(path_sub_directories) > N_USER_KEY_STORED: |
|
n_files_to_delete = len(path_sub_directories) - N_USER_KEY_STORED |
|
for p in path_sub_directories[:n_files_to_delete]: |
|
user_ids.append(p.name) |
|
shutil.rmtree(p) |
|
|
|
list_files_tmp = Path("tmp/").iterdir() |
|
|
|
for file in list_files_tmp: |
|
for user_id in user_ids: |
|
if file.name.endswith(f"{user_id}.npy"): |
|
file.unlink() |
|
model_nams=[] |
|
|
|
def keygen(selected_tasks): |
|
|
|
clean_tmp_directory() |
|
|
|
print("Initializing FHEModelClient...") |
|
|
|
|
|
if not selected_tasks: |
|
return "choose task first" |
|
|
|
if "legal_rating" in selected_tasks: |
|
model_names.append('legal_rating') |
|
if "financial_rating" in selected_tasks: |
|
model_names.append('financial_rating') |
|
|
|
|
|
|
|
|
|
user_id = numpy.random.randint(0, 2**32) |
|
fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") |
|
fhe_api.load() |
|
|
|
|
|
|
|
fhe_api.generate_private_and_evaluation_keys(force=True) |
|
evaluation_key = fhe_api.get_serialized_evaluation_keys() |
|
|
|
|
|
|
|
numpy.save(f"tmp/tmp_evaluation_key_{user_id}.npy", evaluation_key) |
|
|
|
return [list(evaluation_key)[:ENCRYPTED_DATA_BROWSER_LIMIT], user_id] |
|
def encode_quantize_encrypt(text, user_id): |
|
if not user_id: |
|
raise gr.Error("You need to generate FHE keys first.") |
|
|
|
fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") |
|
fhe_api.load() |
|
encodings = transformer_vectorizer.transform([text]) |
|
print(encodings.shape) |
|
quantized_encodings = fhe_api.model.quantize_input(encodings).astype(numpy.uint8) |
|
encrypted_quantized_encoding = fhe_api.quantize_encrypt_serialize(encodings) |
|
|
|
|
|
|
|
numpy.save(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy", encrypted_quantized_encoding) |
|
|
|
|
|
encrypted_quantized_encoding_shorten = list(encrypted_quantized_encoding)[:ENCRYPTED_DATA_BROWSER_LIMIT] |
|
encrypted_quantized_encoding_shorten_hex = ''.join(f'{i:02x}' for i in encrypted_quantized_encoding_shorten) |
|
return ( |
|
encodings[0], |
|
quantized_encodings[0], |
|
encrypted_quantized_encoding_shorten_hex, |
|
) |
|
|
|
|
|
|
|
def run_fhe(user_id): |
|
encoded_data_path = Path(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy") |
|
if not user_id: |
|
raise gr.Error("You need to generate FHE keys first.") |
|
if not encoded_data_path.is_file(): |
|
raise gr.Error("No encrypted data was found. Encrypt the data before trying to predict.") |
|
|
|
|
|
encrypted_quantized_encoding = numpy.load(encoded_data_path) |
|
|
|
|
|
evaluation_key = numpy.load(f"tmp/tmp_evaluation_key_{user_id}.npy") |
|
|
|
|
|
encrypted_quantized_encoding = base64.b64encode(encrypted_quantized_encoding).decode() |
|
encoded_evaluation_key = base64.b64encode(evaluation_key).decode() |
|
|
|
query = {} |
|
query["evaluation_key"] = encoded_evaluation_key |
|
query["encrypted_encoding"] = encrypted_quantized_encoding |
|
headers = {"Content-type": "application/json"} |
|
response = requests.post( |
|
"http://localhost:8000/predict_sentiment", data=json.dumps(query), headers=headers |
|
) |
|
encrypted_prediction = base64.b64decode(response.json()["encrypted_prediction"]) |
|
|
|
|
|
|
|
numpy.save(f"tmp/tmp_encrypted_prediction_{user_id}.npy", encrypted_prediction) |
|
encrypted_prediction_shorten = list(encrypted_prediction)[:ENCRYPTED_DATA_BROWSER_LIMIT] |
|
encrypted_prediction_shorten_hex = ''.join(f'{i:02x}' for i in encrypted_prediction_shorten) |
|
return encrypted_prediction_shorten_hex |
|
|
|
|
|
def decrypt_prediction(user_id): |
|
encoded_data_path = Path(f"tmp/tmp_encrypted_prediction_{user_id}.npy") |
|
if not user_id: |
|
raise gr.Error("You need to generate FHE keys first.") |
|
if not encoded_data_path.is_file(): |
|
raise gr.Error("No encrypted prediction was found. Run the prediction over the encrypted data first.") |
|
|
|
|
|
encrypted_prediction = numpy.load(encoded_data_path).tobytes() |
|
|
|
fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") |
|
fhe_api.load() |
|
|
|
|
|
fhe_api.generate_private_and_evaluation_keys(force=False) |
|
|
|
predictions = fhe_api.deserialize_decrypt_dequantize(encrypted_prediction) |
|
print(predictions) |
|
return { |
|
"low_relative": predictions[0][0], |
|
"medium_relative": predictions[0][1], |
|
"high_relative": predictions[0][2], |
|
} |
|
|
|
|
|
demo = gr.Blocks() |
|
|
|
|
|
print("Starting the demo...") |
|
with demo: |
|
|
|
gr.Markdown( |
|
""" |
|
|
|
<h2 align="center">Contract Analysis</h2> |
|
|
|
""" |
|
) |
|
|
|
|
|
gr.Markdown( |
|
""" |
|
<p align="center"> |
|
</p> |
|
<p align="center"> |
|
</p> |
|
""" |
|
) |
|
|
|
gr.Markdown("## Notes") |
|
gr.Markdown( |
|
""" |
|
- The private key is used to encrypt and decrypt the data and shall never be shared. |
|
- The evaluation key is a public key that the server needs to process encrypted data. |
|
""" |
|
) |
|
gr.Markdown("# Step 0: Select Tasks") |
|
task_checkbox = gr.CheckboxGroup( |
|
choices=["legal_rating", "financial_rating"], |
|
label="select_tasks" |
|
) |
|
|
|
gr.Markdown("# Step 1: Generate the keys") |
|
|
|
b_gen_key_and_install = gr.Button("Generate all the keys and send public part to server") |
|
|
|
evaluation_key = gr.Textbox( |
|
label="Evaluation key (truncated):", |
|
max_lines=4, |
|
interactive=False, |
|
) |
|
|
|
user_id = gr.Textbox( |
|
label="", |
|
max_lines=4, |
|
interactive=False, |
|
visible=False |
|
) |
|
|
|
gr.Markdown("# Step 2: Provide a contract or clause") |
|
gr.Markdown("## Client side") |
|
gr.Markdown( |
|
"Enter a contract or clause you want to analysis)." |
|
) |
|
text = gr.Textbox(label="Enter some words:", value="The Employee is entitled to two weeks of paid vacation annually, to be scheduled at the mutual convenience of the Employee and Employer.") |
|
|
|
gr.Markdown("# Step 3: Encode the message with the private key") |
|
b_encode_quantize_text = gr.Button( |
|
"Encode, quantize and encrypt the text with vectorizer, and send to server" |
|
) |
|
|
|
with gr.Row(): |
|
encoding = gr.Textbox( |
|
label="Representation:", |
|
max_lines=4, |
|
interactive=False, |
|
) |
|
quantized_encoding = gr.Textbox( |
|
label="Quantized representation:", max_lines=4, interactive=False |
|
) |
|
encrypted_quantized_encoding = gr.Textbox( |
|
label="Encrypted quantized representation (truncated):", |
|
max_lines=4, |
|
interactive=False, |
|
) |
|
|
|
gr.Markdown("# Step 4: Run the FHE evaluation") |
|
gr.Markdown("## Server side") |
|
gr.Markdown( |
|
"The encrypted value is received by the server. Thanks to the evaluation key and to FHE, the server can compute the (encrypted) prediction directly over encrypted values. Once the computation is finished, the server returns the encrypted prediction to the client." |
|
) |
|
|
|
b_run_fhe = gr.Button("Run FHE execution there") |
|
encrypted_prediction = gr.Textbox( |
|
label="Encrypted prediction (truncated):", |
|
max_lines=4, |
|
interactive=False, |
|
) |
|
|
|
gr.Markdown("# Step 5: Decrypt the class") |
|
gr.Markdown("## Client side") |
|
gr.Markdown( |
|
"The encrypted sentiment is sent back to client, who can finally decrypt it with its private key. Only the client is aware of the original tweet and the prediction." |
|
) |
|
b_decrypt_prediction = gr.Button("Decrypt prediction") |
|
|
|
labels_sentiment = gr.Label(label="level:") |
|
|
|
|
|
b_gen_key_and_install.click(keygen, inputs=[task_checkbox], outputs=[evaluation_key, user_id]) |
|
|
|
|
|
b_encode_quantize_text.click( |
|
encode_quantize_encrypt, |
|
inputs=[text, user_id], |
|
outputs=[ |
|
encoding, |
|
quantized_encoding, |
|
encrypted_quantized_encoding, |
|
], |
|
) |
|
|
|
|
|
b_run_fhe.click(run_fhe, inputs=[user_id], outputs=[encrypted_prediction]) |
|
|
|
|
|
b_decrypt_prediction.click(decrypt_prediction, inputs=[user_id], outputs=[labels_sentiment]) |
|
gr.Markdown( |
|
"The app was built with [Concrete-ML](https://github.com/zama-ai/concrete-ml), a Privacy-Preserving Machine Learning (PPML) open-source set of tools by [Zama](https://zama.ai/). Try it yourself and don't forget to star on Github ⭐." |
|
) |
|
demo.launch(share=False) |