-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_threads.py
310 lines (237 loc) · 9.79 KB
/
app_threads.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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# This code handles the threads in the LocalGPT
# Image attachment are saved as the file paths in the json files
# Since thread is loaded form the file only once, base64s will be created and attached in the json->st.session_state.messages at that time
# But in rest (in the json saved), only the file paths will be saved
# Now, once thread with base64s is loaded in st, we do not load the json file again and again.
# Instead, st.session_state.messages (thread) is saved repeatedly in the json file
# So, while saving the thread, we will remove the base64s (file paths remain as it is since they were not updated / removed).
import os
import json
from datetime import datetime
from app_images import image_list_to_base64
def get_timestamp():
"""Get current timestamp in a formatted string
Returns:
str: Formatted timestamp
"""
return datetime.now().strftime("%d-%m-%Y %H:%M:%S")
# Get the time-stamp of the current time, suitable for filenames:
def get_timestamp_filename():
"""Get current timestamp in a formatted string, suitable for filenames
Returns:
str: Formatted timestamp
"""
return datetime.now().strftime("%d-%m-%Y_%H-%M-%S")
# Read the file "./sample_thread.json" and "./sample_api_call.json" once to understand the structure of the json file and design of save and load functions.
# Function to save conversation to a file:
def save_conversation(
messages: list[dict],
thread_name: str,
model_name: str,
thread_folder: str
):
"""Save the conversation to a json file and update the config in same file with the last used model name
Args:
messages (list[dict]): List of messages to save
thread_name (str): Name of the thread to save
model_name (str): Name of the model used in the thread
thread_folder (str): Folder where the thread is saved
Returns:
dict: Dictionary containing the status of the saving
"""
ts = get_timestamp()
try:
# Remove the base64 images from the messages before saving to json
for message in messages:
if message.get("role") == "user" and "images" in message:
del message["images"]
json_to_save = {
"config": {
"model": model_name,
"last_saved": ts
},
"messages": messages
}
filename = f"{thread_folder}/{thread_name}.json"
with open(filename, "w") as file:
json.dump(json_to_save, file, indent=4)
return {"status": "success", "timestamp": ts}
except Exception as e:
return {"status": "error", "message": f"Failed to save thread. \n\n {str(e)}"}
# function to load conversation from a file:
def load_conversation(thread_name: str, thread_folder: str, image_folder: str):
"""Load the conversation from a json file and set the model to the last used model
Args:
thread_name (str): Name of the thread to load
thread_folder (str): Folder where the thread is saved
image_folder (str): Folder where the images are saved under threads' folders
Returns:
dict: Dictionary containing the messages, thread name, model name and last saved timestamp
"""
try:
filename = f"{thread_folder}/{thread_name}.json"
with open(filename, "r") as file:
thread_json = json.load(file)
last_saved = thread_json.get("config", {}).get(
"last_saved", get_timestamp())
model_name = thread_json.get("config", {}).get("model", None)
messages = thread_json.get("messages", [])
# Add base64 images to the messages based on the image file paths:
for message in messages:
if message.get("role") == "user" and "image_files" in message:
resp = image_list_to_base64(
image_list=message["image_files"],
image_folder=image_folder,
thread_name=thread_name
)
if resp["status"] == "success":
message["images"] = resp["result"]
else:
# If there is error in processing some single image, return the error message of that image as it is
return resp
return {
"status": "success",
"messages": messages,
"thread_name": thread_name,
"model_name": model_name,
"last_saved": last_saved
}
except Exception as e:
return {"status": "error", "message": f"Failed to load thread. \n\n {str(e)}"}
# Rename the thread file:
def rename_thread(
old_thread_name: str,
new_thread_name: str,
thread_folder: str,
):
"""Rename the thread and its json file
Args:
old_thread_name (str): Old name of the thread
new_thread_name (str): New name of the thread
thread_folder (str): Folder where the thread is saved
Returns:
dict: Dictionary containing the status of the renaming
"""
try:
old_filename = f"{thread_folder}/{old_thread_name}.json"
new_filename = f"{thread_folder}/{new_thread_name}.json"
if os.path.exists(old_filename):
os.rename(old_filename, new_filename)
return {"status": "success"}
else:
return {"status": "error", "message": "Thread not found"}
except Exception as e:
return {"status": "error", "message": f"Failed to rename thread. \n\n {str(e)}"}
# Load thread names by latest first order:
def load_thread_names(thread_folder: str):
"""Load all the thread names present in the Threads folder, based on the last modified time of the file
Args:
thread_folder (str): Folder where the threads are saved
Returns:
list: List of thread names
"""
thread_names = []
files = []
for file in os.listdir(thread_folder):
if file.endswith(".json"):
files.append(file)
files.sort(key=lambda x: os.path.getmtime(
f"{thread_folder}/{x}"), reverse=True)
for file in files:
thread_names.append(file.split(".")[0])
return thread_names
# Delete the thread:
def delete_thread(
thread_name: str,
thread_folder: str,
deleted_threads_folder: str,
image_folder: str,
deleted_images_folder: str
):
"""Deletes the thread from page view, but actually moves it to 'deleted' folder
Args:
thread_name (str): Name of the thread to delete
thread_folder (str): Folder where the thread is saved
deleted_threads_folder (str): Folder where the deleted threads are moved
image_folder (str): Folder where the images are saved under threads' folders
deleted_images_folder (str): Folder where the deleted images are moved
Returns:
dict: Dictionary containing the status of the deletion
"""
try:
old_filename = f"{thread_folder}/{thread_name}.json"
new_filename = f"{deleted_threads_folder}/{thread_name}.json"
# If file already exists in deleted folder, add timestamp to new filename:
if os.path.exists(new_filename):
new_filename = f"{deleted_threads_folder}/{thread_name}_{get_timestamp_filename()}.json"
# Move the file to deleted folder
if os.path.exists(old_filename):
os.rename(old_filename, new_filename)
# Move the thread's images folder to deleted folder:
old_image_folder = f"{image_folder}/{thread_name}"
new_image_folder = f"{deleted_images_folder}/{thread_name}/"
if not os.path.exists(new_image_folder):
os.makedirs(new_image_folder)
if os.path.exists(old_image_folder):
for file in os.listdir(old_image_folder):
os.rename(f"{old_image_folder}/{file}",
f"{new_image_folder}/{file}")
os.rmdir(old_image_folder)
return {"status": "success"}
except Exception as e:
return {"status": "error", "message": f"Failed to delete thread. \n\n {str(e)}"}
def create_new_thread(thread_folder: str):
"""Create a new thread with default values"""
thread_name = f"New Thread"
# Check the thread folder if thread_name already exists, if yes, add timestamp to the new thread name
if f"{thread_folder}/{thread_name}.json" in os.listdir(thread_folder):
thread_name = f"New Thread {get_timestamp_filename()}"
return thread_name
# ---------------------------------------------------------------------------------------
# Test calls:
# ---------------------------------------------------------------------------------------
# # Save conversation:
# messages = [
# {
# "role": "ai",
# "content": "Hello 👋, How may I help you?"
# },
# {
# "role": "user",
# "content": "prompt",
# "image_files": ["filename.png"],
# "images": ["this base64 should be removed"]
# }
# ]
# save_conversation(
# messages=messages,
# thread_name="test_save_thread",
# model_name="bs3.1:latest",
# folder="Threads"
# )
# # Load conversation:
# conversation = load_conversation(
# thread_name="test_save_thread",
# thread_folder="Threads",
# image_folder="Threads/images"
# )
# print(json.dumps(conversation, indent=4))
# # Rename thread:
# a = rename_thread(
# old_thread_name="test_save_thread_renamed",
# new_thread_name="test_save_thread",
# thread_folder="Threads"
# )
# print(json.dumps(a, indent=4))
# # Load thread names:
# thread_names = load_thread_names("Threads")
# print(thread_names)
# # Delete thread:
# a = delete_thread(
# thread_name="test_save_thread",
# thread_folder="Threads",
# deleted_threads_folder="Threads/deleted",
# image_folder="Threads/images",
# deleted_images_folder="Threads/deleted/images"
# )
# print(json.dumps(a, indent=4))