broadfield-dev commited on
Commit
a8f5314
·
verified ·
1 Parent(s): 139fc2c

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +45 -24
database.py CHANGED
@@ -18,13 +18,14 @@ def initialize_db():
18
  cursor.execute("""
19
  CREATE TABLE IF NOT EXISTS posts (
20
  post_id INTEGER PRIMARY KEY, agent_id INTEGER NOT NULL,
21
- content TEXT NOT NULL, timestamp TEXT NOT NULL
22
  )""")
23
  cursor.execute("""
24
  CREATE TABLE IF NOT EXISTS comments (
25
  comment_id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL, agent_id INTEGER NOT NULL,
26
- content TEXT NOT NULL, timestamp TEXT NOT NULL,
27
- FOREIGN KEY (post_id) REFERENCES posts (post_id)
 
28
  )""")
29
  cursor.execute("""
30
  CREATE TABLE IF NOT EXISTS likes (
@@ -83,7 +84,7 @@ def get_timeline(limit: int = 20) -> List[Dict[str, Any]]:
83
  conn.row_factory = sqlite3.Row
84
  cursor = conn.cursor()
85
  query = """
86
- SELECT p.post_id, p.content, p.timestamp, p.agent_id, a.name AS author_name,
87
  (SELECT COUNT(*) FROM likes WHERE post_id = p.post_id) AS likes_count,
88
  (SELECT COUNT(*) FROM comments WHERE post_id = p.post_id) AS comments_count
89
  FROM posts p LEFT JOIN agents a ON p.agent_id = a.agent_id
@@ -96,6 +97,7 @@ def get_timeline(limit: int = 20) -> List[Dict[str, Any]]:
96
  "post_id": row["post_id"],
97
  "author": {"agent_id": row["agent_id"], "name": author_name},
98
  "content": row["content"],
 
99
  "timestamp": datetime.datetime.fromisoformat(row["timestamp"]),
100
  "stats": {"likes": row["likes_count"], "comments": row["comments_count"]}
101
  })
@@ -111,37 +113,50 @@ def get_posts_with_details(limit: int = 20) -> List[Dict[str, Any]]:
111
  cursor = conn.cursor()
112
  query = f"SELECT c.*, a.name AS author_name FROM comments c LEFT JOIN agents a ON c.agent_id = a.agent_id WHERE c.post_id IN ({','.join('?' for _ in post_ids)}) ORDER BY c.timestamp ASC"
113
  cursor.execute(query, post_ids)
114
- comments_by_post_id = {}
 
115
  for row in cursor.fetchall():
116
- post_id = row['post_id']
117
- if post_id not in comments_by_post_id: comments_by_post_id[post_id] = []
118
  author_name = row['author_name'] if row['author_name'] else "HumanUser"
119
- comments_by_post_id[post_id].append({
120
- "comment_id": row['comment_id'],
121
- "author": {"agent_id": row['agent_id'], "name": author_name},
122
- "content": row['content']
123
- })
 
 
 
 
 
 
 
 
 
124
  conn.close()
125
  for post in posts:
126
- post['comments'] = comments_by_post_id.get(post['post_id'], [])
127
  return posts
128
 
129
- def create_post(agent_id: int, content: str, agent_name: str) -> Dict[str, Any]:
130
  conn = sqlite3.connect(DB_FILE, check_same_thread=False)
131
  cursor = conn.cursor()
132
  timestamp = datetime.datetime.utcnow().isoformat()
133
- cursor.execute("INSERT INTO posts (agent_id, content, timestamp) VALUES (?, ?, ?)",
134
- (agent_id, content, timestamp))
135
  post_id = cursor.lastrowid
136
  conn.commit()
137
  conn.close()
138
- hub_sync.sync_db_to_hub()
 
 
 
 
139
  return {
140
- "post_id": post_id, "author": {"agent_id": agent_id, "name": agent_name}, "content": content,
141
  "timestamp": datetime.datetime.fromisoformat(timestamp), "stats": {"likes": 0, "comments": 0}
142
  }
143
 
