Standard_Intelligence_Dev / users_management.py
heymenn's picture
Update users_management.py
aeaa082 verified
import json
import os
from hashlib import sha256
import gradio as gr
def save_user_data_to_json(user, conf_file_path='users.json'):
username = user['name']
# Load existing data
if os.path.exists(conf_file_path):
with open(conf_file_path, 'r') as file:
try:
existing_data = json.load(file)
except json.JSONDecodeError:
existing_data = {}
else:
existing_data = {}
existing_data[username] = user
# Save updated data back to file
with open(conf_file_path, 'w') as file:
json.dump(existing_data, file, indent=4)
return conf_file_path
def load_from_json(file_path='users.json'):
"""
Load user data from a JSON file and return it as a dictionary.
:param file_path: The path to the JSON file from which to load user data.
:return: A dictionary containing the user data loaded from the JSON file.
"""
if os.path.exists(file_path):
with open(file_path, 'r') as file:
try:
user_data = json.load(file)
return user_data
except json.JSONDecodeError as e:
print(f"Error decoding JSON from {file_path}: {e}")
return {}
else:
print(f"File {file_path} not found.")
return {}
def add_user_pref(user, input_value, input_type='keywords'):
if not user['history']:
user['history'] = {"keywords": [], "prompts": []}
for word in input_value:
if word not in user['history'][input_type]:
user['history'][input_type].append(word)
return user
def update_json(user, prompt, keywords):
username = user['name']
users = load_from_json()
user = users.get(username)
print(f"TYPE PROMPT = {type(prompt)}")
if username != 'Guest':
user = add_user_pref(user, prompt, input_type='prompts')
user = add_user_pref(user, keywords, input_type='keywords')
conf_file_path = save_user_data_to_json(user)
# with open('users.json', 'r') as file:
# saved_data = json.load(file)
else:
conf_file_path = "users.json"
users = load_from_json()
user = users.get(username)
return gr.update(choices=user['history']['prompts']), gr.update(choices=user['history']['keywords']), user, conf_file_path
def auth_user(username, password):
users = load_from_json()
if username in users and sha256(password.encode()).hexdigest() == users[username]['hashed_password']:
user = users.get(username)
else:
username = 'Guest'
user = users.get(username)
return user, f"## Hi {username}!", gr.update(choices=user['history']['prompts']), gr.update(choices=user['history']['keywords'])
def logout():
username = 'Guest'
user = users.get(username)
return user, f"## Hi {username}!", gr.update(choices=user['history']['prompts']), gr.update(choices=user['history']['keywords'])
users = load_from_json()