broadfield-dev commited on
Commit
94b8a3f
Β·
verified Β·
1 Parent(s): 3e07d2b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -162
app.py CHANGED
@@ -1,220 +1,182 @@
1
  import gradio as gr
2
- import json
3
- import os
4
- import io
5
  import base64
6
- import struct
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
- # LOAD KEYS AND CONFIG
29
  # ==============================================================================
30
- KEYLOCK_PRIV_KEY = os.environ.get('KEYLOCK_PRIV_KEY')
31
- PUBLIC_KEY_PEM_STRING = ""
32
- try:
33
- with open("keylock_pub.pem", "r") as f:
34
- PUBLIC_KEY_PEM_STRING = f.read()
35
- logger.info("Successfully loaded public key from keylock_pub.pem.")
36
- except FileNotFoundError:
37
- PUBLIC_KEY_PEM_STRING = "Error: keylock_pub.pem file not found. 'Creator' tab will not work."
38
 
39
  # ==============================================================================
40
- # CREATOR LOGIC
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
- # 2. Create Carrier Image and Embed Data
64
- img = Image.new('RGB', (800, 600), color=(45, 52, 54))
65
- draw = ImageDraw.Draw(img)
66
- try:
67
- font = ImageFont.truetype("DejaVuSans.ttf", 40)
68
- except IOError:
69
- font = ImageFont.load_default()
70
- draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
71
 
72
- img_rgb = img.convert("RGB")
73
- pixel_data = np.array(img_rgb).ravel()
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
- private_key = serialization.load_pem_private_key(KEYLOCK_PRIV_KEY.encode(), password=None)
94
- with io.BytesIO() as buffer:
95
- image.save(buffer, format="PNG")
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
- header_binary_string = "".join(str(p & 1) for p in pixel_data[:32])
102
- data_length = int(header_binary_string, 2)
103
- end_offset = 32 + (data_length * 8)
104
- if pixel_data.size < end_offset: raise ValueError("Image data corrupt or truncated.")
 
 
 
105
 
106
- data_binary_string = "".join(str(p & 1) for p in pixel_data[32:end_offset])
107
- crypto_payload = int(data_binary_string, 2).to_bytes(data_length, byteorder='big')
 
 
 
108
 
109
- rsa_key_len = private_key.key_size // 8
110
- len_header = struct.unpack('>I', crypto_payload[:4])[0]
111
- if len_header != rsa_key_len: raise ValueError("Key pair mismatch or corrupt data.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- encrypted_key = crypto_payload[4:4 + rsa_key_len]
114
- nonce = crypto_payload[4 + rsa_key_len : 4 + rsa_key_len + 12]
115
- ciphertext = crypto_payload[4 + rsa_key_len + 12:]
 
116
 
117
- aes_key = private_key.decrypt(encrypted_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
118
- decrypted_bytes = AESGCM(aes_key).decrypt(nonce, ciphertext, None)
119
 
120
- logger.info("Successfully decoded an image via internal call.")
121
- return json.loads(decrypted_bytes.decode('utf-8'))
 
 
 
122
 
123
- except Exception as e:
124
- logger.error(f"Decryption failed: {e}", exc_info=True)
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
- return None, None, f"❌ Error: {e}"
 
 
141
 
142
  # ==============================================================================
143
  # GRADIO DASHBOARD INTERFACE
144
  # ==============================================================================
145
  theme = gr.themes.Base(
146
  primary_hue="blue",
147
- secondary_hue="blue",
148
  neutral_hue="slate",
149
  font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
150
  ).set(
151
- body_background_fill="#F0F2F5",
152
  block_background_fill="white",
153
  block_border_width="1px",
154
  block_shadow="*shadow_drop_lg",
155
- button_primary_background_fill="*primary_500",
156
- button_primary_background_fill_hover="*primary_600",
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 unified dashboard to demonstrate the KeyLock ecosystem: API Server, Image Creator, and API Client.")
163
 
164
  with gr.Tabs():
165
- with gr.TabItem("πŸ“‘ API Server Status & Docs", id=0):
166
- gr.Markdown("## Server Status")
167
- key_status = "βœ… Loaded successfully from secrets." if KEYLOCK_PRIV_KEY else "❌ NOT FOUND. The API will not work. Set the `KEYLOCK_PRIV_KEY` secret in the Space settings."
168
- gr.Textbox(label="Private Key Status", value=key_status, interactive=False)
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
- creator_input = gr.Textbox(
187
- lines=7,
188
- label="Secret Data (Key-Value Pairs)",
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="Generated Encrypted Image", type="pil")
195
- creator_download_output = gr.File(label="Download Image")
196
-
197
- with gr.TabItem("πŸ’» API Client (Simulator)", id=2):
198
- gr.Markdown("## Decrypt an Image via Simulated API Call")
199
- gr.Markdown("Upload an image created by the 'Creator' tab to test the server's decryption logic.")
200
- with gr.Row():
201
  with gr.Column(scale=1):
202
- client_input_image = gr.Image(type="pil", label="Upload Encrypted Image", sources=["upload", "clipboard"])
203
- client_decrypt_button = gr.Button("Decrypt Image", variant="primary")
204
  with gr.Column(scale=1):
205
- client_output_json = gr.JSON(label="Decrypted Data from Server")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  # --- Wire up the component logic ---
208
  creator_button.click(
209
- fn=creator_wrapper,
210
- inputs=[creator_input],
211
  outputs=[creator_image_output, creator_download_output, creator_status]
212
  )
213
 
214
- client_decrypt_button.click(
215
- fn=decode_data_from_image,
216
- inputs=[client_input_image],
217
- outputs=[client_output_json]
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__":