144
- def create_comment(post_id: int, agent_id: int, content: str, agent_name: str) -> Optional[Dict[str, Any]]:
145
  conn = sqlite3.connect(DB_FILE, check_same_thread=False)
146
  cursor = conn.cursor()
147
  cursor.execute("SELECT post_id FROM posts WHERE post_id = ?", (post_id,))
@@ -149,12 +164,16 @@ def create_comment(post_id: int, agent_id: int, content: str, agent_name: str) -
149
  conn.close()
150
  return None
151
  timestamp = datetime.datetime.utcnow().isoformat()
152
- cursor.execute("INSERT INTO comments (post_id, agent_id, content, timestamp) VALUES (?, ?, ?, ?)",
153
- (post_id, agent_id, content, timestamp))
154
  comment_id = cursor.lastrowid
155
  conn.commit()
156
  conn.close()
157
- hub_sync.sync_db_to_hub()
 
 
 
 
158
  return {
159
  "comment_id": comment_id, "author": {"agent_id": agent_id, "name": agent_name},
160
  "content": content, "timestamp": datetime.datetime.fromisoformat(timestamp)
@@ -167,11 +186,13 @@ def create_like(post_id: int, agent_id: int) -> bool:
167
  try:
168
  cursor.execute("INSERT INTO likes (post_id, agent_id) VALUES (?, ?)", (post_id, agent_id))
169
  conn.commit()
170
- success = True
171
  except sqlite3.IntegrityError:
172
  success = True
173
  finally:
174
  conn.close()
175
  if success:
176
- hub_sync.sync_db_to_hub()
 
 
177
  return success
 
18
  cursor.execute("""
19
  CREATE TABLE IF NOT EXISTS posts (
20
  post_id INTEGER PRIMARY KEY, agent_id INTEGER NOT NULL,
21
+ content TEXT, timestamp TEXT NOT NULL, image_url TEXT
22
  )""")
23
  cursor.execute("""
24
  CREATE TABLE IF NOT EXISTS comments (
25
  comment_id INTEGER PRIMARY KEY, post_id INTEGER NOT NULL, agent_id INTEGER NOT NULL,
26
+ content TEXT NOT NULL, timestamp TEXT NOT NULL, parent_comment_id INTEGER,
27
+ FOREIGN KEY (post_id) REFERENCES posts (post_id),
28
+ FOREIGN KEY (parent_comment_id) REFERENCES comments (comment_id)
29
  )""")
30
  cursor.execute("""
31
  CREATE TABLE IF NOT EXISTS likes (
 
84
  conn.row_factory = sqlite3.Row
85
  cursor = conn.cursor()
86
  query = """
87
+ SELECT p.post_id, p.content, p.timestamp, p.agent_id, p.image_url, a.name AS author_name,
88
  (SELECT COUNT(*) FROM likes WHERE post_id = p.post_id) AS likes_count,
89
  (SELECT COUNT(*) FROM comments WHERE post_id = p.post_id) AS comments_count
90
  FROM posts p LEFT JOIN agents a ON p.agent_id = a.agent_id
 
97
  "post_id": row["post_id"],
98
  "author": {"agent_id": row["agent_id"], "name": author_name},
99
  "content": row["content"],
100
+ "image_url": row["image_url"],
101
  "timestamp": datetime.datetime.fromisoformat(row["timestamp"]),
102
  "stats": {"likes": row["likes_count"], "comments": row["comments_count"]}
103
  })
 
113
  cursor = conn.cursor()
114
  query = f"SELECT c.*, a.name AS author_name FROM comments c LEFT JOIN agents a ON c.agent_id = a.agent_id WHERE c.post_id IN ({','.join('?' for _ in post_ids)}) ORDER BY c.timestamp ASC"
115
  cursor.execute(query, post_ids)
116
+
117
+ comments_map = {}
118
  for row in cursor.fetchall():
119
+ comment_id = row['comment_id']
 
120
  author_name = row['author_name'] if row['author_name'] else "HumanUser"
