cryogenic22 commited on
Commit
8b12079
·
verified ·
1 Parent(s): fdff852

Update storage/storage_manager.py

Browse files
Files changed (1) hide show
  1. storage/storage_manager.py +53 -21
storage/storage_manager.py CHANGED
@@ -13,14 +13,17 @@ class UserStorageManager:
13
 
14
  def ensure_directories(self):
15
  """Ensure all required directories exist"""
16
- for path in self.paths.values():
17
- path.mkdir(parents=True, exist_ok=True)
 
 
 
18
 
19
  def save_chat(self, chat_data, images=None, filename=None):
20
  """Save chat with associated images"""
21
  try:
22
- timestamp = datetime.now().isoformat() # Use ISO format timestamp
23
- formatted_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # For filename
24
  chat_id = f"chat_{formatted_timestamp}"
25
 
26
  if filename:
@@ -32,31 +35,60 @@ class UserStorageManager:
32
  # Add metadata
33
  chat_metadata = {
34
  'id': chat_id,
35
- 'timestamp': timestamp, # ISO format for proper datetime parsing
36
- 'formatted_timestamp': formatted_timestamp, # For display
37
  'data': chat_data
38
  }
39
 
40
  with open(chat_file, "w") as f:
41
  json.dump(chat_metadata, f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
43
  def get_all_chats(self):
44
  """Get all user's chats with metadata"""
45
  try:
46
  chats = []
47
  for chat_file in sorted(self.paths["chats"].glob("*.json"), reverse=True):
48
- with open(chat_file, "r") as f:
49
- chat_data = json.load(f)
50
- # Load associated images if they exist
51
- chat_id = chat_data.get('id', chat_file.stem)
52
- image_dir = self.paths["images"] / chat_id
53
- if image_dir.exists():
54
- images = []
55
- for img_file in sorted(image_dir.glob("*.png")):
56
- with open(img_file, "rb") as f:
57
- images.append(f.read())
58
- chat_data['images'] = images
59
- chats.append(chat_data)
 
 
 
 
60
  return chats
61
  except Exception as e:
62
  st.error(f"Error loading chats: {str(e)}")
@@ -68,10 +100,10 @@ class UserStorageManager:
68
  chat_file = self.paths["chats"] / f"{chat_id}.json"
69
  if not chat_file.exists():
70
  return None
71
-
72
  with open(chat_file, "r") as f:
73
  chat_data = json.load(f)
74
-
75
  # Load associated images
76
  image_dir = self.paths["images"] / chat_id
77
  if image_dir.exists():
@@ -80,7 +112,7 @@ class UserStorageManager:
80
  with open(img_file, "rb") as f:
81
  images.append(f.read())
82
  chat_data['images'] = images
83
-
84
  return chat_data
85
  except Exception as e:
86
  st.error(f"Error loading chat: {str(e)}")
 
13
 
14
  def ensure_directories(self):
15
  """Ensure all required directories exist"""
16
+ try:
17
+ for path in self.paths.values():
18
+ path.mkdir(parents=True, exist_ok=True)
19
+ except Exception as e:
20
+ st.error(f"Error creating directories: {str(e)}")
21
 
22
  def save_chat(self, chat_data, images=None, filename=None):
23
  """Save chat with associated images"""
24
  try:
25
+ timestamp = datetime.now().isoformat()
26
+ formatted_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
27
  chat_id = f"chat_{formatted_timestamp}"
28
 
29
  if filename:
 
35
  # Add metadata
36
  chat_metadata = {
37
  'id': chat_id,
38
+ 'timestamp': timestamp,
39
+ 'formatted_timestamp': formatted_timestamp,
40
  'data': chat_data
41
  }
42
 
43
  with open(chat_file, "w") as f:
44
  json.dump(chat_metadata, f)
45
+
46
+ # Save associated images
47
+ if images:
48
+ image_dir = self.paths["images"] / chat_id
49
+ image_dir.mkdir(exist_ok=True)
50
+
51
+ if isinstance(images, list):
52
+ for idx, img_data in enumerate(images):
53
+ img_file = image_dir / f"image_{idx}.png"
54
+ with open(img_file, "wb") as f:
55
+ f.write(img_data)
56
+ else:
57
+ img_file = image_dir / "image_0.png"
58
+ with open(img_file, "wb") as f:
59
+ f.write(images)
60
 
61
+ # Update chat data with image references
62
+ chat_metadata['image_paths'] = [str(p) for p in image_dir.glob("*.png")]
63
+ with open(chat_file, "w") as f:
64
+ json.dump(chat_metadata, f)
65
+
66
+ return chat_id
67
+ except Exception as e:
68
+ st.error(f"Error saving chat: {str(e)}")
69
+ return None
70
+
71
  def get_all_chats(self):
72
  """Get all user's chats with metadata"""
73
  try:
74
  chats = []
75
  for chat_file in sorted(self.paths["chats"].glob("*.json"), reverse=True):
76
+ try:
77
+ with open(chat_file, "r") as f:
78
+ chat_data = json.load(f)
79
+ # Load associated images if they exist
80
+ chat_id = chat_data.get('id', chat_file.stem)
81
+ image_dir = self.paths["images"] / chat_id
82
+ if image_dir.exists():
83
+ images = []
84
+ for img_file in sorted(image_dir.glob("*.png")):
85
+ with open(img_file, "rb") as f:
86
+ images.append(f.read())
87
+ chat_data['images'] = images
88
+ chats.append(chat_data)
89
+ except Exception as e:
90
+ st.warning(f"Error loading chat {chat_file.name}: {str(e)}")
91
+ continue
92
  return chats
93
  except Exception as e:
94
  st.error(f"Error loading chats: {str(e)}")
 
100
  chat_file = self.paths["chats"] / f"{chat_id}.json"
101
  if not chat_file.exists():
102
  return None
103
+
104
  with open(chat_file, "r") as f:
105
  chat_data = json.load(f)
106
+
107
  # Load associated images
108
  image_dir = self.paths["images"] / chat_id
109
  if image_dir.exists():
 
112
  with open(img_file, "rb") as f:
113
  images.append(f.read())
114
  chat_data['images'] = images
115
+
116
  return chat_data
117
  except Exception as e:
118
  st.error(f"Error loading chat: {str(e)}")