Spaces:
Running
Running
File size: 9,838 Bytes
f8cd41a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
# Secure Config Editor with Faculty-Only Access
# This ensures only authorized faculty can edit configuration
import json
import gradio as gr
import os
import hashlib
import secrets
# Faculty authentication using environment variable
FACULTY_ACCESS_CODE = os.environ.get("FACULTY_CONFIG_PASSWORD")
CONFIG_EDIT_TOKEN = os.environ.get("CONFIG_EDIT_TOKEN") # Alternative: use a secret token
def verify_faculty_access(password):
"""Verify if the user has faculty access"""
if not FACULTY_ACCESS_CODE:
return False, "β Faculty access not configured. Contact administrator."
if password == FACULTY_ACCESS_CODE:
return True, "β
Faculty access granted"
return False, "β Invalid access code"
def create_secure_config_editor():
"""Create the configuration editor with faculty authentication"""
# State to track authentication
is_authenticated = gr.State(False)
with gr.Group() as config_editor:
gr.Markdown("### π Faculty Configuration Editor")
# Authentication section
with gr.Group(visible=True) as auth_section:
gr.Markdown("This section is restricted to faculty members only.")
with gr.Row():
access_code = gr.Textbox(
label="Faculty Access Code",
type="password",
placeholder="Enter your faculty access code"
)
auth_btn = gr.Button("π Authenticate", variant="primary")
auth_status = gr.Markdown("")
# Configuration editor (hidden until authenticated)
with gr.Group(visible=False) as editor_section:
config = load_config()
gr.Markdown("### βοΈ Edit Assistant Configuration")
gr.Markdown("**Note**: Students cannot access this section. Changes affect all users.")
with gr.Row():
with gr.Column(scale=2):
system_prompt = gr.TextArea(
label="System Prompt",
value=config.get('system_prompt', ''),
lines=10,
placeholder="Define your assistant's role and behavior..."
)
with gr.Column(scale=1):
temperature = gr.Slider(
label="Temperature",
minimum=0.0,
maximum=2.0,
step=0.1,
value=config.get('temperature', 0.7)
)
max_tokens = gr.Number(
label="Max Response Tokens",
value=config.get('max_tokens', 500),
minimum=50,
maximum=8000
)
examples_text = gr.TextArea(
label="Example Prompts (one per line)",
value='\n'.join(eval(config.get('examples', '[]'))),
lines=5,
placeholder="What is machine learning?\nExplain quantum computing"
)
grounding_urls_text = gr.TextArea(
label="Grounding URLs (one per line)",
value='\n'.join(json.loads(config.get('grounding_urls', '[]'))),
lines=5,
placeholder="https://example.com/course-materials"
)
with gr.Row():
save_btn = gr.Button("πΎ Save Configuration", variant="primary")
export_btn = gr.Button("π₯ Export Config", variant="secondary")
import_btn = gr.Button("π€ Import Config", variant="secondary")
config_file = gr.File(label="Import Configuration", visible=False)
status = gr.Markdown("")
# Lock/Unlock settings for specific periods
with gr.Accordion("π Advanced: Lock Settings", open=False):
gr.Markdown("""
**Lock Configuration During Exams**
You can temporarily lock the configuration to prevent changes during exams or assessments.
""")
lock_config = gr.Checkbox(
label="Lock configuration (prevents all changes)",
value=config.get('locked', False)
)
lock_reason = gr.Textbox(
label="Lock reason (visible to other faculty)",
placeholder="e.g., Midterm exam in progress"
)
# Authentication handler
def authenticate(password):
success, message = verify_faculty_access(password)
if success:
return {
auth_status: message,
auth_section: gr.update(visible=False),
editor_section: gr.update(visible=True),
is_authenticated: True
}
else:
return {
auth_status: message,
is_authenticated: False
}
# Save configuration handler
def save_config_secure(auth_state, system_prompt, temperature, max_tokens,
examples_text, grounding_urls_text, lock_config, lock_reason):
if not auth_state:
return "β Unauthorized: Please authenticate first"
try:
config = load_config()
# Check if configuration is locked
if config.get('locked', False) and not lock_config:
lock_info = config.get('lock_reason', 'Unknown reason')
return f"β Configuration is locked: {lock_info}"
# Update configuration
config['system_prompt'] = system_prompt
config['temperature'] = temperature
config['max_tokens'] = int(max_tokens)
config['locked'] = lock_config
config['lock_reason'] = lock_reason if lock_config else ""
# Parse examples
if examples_text:
examples = [ex.strip() for ex in examples_text.split('\n') if ex.strip()]
config['examples'] = str(examples)
# Parse URLs
if grounding_urls_text:
urls = [url.strip() for url in grounding_urls_text.split('\n') if url.strip()]
config['grounding_urls'] = json.dumps(urls)
# Add audit trail
config['last_modified_by'] = 'faculty'
config['last_modified_at'] = str(datetime.now())
# Save with backup
backup_config()
with open('config.json', 'w') as f:
json.dump(config, f, indent=2)
return f"β
Configuration saved successfully! {'π Config is now LOCKED' if lock_config else ''}"
except Exception as e:
return f"β Error saving config: {str(e)}"
# Export configuration
def export_config_secure(auth_state):
if not auth_state:
return None, "β Unauthorized"
try:
# Create a sanitized version for export
config = load_config()
export_data = {
'system_prompt': config.get('system_prompt'),
'temperature': config.get('temperature'),
'max_tokens': config.get('max_tokens'),
'examples': config.get('examples'),
'grounding_urls': config.get('grounding_urls'),
'exported_at': str(datetime.now()),
'exported_by': 'faculty'
}
filename = f"assistant_config_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(filename, 'w') as f:
json.dump(export_data, f, indent=2)
return filename, "β
Configuration exported successfully"
except Exception as e:
return None, f"β Export failed: {str(e)}"
# Wire up event handlers
auth_btn.click(
authenticate,
inputs=[access_code],
outputs=[auth_status, auth_section, editor_section, is_authenticated]
)
save_btn.click(
save_config_secure,
inputs=[is_authenticated, system_prompt, temperature, max_tokens,
examples_text, grounding_urls_text, lock_config, lock_reason],
outputs=status
)
export_btn.click(
export_config_secure,
inputs=[is_authenticated],
outputs=[config_file, status]
)
return config_editor
def load_config():
"""Load configuration from config.json"""
try:
with open('config.json', 'r') as f:
return json.load(f)
except Exception as e:
return {"error": f"Failed to load config: {str(e)}"}
def backup_config():
"""Create a backup of the current configuration"""
try:
config = load_config()
backup_name = f"config_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(f"backups/{backup_name}", 'w') as f:
json.dump(config, f, indent=2)
except:
pass # Silent fail for backup
from datetime import datetime |