import json import os from hashlib import sha256 def save_user_data_to_json(username, file_path='users.json'): user = users[username] # Load existing data if os.path.exists(file_path): with open(file_path, 'r') as file: try: existing_data = json.load(file) except json.JSONDecodeError: existing_data = {} else: existing_data = {} # Update or add the user's data, including hashed password user_data = { "name": username, "hashed_password": user['hashed_password'], "history": user['history'] } existing_data[username] = user_data # Save updated data back to file with open(file_path, 'w') as file: json.dump(existing_data, file, indent=4) 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(username, input_value, users, input_type='keywords'): # Ensure the user exists user = users[username] if username not in users: print(f"User {username} not found in {users}") return # Initialize the history as a list of dictionaries if empty if not user['history']: user['history'] = {"keywords": [], "prompts": []} # Add the input value to the corresponding list for word in input_value: if word not in user['history'][input_type]: user['history'][input_type].append(word) def update_json(user, prompt, keywords): print(f"TYPE PROMPT = {type(prompt)}") username = user['name'] if username != 'Guest': add_user_pref(username, [prompt], users,input_type='prompts') add_user_pref(username, keywords, users,input_type='keywords') save_user_data_to_json(username) with open('users.json', 'r') as file: saved_data = json.load(file) def auth_user(username, password): if username in users and sha256(password.encode()).hexdigest() == users[username]['hashed_password']: #mistral_api_key = os.environ[username] 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'])