Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,4 @@
|
|
1 |
import gradio as gr
|
2 |
-
from gradio_client import Client
|
3 |
from PIL import Image, ImageDraw, ImageFont
|
4 |
import base64
|
5 |
import io
|
@@ -7,7 +6,6 @@ import json
|
|
7 |
import logging
|
8 |
import os
|
9 |
import requests
|
10 |
-
import tempfile
|
11 |
import struct
|
12 |
import numpy as np
|
13 |
from cryptography.hazmat.primitives import serialization
|
@@ -20,20 +18,18 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(level
|
|
20 |
logger = logging.getLogger(__name__)
|
21 |
|
22 |
# ==============================================================================
|
23 |
-
# CONFIGURATION
|
24 |
# ==============================================================================
|
25 |
-
CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
|
26 |
-
SERVER_SPACE_ID = "broadfield-dev/KeyLock-Auth-Server"
|
27 |
CREATOR_ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
|
28 |
-
|
29 |
BASE_HF_URL = "https://huggingface.co/spaces/"
|
|
|
|
|
|
|
30 |
CREATOR_URL = f"{BASE_HF_URL}{CREATOR_SPACE_ID}"
|
31 |
SERVER_URL = f"{BASE_HF_URL}{SERVER_SPACE_ID}"
|
32 |
-
CREATOR_APP_PY_URL = f"{CREATOR_URL}/blob/main/app.py"
|
33 |
-
SERVER_APP_PY_URL = f"{SERVER_URL}/blob/main/app.py"
|
34 |
|
35 |
# ==============================================================================
|
36 |
-
# LOCAL LOGIC (Key and Image Generation)
|
37 |
# ==============================================================================
|
38 |
def generate_rsa_keys():
|
39 |
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
@@ -73,31 +69,35 @@ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.I
|
|
73 |
# UI HELPER & REMOTE API CALL LOGIC
|
74 |
# ==============================================================================
|
75 |
|
76 |
-
# --- THIS IS THE MISSING FUNCTION THAT HAS BEEN ADDED BACK ---
|
77 |
def get_server_list():
|
78 |
-
"""Fetches the list of servers from the public JSON file."""
|
79 |
status = f"Fetching server list from remote config..."
|
80 |
-
# Yield an initial state to show the UI is working
|
81 |
yield gr.Dropdown(choices=[], value=None, label="β³ Fetching..."), status, []
|
82 |
try:
|
83 |
-
response = requests.get(
|
84 |
response.raise_for_status()
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
except Exception as e:
|
95 |
-
|
96 |
-
status = f"β Error fetching configuration: {e}"
|
97 |
-
# Yield a final error state
|
98 |
yield gr.Dropdown(choices=[], value=None, label="Error fetching servers"), status, []
|
99 |
|
100 |
-
|
101 |
def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoints: list):
|
102 |
"""UI wrapper for creating an image for a selected service."""
|
103 |
if not service_name: raise gr.Error("Please select a target server.")
|
@@ -105,7 +105,6 @@ def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoi
|
|
105 |
if not public_key: raise gr.Error(f"Could not find public key for '{service_name}'.")
|
106 |
try:
|
107 |
created_image = create_encrypted_image(secret_data, public_key)
|
108 |
-
# Use a single return for robustness
|
109 |
return created_image, f"β
Success! Image created for '{service_name}'."
|
110 |
except Exception as e:
|
111 |
return None, f"β Error: {e}"
|
@@ -116,11 +115,9 @@ def send_keylock_wrapper(service_name: str, image: Image.Image, available_endpoi
|
|
116 |
if image is None: raise gr.Error("Please upload an image to send.")
|
117 |
|
118 |
api_endpoint = next((e.get('api_endpoint') for e in available_endpoints if e['name'] == service_name), None)
|
119 |
-
if not api_endpoint:
|
120 |
-
raise gr.Error(f"Configuration Error: Could not find 'api_endpoint' for '{service_name}'.")
|
121 |
|
122 |
status = f"Connecting to endpoint: {api_endpoint}"
|
123 |
-
# Use yield to provide an immediate status update
|
124 |
yield None, status
|
125 |
|
126 |
try:
|
@@ -211,11 +208,9 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
211 |
gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
212 |
|
213 |
def refresh_and_update_all():
|
214 |
-
# The generator must be iterated to get its values
|
215 |
for dropdown_update, status_update, state_update in get_server_list():
|
216 |
-
|
217 |
-
pass # We only care about the final state
|
218 |
-
# Update both dropdowns and the state
|
219 |
return dropdown_update, dropdown_update, status_update, state_update
|
220 |
|
221 |
refresh_button.click(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])
|
|
|
1 |
import gradio as gr
|
|
|
2 |
from PIL import Image, ImageDraw, ImageFont
|
3 |
import base64
|
4 |
import io
|
|
|
6 |
import logging
|
7 |
import os
|
8 |
import requests
|
|
|
9 |
import struct
|
10 |
import numpy as np
|
11 |
from cryptography.hazmat.primitives import serialization
|
|
|
18 |
logger = logging.getLogger(__name__)
|
19 |
|
20 |
# ==============================================================================
|
21 |
+
# CONFIGURATION
|
22 |
# ==============================================================================
|
|
|
|
|
23 |
CREATOR_ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
|
|
|
24 |
BASE_HF_URL = "https://huggingface.co/spaces/"
|
25 |
+
# Define these here for cleaner linking in the UI
|
26 |
+
CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
|
27 |
+
SERVER_SPACE_ID = "broadfield-dev/KeyLock-Auth-Server"
|
28 |
CREATOR_URL = f"{BASE_HF_URL}{CREATOR_SPACE_ID}"
|
29 |
SERVER_URL = f"{BASE_HF_URL}{SERVER_SPACE_ID}"
|
|
|
|
|
30 |
|
31 |
# ==============================================================================
|
32 |
+
# LOCAL LOGIC (Key and Image Generation)
|
33 |
# ==============================================================================
|
34 |
def generate_rsa_keys():
|
35 |
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
|
69 |
# UI HELPER & REMOTE API CALL LOGIC
|
70 |
# ==============================================================================
|
71 |
|
|
|
72 |
def get_server_list():
|
73 |
+
"""Fetches and validates the list of servers from the public JSON file."""
|
74 |
status = f"Fetching server list from remote config..."
|
|
|
75 |
yield gr.Dropdown(choices=[], value=None, label="β³ Fetching..."), status, []
|
76 |
try:
|
77 |
+
response = requests.get(ENDPOINTS_JSON_URL, timeout=10)
|
78 |
response.raise_for_status()
|
79 |
+
|
80 |
+
all_entries = response.json()
|
81 |
+
valid_endpoints = []
|
82 |
+
required_keys = ["name", "api_endpoint", "public_key"]
|
83 |
+
|
84 |
+
# --- ROBUST VALIDATION LOGIC ---
|
85 |
+
for entry in all_entries:
|
86 |
+
if all(key in entry for key in required_keys):
|
87 |
+
valid_endpoints.append(entry)
|
88 |
+
else:
|
89 |
+
logger.warning(f"Skipping invalid entry in configuration file: {entry}")
|
90 |
+
|
91 |
+
if not valid_endpoints:
|
92 |
+
raise ValueError("No valid server configurations found in the remote file.")
|
93 |
+
|
94 |
+
endpoint_names = [e['name'] for e in valid_endpoints]
|
95 |
+
status = f"β
Success! Found {len(endpoint_names)} valid servers."
|
96 |
+
yield gr.Dropdown(choices=endpoint_names, value=endpoint_names[0] if endpoint_names else None, label="Target Server"), status, valid_endpoints
|
97 |
except Exception as e:
|
98 |
+
status = f"β Error fetching or parsing configuration: {e}"
|
|
|
|
|
99 |
yield gr.Dropdown(choices=[], value=None, label="Error fetching servers"), status, []
|
100 |
|
|
|
101 |
def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoints: list):
|
102 |
"""UI wrapper for creating an image for a selected service."""
|
103 |
if not service_name: raise gr.Error("Please select a target server.")
|
|
|
105 |
if not public_key: raise gr.Error(f"Could not find public key for '{service_name}'.")
|
106 |
try:
|
107 |
created_image = create_encrypted_image(secret_data, public_key)
|
|
|
108 |
return created_image, f"β
Success! Image created for '{service_name}'."
|
109 |
except Exception as e:
|
110 |
return None, f"β Error: {e}"
|
|
|
115 |
if image is None: raise gr.Error("Please upload an image to send.")
|
116 |
|
117 |
api_endpoint = next((e.get('api_endpoint') for e in available_endpoints if e['name'] == service_name), None)
|
118 |
+
if not api_endpoint: raise gr.Error(f"Configuration Error: Could not find 'api_endpoint' for '{service_name}'.")
|
|
|
119 |
|
120 |
status = f"Connecting to endpoint: {api_endpoint}"
|
|
|
121 |
yield None, status
|
122 |
|
123 |
try:
|
|
|
208 |
gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
209 |
|
210 |
def refresh_and_update_all():
|
211 |
+
# The generator must be iterated to get its final values
|
212 |
for dropdown_update, status_update, state_update in get_server_list():
|
213 |
+
pass
|
|
|
|
|
214 |
return dropdown_update, dropdown_update, status_update, state_update
|
215 |
|
216 |
refresh_button.click(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])
|