Update app.py
Browse files
app.py
CHANGED
@@ -1,220 +1,182 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import io
|
5 |
import base64
|
6 |
-
import
|
7 |
import logging
|
8 |
-
import tempfile
|
9 |
-
from PIL import Image, ImageDraw, ImageFont
|
10 |
-
import numpy as np
|
11 |
-
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
12 |
-
from cryptography.hazmat.primitives import hashes
|
13 |
-
from cryptography.hazmat.primitives import serialization
|
14 |
-
from cryptography.hazmat.primitives.asymmetric import padding
|
15 |
-
from cryptography.exceptions import InvalidTag
|
16 |
-
|
17 |
-
|
18 |
-
#import subprocess
|
19 |
-
#result = subprocess.run(["pip", "freeze"], capture_output=True, text=True)
|
20 |
-
#print(result.stdout)
|
21 |
-
|
22 |
|
23 |
# --- Configure Logging ---
|
24 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
25 |
logger = logging.getLogger(__name__)
|
26 |
|
27 |
# ==============================================================================
|
28 |
-
#
|
29 |
# ==============================================================================
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
except FileNotFoundError:
|
37 |
-
PUBLIC_KEY_PEM_STRING = "Error: keylock_pub.pem file not found. 'Creator' tab will not work."
|
38 |
|
39 |
# ==============================================================================
|
40 |
-
#
|
41 |
# ==============================================================================
|
42 |
-
def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
|
43 |
-
if not secret_data_str.strip(): raise ValueError("Secret data cannot be empty.")
|
44 |
-
|
45 |
-
# 1. Parse & Encrypt Data
|
46 |
-
data_dict = {}
|
47 |
-
for line in secret_data_str.splitlines():
|
48 |
-
if not line.strip() or line.strip().startswith('#'): continue
|
49 |
-
key, value = line.split(':', 1) if ':' in line else line.split('=', 1)
|
50 |
-
data_dict[key.strip()] = value.strip().strip("'\"")
|
51 |
-
|
52 |
-
json_bytes = json.dumps(data_dict).encode('utf-8')
|
53 |
-
public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
|
54 |
-
aes_key = os.urandom(32)
|
55 |
-
nonce = os.urandom(12)
|
56 |
-
ciphertext_with_tag = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
57 |
-
rsa_encrypted_aes_key = public_key.encrypt(
|
58 |
-
aes_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
|
59 |
-
)
|
60 |
-
encrypted_aes_key_len_bytes = struct.pack('>I', len(rsa_encrypted_aes_key))
|
61 |
-
encrypted_payload = encrypted_aes_key_len_bytes + rsa_encrypted_aes_key + nonce + ciphertext_with_tag
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
|
71 |
|
72 |
-
|
73 |
-
|
74 |
-
data_length_header = struct.pack('>I', len(encrypted_payload))
|
75 |
-
binary_payload = ''.join(format(byte, '08b') for byte in data_length_header + encrypted_payload)
|
76 |
-
if len(binary_payload) > pixel_data.size:
|
77 |
-
raise ValueError("Data is too large for the image capacity.")
|
78 |
-
for i in range(len(binary_payload)):
|
79 |
-
pixel_data[i] = (pixel_data[i] & 0xFE) | int(binary_payload[i])
|
80 |
-
stego_pixels = pixel_data.reshape(img_rgb.size[1], img_rgb.size[0], 3)
|
81 |
-
return Image.fromarray(stego_pixels, 'RGB')
|
82 |
|
83 |
-
# ==============================================================================
|
84 |
-
# SERVER (DECODER) LOGIC
|
85 |
-
# ==============================================================================
|
86 |
-
def decode_data_from_image(image: Image.Image) -> dict:
|
87 |
-
if not KEYLOCK_PRIV_KEY:
|
88 |
-
raise gr.Error("Server Error: The API is not configured with a private key.")
|
89 |
-
if image is None:
|
90 |
-
raise gr.Error("Please provide an image to decode.")
|
91 |
-
|
92 |
try:
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
image_buffer = buffer.getvalue()
|
97 |
-
|
98 |
-
img_rgb = Image.open(io.BytesIO(image_buffer)).convert("RGB")
|
99 |
-
pixel_data = np.array(img_rgb).ravel()
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
105 |
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
|
|
|
116 |
|
117 |
-
|
118 |
-
|
119 |
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
122 |
|
123 |
-
|
124 |
-
|
125 |
-
raise gr.Error(f"Decryption failed. The image may be corrupt, not encrypted with the correct key, or the server is misconfigured. Details: {e}")
|
126 |
|
127 |
-
# ==============================================================================
|
128 |
-
# GRADIO UI HELPER FUNCTIONS
|
129 |
-
# ==============================================================================
|
130 |
-
def creator_wrapper(secret_data_str: str):
|
131 |
-
"""Wrapper for the Gradio UI to call the creator function."""
|
132 |
-
if not PUBLIC_KEY_PEM_STRING or "Error" in PUBLIC_KEY_PEM_STRING:
|
133 |
-
raise gr.Error("Cannot create image: public key file is missing or invalid.")
|
134 |
-
try:
|
135 |
-
encrypted_image = create_encrypted_image(secret_data_str, PUBLIC_KEY_PEM_STRING)
|
136 |
-
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
137 |
-
encrypted_image.save(tmp.name)
|
138 |
-
return encrypted_image, tmp.name, "β
Success! Image created and ready for download."
|
139 |
except Exception as e:
|
140 |
-
|
|
|
|
|
141 |
|
142 |
# ==============================================================================
|
143 |
# GRADIO DASHBOARD INTERFACE
|
144 |
# ==============================================================================
|
145 |
theme = gr.themes.Base(
|
146 |
primary_hue="blue",
|
147 |
-
secondary_hue="
|
148 |
neutral_hue="slate",
|
149 |
font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
|
150 |
).set(
|
151 |
-
body_background_fill="#
|
152 |
block_background_fill="white",
|
153 |
block_border_width="1px",
|
154 |
block_shadow="*shadow_drop_lg",
|
155 |
-
button_primary_background_fill="*
|
156 |
-
button_primary_background_fill_hover="*
|
157 |
button_primary_text_color="white",
|
158 |
)
|
159 |
|
160 |
with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
161 |
gr.Markdown("# π KeyLock Operations Dashboard")
|
162 |
-
gr.Markdown("A
|
163 |
|
164 |
with gr.Tabs():
|
165 |
-
with gr.TabItem("
|
166 |
-
gr.Markdown("##
|
167 |
-
|
168 |
-
gr.
|
169 |
-
|
170 |
-
with gr.Accordion("View Service Public Key", open=False):
|
171 |
-
gr.Code(value=PUBLIC_KEY_PEM_STRING, language="python", label="Service Public Key (from keylock_pub.pem)")
|
172 |
-
|
173 |
-
gr.Markdown("## API Documentation")
|
174 |
-
gr.Markdown("This server exposes a conceptual API endpoint for external clients.")
|
175 |
-
gr.Code(language="markdown", value="""
|
176 |
-
- **Endpoint**: `/run/keylock-auth-decoder`
|
177 |
-
- **Method**: `POST`
|
178 |
-
- **Body**: JSON payload `{ "data": ["<base64_encoded_image_string>"] }`
|
179 |
-
""")
|
180 |
-
|
181 |
-
with gr.TabItem("π Image Creator", id=1):
|
182 |
-
gr.Markdown("## Create an Encrypted Image for the Server")
|
183 |
-
gr.Markdown("Use this tool to encrypt data using the server's public key.")
|
184 |
-
with gr.Row():
|
185 |
with gr.Column(scale=2):
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
placeholder="USERNAME: [email protected]\nAPI_KEY: sk-12345..."
|
190 |
-
)
|
191 |
-
creator_button = gr.Button("Create Encrypted Image", variant="primary")
|
192 |
with gr.Column(scale=1):
|
193 |
-
creator_status = gr.Textbox(label="Status", interactive=False)
|
194 |
-
creator_image_output = gr.Image(label="
|
195 |
-
creator_download_output = gr.File(label="Download Image")
|
196 |
-
|
197 |
-
with gr.TabItem("π»
|
198 |
-
gr.Markdown("## Decrypt an Image via
|
199 |
-
gr.Markdown("
|
200 |
-
with gr.Row():
|
201 |
with gr.Column(scale=1):
|
202 |
-
|
203 |
-
|
204 |
with gr.Column(scale=1):
|
205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
|
207 |
# --- Wire up the component logic ---
|
208 |
creator_button.click(
|
209 |
-
fn=
|
210 |
-
inputs=[
|
211 |
outputs=[creator_image_output, creator_download_output, creator_status]
|
212 |
)
|
213 |
|
214 |
-
|
215 |
-
fn=
|
216 |
-
inputs=[
|
217 |
-
outputs=[
|
218 |
)
|
219 |
|
220 |
if __name__ == "__main__":
|
|
|
1 |
import gradio as gr
|
2 |
+
from gradio_client import Client, GradioClientError
|
3 |
+
from PIL import Image
|
|
|
4 |
import base64
|
5 |
+
import io
|
6 |
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# --- Configure Logging ---
|
9 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
10 |
logger = logging.getLogger(__name__)
|
11 |
|
12 |
# ==============================================================================
|
13 |
+
# CONFIGURATION: IDs of the remote Gradio Spaces
|
14 |
# ==============================================================================
|
15 |
+
# These should be the names of YOUR deployed spaces.
|
16 |
+
CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
|
17 |
+
SERVER_SPACE_ID = "broadfield-dev/KeyLock-Auth-Server"
|
18 |
+
# We also provide a link to the original client for reference.
|
19 |
+
CLIENT_SPACE_LINK = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Client"
|
20 |
+
|
|
|
|
|
21 |
|
22 |
# ==============================================================================
|
23 |
+
# API CALL WRAPPER FUNCTIONS
|
24 |
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
def create_image_via_api(secret_data: str, public_key: str):
|
27 |
+
"""
|
28 |
+
Calls the Creator Space API to generate an encrypted image.
|
29 |
+
This function uses 'yield' to provide real-time status updates to the UI.
|
30 |
+
"""
|
31 |
+
if not all([secret_data, public_key]):
|
32 |
+
raise gr.Error("Secret Data and Public Key are both required.")
|
|
|
33 |
|
34 |
+
status = f"Initializing client for Creator: {CREATOR_SPACE_ID}..."
|
35 |
+
yield None, None, status # Yield initial status update
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
try:
|
38 |
+
client = Client(src=CREATOR_SPACE_ID)
|
39 |
+
status = f"Calling API '/create_image' on {CREATOR_SPACE_ID}..."
|
40 |
+
yield None, None, status
|
|
|
|
|
|
|
|
|
41 |
|
42 |
+
# The 'predict' method calls the API endpoint.
|
43 |
+
# The result from an Image output in the remote API is a filepath to a temporary file.
|
44 |
+
temp_filepath = client.predict(
|
45 |
+
secret_data_str=secret_data,
|
46 |
+
public_key_pem=public_key,
|
47 |
+
api_name="/create_image" # The API name defined in the Creator space
|
48 |
+
)
|
49 |
|
50 |
+
if not temp_filepath:
|
51 |
+
raise gr.Error("Creator API did not return a valid image file path.")
|
52 |
+
|
53 |
+
# Load the image from the temporary file to display it in our dashboard's UI
|
54 |
+
created_image = Image.open(temp_filepath)
|
55 |
|
56 |
+
status = "β
Success! Image created by the Creator service."
|
57 |
+
yield created_image, temp_filepath, status
|
58 |
+
|
59 |
+
except Exception as e:
|
60 |
+
logger.error(f"Creator API call failed: {e}", exc_info=True)
|
61 |
+
# Yield the error message back to the UI
|
62 |
+
yield None, None, f"β Error calling Creator API: {e}"
|
63 |
+
|
64 |
+
|
65 |
+
def decrypt_image_via_api(image: Image.Image):
|
66 |
+
"""
|
67 |
+
Calls the Server Space API to decrypt an image.
|
68 |
+
Uses 'yield' for status updates.
|
69 |
+
"""
|
70 |
+
if image is None:
|
71 |
+
raise gr.Error("Please upload an image to decrypt.")
|
72 |
+
|
73 |
+
status = f"Initializing client for Server: {SERVER_SPACE_ID}..."
|
74 |
+
yield None, status
|
75 |
+
|
76 |
+
try:
|
77 |
+
client = Client(src=SERVER_SPACE_ID)
|
78 |
|
79 |
+
# Convert the user's uploaded PIL image to a base64 string for the server's API
|
80 |
+
with io.BytesIO() as buffer:
|
81 |
+
image.save(buffer, format="PNG")
|
82 |
+
b64_string = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
83 |
|
84 |
+
status = f"Calling API '/keylock-auth-decoder' on {SERVER_SPACE_ID}..."
|
85 |
+
yield None, status
|
86 |
|
87 |
+
# Call the server's API endpoint. The result will be a dictionary.
|
88 |
+
decrypted_json = client.predict(
|
89 |
+
image_base64_string=b64_string,
|
90 |
+
api_name="/keylock-auth-decoder" # The API name defined in the Server space
|
91 |
+
)
|
92 |
|
93 |
+
status = "β
Success! Data decrypted by the Server."
|
94 |
+
yield decrypted_json, status
|
|
|
95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
except Exception as e:
|
97 |
+
logger.error(f"Server API call failed: {e}", exc_info=True)
|
98 |
+
yield None, f"β Error calling Server API: {e}"
|
99 |
+
|
100 |
|
101 |
# ==============================================================================
|
102 |
# GRADIO DASHBOARD INTERFACE
|
103 |
# ==============================================================================
|
104 |
theme = gr.themes.Base(
|
105 |
primary_hue="blue",
|
106 |
+
secondary_hue="sky",
|
107 |
neutral_hue="slate",
|
108 |
font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
|
109 |
).set(
|
110 |
+
body_background_fill="#F8FAFC",
|
111 |
block_background_fill="white",
|
112 |
block_border_width="1px",
|
113 |
block_shadow="*shadow_drop_lg",
|
114 |
+
button_primary_background_fill="*primary_600",
|
115 |
+
button_primary_background_fill_hover="*primary_700",
|
116 |
button_primary_text_color="white",
|
117 |
)
|
118 |
|
119 |
with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
120 |
gr.Markdown("# π KeyLock Operations Dashboard")
|
121 |
+
gr.Markdown("A centralized dashboard demonstrating the entire KeyLock ecosystem by making live API calls to the deployed Creator and Server spaces.")
|
122 |
|
123 |
with gr.Tabs():
|
124 |
+
with gr.TabItem("π Image Creator", id=0):
|
125 |
+
gr.Markdown("## Create an Encrypted Image via API Call")
|
126 |
+
gr.Markdown(f"This interface calls the **`{CREATOR_SPACE_ID}`** Space to generate a new encrypted image.")
|
127 |
+
with gr.Row(variant="panel"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
with gr.Column(scale=2):
|
129 |
+
creator_secret_input = gr.Textbox(lines=5, label="Secret Data", placeholder="API_KEY: sk-123...\nUSER: demo-user")
|
130 |
+
creator_pubkey_input = gr.Textbox(lines=7, label="Public Key of the Target Server", placeholder="Paste the Server's public key here...")
|
131 |
+
creator_button = gr.Button("Create Image via Creator API", variant="primary", icon="β¨")
|
|
|
|
|
|
|
132 |
with gr.Column(scale=1):
|
133 |
+
creator_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
134 |
+
creator_image_output = gr.Image(label="Image from Creator Service", type="pil", show_download_button=True)
|
135 |
+
creator_download_output = gr.File(label="Download Image File")
|
136 |
+
|
137 |
+
with gr.TabItem("π» Client / Decoder", id=1):
|
138 |
+
gr.Markdown("## Decrypt an Image via API Call")
|
139 |
+
gr.Markdown(f"This interface acts as a client, calling the **`{SERVER_SPACE_ID}`** Space to decrypt an image.")
|
140 |
+
with gr.Row(variant="panel"):
|
141 |
with gr.Column(scale=1):
|
142 |
+
client_image_input = gr.Image(type="pil", label="Upload Encrypted Image", sources=["upload", "clipboard"])
|
143 |
+
client_button = gr.Button("Decrypt Image via Server API", variant="primary", icon="π")
|
144 |
with gr.Column(scale=1):
|
145 |
+
client_status = gr.Textbox(label="Status", interactive=False, lines=2)
|
146 |
+
client_json_output = gr.JSON(label="Decrypted Data from Server")
|
147 |
+
|
148 |
+
with gr.TabItem("βΉοΈ Service Information", id=2):
|
149 |
+
gr.Markdown("## Ecosystem Overview")
|
150 |
+
gr.Markdown(
|
151 |
+
f"""
|
152 |
+
This dashboard coordinates three separate Hugging Face Spaces to demonstrate a complete workflow:
|
153 |
+
|
154 |
+
1. **Creator Service:**
|
155 |
+
- **Space:** [{CREATOR_SPACE_ID}](https://huggingface.co/spaces/{CREATOR_SPACE_ID})
|
156 |
+
- **Role:** Provides a UI and an API (`/run/create_image`) to encrypt data into PNG images.
|
157 |
+
|
158 |
+
2. **Server (Decoder) Service:**
|
159 |
+
- **Space:** [{SERVER_SPACE_ID}](https://huggingface.co/spaces/{SERVER_SPACE_ID})
|
160 |
+
- **Role:** Holds a secret private key and provides a secure API (`/run/keylock-auth-decoder`) to decrypt images.
|
161 |
+
|
162 |
+
3. **This Dashboard:**
|
163 |
+
- **Role:** Acts as a master client and control panel, making live API calls to the other services to showcase the end-to-end process.
|
164 |
+
|
165 |
+
*Note: The original `{CLIENT_SPACE_LINK.split('/')[-1]}` is now superseded by the 'Client / Decoder' tab in this dashboard.*
|
166 |
+
"""
|
167 |
+
)
|
168 |
|
169 |
# --- Wire up the component logic ---
|
170 |
creator_button.click(
|
171 |
+
fn=create_image_via_api,
|
172 |
+
inputs=[creator_secret_input, creator_pubkey_input],
|
173 |
outputs=[creator_image_output, creator_download_output, creator_status]
|
174 |
)
|
175 |
|
176 |
+
client_button.click(
|
177 |
+
fn=decrypt_image_via_api,
|
178 |
+
inputs=[client_image_input],
|
179 |
+
outputs=[client_json_output, client_status]
|
180 |
)
|
181 |
|
182 |
if __name__ == "__main__":
|