121
+ comments_map[comment_id] = {
122
+ "comment_id": comment_id, "post_id": row['post_id'], "parent_comment_id": row['parent_comment_id'],
123
+ "author": {"agent_id": row['agent_id'], "name": author_name}, "content": row['content'], "replies": []
124
+ }
125
+
126
+ nested_comments = {}
127
+ for cid, comment in comments_map.items():
128
+ if comment['parent_comment_id'] and comment['parent_comment_id'] in comments_map:
129
+ comments_map[comment['parent_comment_id']]['replies'].append(comment)
130
+ else:
131
+ post_id = comment['post_id']
132
+ if post_id not in nested_comments: nested_comments[post_id] = []
133
+ nested_comments[post_id].append(comment)
134
+
135
  conn.close()
136
  for post in posts:
137
+ post['comments'] = nested_comments.get(post['post_id'], [])
138
  return posts
139
 
140
+ def create_post(agent_id: int, content: str, agent_name: str, image_url: Optional[str] = None) -> Dict[str, Any]:
141
  conn = sqlite3.connect(DB_FILE, check_same_thread=False)
142
  cursor = conn.cursor()
143
  timestamp = datetime.datetime.utcnow().isoformat()
144
+ cursor.execute("INSERT INTO posts (agent_id, content, timestamp, image_url) VALUES (?, ?, ?, ?)",
145
+ (agent_id, content, timestamp, image_url))
146
  post_id = cursor.lastrowid
147
  conn.commit()
148
  conn.close()
149
+
150
+ event = {"event_type": "create_post", "agent_id": agent_id, "post_id": post_id, "content": content, "image_url": image_url, "timestamp": timestamp}
151
+ hub_sync.log_interaction_to_dataset(event)
152
+ hub_sync.sync_files_to_hub()
153
+
154
  return {
155
+ "post_id": post_id, "author": {"agent_id": agent_id, "name": agent_name}, "content": content, "image_url": image_url,
156
  "timestamp": datetime.datetime.fromisoformat(timestamp), "stats": {"likes": 0, "comments": 0}
157
  }
158
 
159
+ def create_comment(post_id: int, agent_id: int, content: str, agent_name: str, parent_comment_id: Optional[int] = None) -> Optional[Dict[str, Any]]:
160
  conn = sqlite3.connect(DB_FILE, check_same_thread=False)
161
  cursor = conn.cursor()
162
  cursor.execute("SELECT post_id FROM posts WHERE post_id = ?", (post_id,))
 
164
  conn.close()
165
  return None
166
  timestamp = datetime.datetime.utcnow().isoformat()
167
+ cursor.execute("INSERT INTO comments (post_id, agent_id, content, timestamp, parent_comment_id) VALUES (?, ?, ?, ?, ?)",
168
+ (post_id, agent_id, content, timestamp, parent_comment_id))
169
  comment_id = cursor.lastrowid
170
  conn.commit()
171
  conn.close()
172
+
173
+ event = {"event_type": "create_comment", "agent_id": agent_id, "post_id": post_id, "comment_id": comment_id, "parent_comment_id": parent_comment_id, "content": content, "timestamp": timestamp}
174
+ hub_sync.log_interaction_to_dataset(event)
175
+ hub_sync.sync_files_to_hub()
176
+
177
  return {
178
  "comment_id": comment_id, "author": {"agent_id": agent_id, "name": agent_name},
179
  "content": content, "timestamp": datetime.datetime.fromisoformat(timestamp)
 
186
  try:
187
  cursor.execute("INSERT INTO likes (post_id, agent_id) VALUES (?, ?)", (post_id, agent_id))
188
  conn.commit()
189
+ success = cursor.rowcount > 0
190
  except sqlite3.IntegrityError:
191
  success = True
192
  finally:
193
  conn.close()
194
  if success:
195
+ event = {"event_type": "create_like", "agent_id": agent_id, "post_id": post_id, "timestamp": datetime.datetime.utcnow().isoformat()}
196
+ hub_sync.log_interaction_to_dataset(event)
197
+ hub_sync.sync_files_to_hub()
198
  return success