import gradio as gr from requests import head from transformer_vectorizer import TransformerVectorizer from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np 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 import easyocr import PyPDF2 import os reader = easyocr.Reader(['en']) # This repository's directory REPO_DIR = Path(__file__).parent subprocess.Popen(["uvicorn", "server:app"], cwd=REPO_DIR) # Wait 5 sec for the server to start time.sleep(5) # Encrypted data limit for the browser to display # (encrypted data is too large to display in the browser) 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" #FHE_LEGAL_PATH="deployment/legal_rating" print("Loading the transformer model...") # Initialize the transformer vectorizer transformer_vectorizer = TransformerVectorizer() vectorizer = TfidfVectorizer() def process_input(input_type, user_input, uploaded_file): print('ooooocr') if input_type == "File Upload" and uploaded_file is not None: # 读取上传的文件 with open(uploaded_file.name, "rb") as f: image = f.read() results = reader.readtext(image) # 提取识别的文本 extracted_text = ' '.join([text[1] for text in results]) print("提取的文本:") print(extracted_text) return extracted_text elif input_type == "Text Input": return user_input ''' def process_input(input_type, user_input, uploaded_file): if input_type == "File Upload" and uploaded_file is not None: file_ext = os.path.splitext(uploaded_file.name)[1].lower() extracted_text = "" if file_ext in ['.jpg', '.jpeg', '.png']: # 处理图片文件 results = reader.readtext(uploaded_file.name) extracted_text = ' '.join([text[1] for text in results]) print("从图片提取的文本:") print(extracted_text) elif file_ext == '.txt': # 处理TXT文件 with open(uploaded_file.name, 'r', encoding='utf-8') as f: extracted_text = f.read() print("从TXT文件提取的文本:") print(extracted_text) elif file_ext == '.pdf': # 处理PDF文件 with open(uploaded_file.name, 'rb') as f: reader_pdf = PyPDF2.PdfReader(f) for page_num in range(len(reader_pdf.pages)): page = reader_pdf.pages[page_num] extracted_text += page.extract_text() + "\n" print("从PDF文件提取的文本:") print(extracted_text) else: return "不支持的文件类型。请上传 .jpg, .jpeg, .png, .txt 或 .pdf 文件。" return extracted_text elif input_type == "Text Input": return user_input else: return "无效的输入类型或未上传文件。" ''' def toggle_visibility(input_type): user_input_visible = input_type == "Text Input" file_upload_visible = input_type == "File Upload" return gr.update(visible=user_input_visible), gr.update(visible=file_upload_visible) def clean_tmp_directory(): # Allow 20 user keys to be stored. # Once that limitation is reached, deleted the oldest. 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() # Delete all files related to user_id for file in list_files_tmp: for user_id in user_ids: if file.name.endswith(f"{user_id}.npy"): file.unlink() mes=[] def keygen(selected_tasks): # Clean tmp directory if needed clean_tmp_directory() print("Initializing FHEModelClient...") if not selected_tasks: return "choose a task first" # 修改提示信息为英文 user_id = numpy.random.randint(0, 2**32) if "legal_rating" in selected_tasks: model_names.append('legal_rating') # Let's create a user_id fhe_api= FHEModelClient(FHE_LEGAL_PATH, f".fhe_keys/{user_id}") if "financial_rating" in selected_tasks: model_names.append('financial_rating') fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") # Let's create a user_id fhe_api.load() # Generate a fresh key fhe_api.generate_private_and_evaluation_keys(force=True) evaluation_key = fhe_api.get_serialized_evaluation_keys() # Save evaluation_key in a file, since too large to pass through regular Gradio # buttons, https://github.com/gradio-app/gradio/issues/1877 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.") if "legal_rating" in model_names: fhe_api = FHEModelClient(FHE_LEGAL_PATH, f".fhe_keys/{user_id}") encodings =vectorizer.fit_transform([text]).toarray() if encodings.shape[1] < 1736: # 在后面填充零 padding = np.zeros((1, 1736 - encodings.shape[1])) encodings = np.hstack((encodings, padding)) elif encodings.shape[1] > 1736: # 截取前1736列 encodings = encodings[:, :1736] else: fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") encodings = transformer_vectorizer.transform([text]) fhe_api.load() quantized_encodings = fhe_api.model.quantize_input(encodings).astype(numpy.uint8) encrypted_quantized_encoding = fhe_api.quantize_encrypt_serialize(encodings) # Save encrypted_quantized_encoding in a file, since too large to pass through regular Gradio # buttons, https://github.com/gradio-app/gradio/issues/1877 numpy.save(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy", encrypted_quantized_encoding) # Compute size 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.") # Read encrypted_quantized_encoding from the file encrypted_quantized_encoding = numpy.load(encoded_data_path) # Read evaluation_key from the file evaluation_key = numpy.load(f"tmp/tmp_evaluation_key_{user_id}.npy") # Use base64 to encode the encodings and evaluation key 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"} if "legal_rating" in model_names: response = requests.post( "http://localhost:8000/predict_legal", data=json.dumps(query), headers=headers ) else: response = requests.post( "http://localhost:8000/predict_sentiment", data=json.dumps(query), headers=headers ) encrypted_prediction = base64.b64decode(response.json()["encrypted_prediction"]) # Save encrypted_prediction in a file, since too large to pass through regular Gradio # buttons, https://github.com/gradio-app/gradio/issues/1877 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.") # Read encrypted_prediction from the file encrypted_prediction = numpy.load(encoded_data_path).tobytes() if "legal_rating" in model_names: fhe_api = FHEModelClient(FHE_LEGAL_PATH, f".fhe_keys/{user_id}") fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") fhe_api.load() # We need to retrieve the private key that matches the client specs (see issue #18) 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( """
""" ) gr.Markdown( """
""" ) 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( """