-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbackup.py
58 lines (36 loc) · 1.71 KB
/
backup.py
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
import json
import jsonpickle
import streamlit as st
from common import Conversation, set_openai_api_key
from encryption import DEFAULT_KEY, decrypt, decrypt_prop, encrypt, encrypt_prop, generate_key
BACKUP_PROPS = ["openai_key", "databases", "current_conversation"]
def backup_settings(password: str) -> dict:
backup = dict()
backup["use_default_key"] = not password
enc_key = generate_key(password) if password else DEFAULT_KEY
for prop in BACKUP_PROPS:
value = st.session_state[prop]
if isinstance(value, dict):
value = {k: json.loads(jsonpickle.encode(encrypt_prop(v, enc_key))) for k, v in value.items()}
if prop == "openai_key":
value = encrypt(value.encode("utf-8"), enc_key).decode("utf-8")
backup[prop] = value
return backup
def load_settings(backup: dict, password: str):
enc_key = generate_key(password) if password else DEFAULT_KEY
for prop in BACKUP_PROPS:
if prop in backup:
value = backup[prop]
if isinstance(value, dict):
value = {k: decrypt_prop(jsonpickle.decode(json.dumps(v)), enc_key) for k, v in value.items()}
if prop == "openai_key":
value = decrypt(value.encode("utf-8"), enc_key).decode("utf-8")
set_openai_api_key(value)
st.session_state[prop] = value
def backup_conversation(id: str) -> dict:
if id not in st.session_state.conversations:
return None
return json.loads(jsonpickle.encode(st.session_state.conversations[id]))
def load_conversation(backup: dict) -> Conversation:
# As this will create a new object, the timestamp will be updated
return jsonpickle.decode(json.dumps(backup))