oceansweep
commited on
Commit
•
babbdf2
1
Parent(s):
fc897ae
Update App_Function_Libraries/DB/Character_Chat_DB.py
Browse files
App_Function_Libraries/DB/Character_Chat_DB.py
CHANGED
@@ -1,701 +1,702 @@
|
|
1 |
-
# character_chat_db.py
|
2 |
-
# Database functions for managing character cards and chat histories.
|
3 |
-
# #
|
4 |
-
# Imports
|
5 |
-
import configparser
|
6 |
-
import sqlite3
|
7 |
-
import json
|
8 |
-
import
|
9 |
-
import
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
from
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
#
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
config
|
31 |
-
config.
|
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 |
-
parsed_card['
|
213 |
-
parsed_card['
|
214 |
-
parsed_card['
|
215 |
-
parsed_card['
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
parsed_card['
|
228 |
-
parsed_card['
|
229 |
-
parsed_card['
|
230 |
-
parsed_card['
|
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 |
-
# card_data['
|
273 |
-
# card_data['
|
274 |
-
# card_data['
|
275 |
-
# card_data['
|
276 |
-
# card_data['
|
277 |
-
#
|
278 |
-
#
|
279 |
-
#
|
280 |
-
#
|
281 |
-
#
|
282 |
-
#
|
283 |
-
#
|
284 |
-
#
|
285 |
-
#
|
286 |
-
# card_data['
|
287 |
-
# card_data['
|
288 |
-
# card_data['
|
289 |
-
# card_data['
|
290 |
-
# card_data['
|
291 |
-
# card_data['
|
292 |
-
#
|
293 |
-
#
|
294 |
-
#
|
295 |
-
#
|
296 |
-
#
|
297 |
-
#
|
298 |
-
#
|
299 |
-
#
|
300 |
-
#
|
301 |
-
#
|
302 |
-
#
|
303 |
-
#
|
304 |
-
#
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
cursor.
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
card_data.get('
|
366 |
-
card_data.get('
|
367 |
-
card_data.get('
|
368 |
-
card_data.get('
|
369 |
-
card_data.get('
|
370 |
-
card_data.get('
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
cursor.execute("DELETE FROM
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
cursor
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
chat
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
List[
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
"
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
#
|
701 |
-
|
|
|
|
1 |
+
# character_chat_db.py
|
2 |
+
# Database functions for managing character cards and chat histories.
|
3 |
+
# #
|
4 |
+
# Imports
|
5 |
+
import configparser
|
6 |
+
import sqlite3
|
7 |
+
import json
|
8 |
+
import logging
|
9 |
+
import os
|
10 |
+
import sys
|
11 |
+
from typing import List, Dict, Optional, Tuple, Any, Union
|
12 |
+
|
13 |
+
from App_Function_Libraries.Utils.Utils import get_database_dir, get_project_relative_path, get_database_path
|
14 |
+
#from Tests.Chat_APIs.Chat_APIs_Integration_test import logging
|
15 |
+
|
16 |
+
#
|
17 |
+
#######################################################################################################################
|
18 |
+
#
|
19 |
+
#
|
20 |
+
|
21 |
+
def ensure_database_directory():
|
22 |
+
os.makedirs(get_database_dir(), exist_ok=True)
|
23 |
+
|
24 |
+
ensure_database_directory()
|
25 |
+
|
26 |
+
|
27 |
+
# Construct the path to the config file
|
28 |
+
config_path = get_project_relative_path('Config_Files/config.txt')
|
29 |
+
|
30 |
+
# Read the config file
|
31 |
+
config = configparser.ConfigParser()
|
32 |
+
config.read(config_path)
|
33 |
+
|
34 |
+
# Get the chat db path from the config, or use the default if not specified
|
35 |
+
chat_DB_PATH = config.get('Database', 'chatDB_path', fallback=get_database_path('chatDB.db'))
|
36 |
+
print(f"Chat Database path: {chat_DB_PATH}")
|
37 |
+
|
38 |
+
########################################################################################################
|
39 |
+
#
|
40 |
+
# Functions
|
41 |
+
|
42 |
+
# FIXME - Setup properly and test/add documentation for its existence...
|
43 |
+
def initialize_database():
|
44 |
+
"""Initialize the SQLite database with required tables and FTS5 virtual tables."""
|
45 |
+
conn = None
|
46 |
+
try:
|
47 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
48 |
+
cursor = conn.cursor()
|
49 |
+
|
50 |
+
# Enable foreign key constraints
|
51 |
+
cursor.execute("PRAGMA foreign_keys = ON;")
|
52 |
+
|
53 |
+
# Create CharacterCards table with V2 fields
|
54 |
+
cursor.execute("""
|
55 |
+
CREATE TABLE IF NOT EXISTS CharacterCards (
|
56 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
57 |
+
name TEXT UNIQUE NOT NULL,
|
58 |
+
description TEXT,
|
59 |
+
personality TEXT,
|
60 |
+
scenario TEXT,
|
61 |
+
image BLOB,
|
62 |
+
post_history_instructions TEXT,
|
63 |
+
first_mes TEXT,
|
64 |
+
mes_example TEXT,
|
65 |
+
creator_notes TEXT,
|
66 |
+
system_prompt TEXT,
|
67 |
+
alternate_greetings TEXT,
|
68 |
+
tags TEXT,
|
69 |
+
creator TEXT,
|
70 |
+
character_version TEXT,
|
71 |
+
extensions TEXT,
|
72 |
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
73 |
+
);
|
74 |
+
""")
|
75 |
+
|
76 |
+
# Create CharacterChats table
|
77 |
+
cursor.execute("""
|
78 |
+
CREATE TABLE IF NOT EXISTS CharacterChats (
|
79 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
80 |
+
character_id INTEGER NOT NULL,
|
81 |
+
conversation_name TEXT,
|
82 |
+
chat_history TEXT,
|
83 |
+
is_snapshot BOOLEAN DEFAULT FALSE,
|
84 |
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
85 |
+
FOREIGN KEY (character_id) REFERENCES CharacterCards(id) ON DELETE CASCADE
|
86 |
+
);
|
87 |
+
""")
|
88 |
+
|
89 |
+
# Create FTS5 virtual table for CharacterChats
|
90 |
+
cursor.execute("""
|
91 |
+
CREATE VIRTUAL TABLE IF NOT EXISTS CharacterChats_fts USING fts5(
|
92 |
+
conversation_name,
|
93 |
+
chat_history,
|
94 |
+
content='CharacterChats',
|
95 |
+
content_rowid='id'
|
96 |
+
);
|
97 |
+
""")
|
98 |
+
|
99 |
+
# Create triggers to keep FTS5 table in sync with CharacterChats
|
100 |
+
cursor.executescript("""
|
101 |
+
CREATE TRIGGER IF NOT EXISTS CharacterChats_ai AFTER INSERT ON CharacterChats BEGIN
|
102 |
+
INSERT INTO CharacterChats_fts(rowid, conversation_name, chat_history)
|
103 |
+
VALUES (new.id, new.conversation_name, new.chat_history);
|
104 |
+
END;
|
105 |
+
|
106 |
+
CREATE TRIGGER IF NOT EXISTS CharacterChats_ad AFTER DELETE ON CharacterChats BEGIN
|
107 |
+
DELETE FROM CharacterChats_fts WHERE rowid = old.id;
|
108 |
+
END;
|
109 |
+
|
110 |
+
CREATE TRIGGER IF NOT EXISTS CharacterChats_au AFTER UPDATE ON CharacterChats BEGIN
|
111 |
+
UPDATE CharacterChats_fts SET conversation_name = new.conversation_name, chat_history = new.chat_history
|
112 |
+
WHERE rowid = new.id;
|
113 |
+
END;
|
114 |
+
""")
|
115 |
+
|
116 |
+
# Create ChatKeywords table
|
117 |
+
cursor.execute("""
|
118 |
+
CREATE TABLE IF NOT EXISTS ChatKeywords (
|
119 |
+
chat_id INTEGER NOT NULL,
|
120 |
+
keyword TEXT NOT NULL,
|
121 |
+
FOREIGN KEY (chat_id) REFERENCES CharacterChats(id) ON DELETE CASCADE
|
122 |
+
);
|
123 |
+
""")
|
124 |
+
|
125 |
+
# Create indexes for faster searches
|
126 |
+
cursor.execute("""
|
127 |
+
CREATE INDEX IF NOT EXISTS idx_chatkeywords_keyword ON ChatKeywords(keyword);
|
128 |
+
""")
|
129 |
+
cursor.execute("""
|
130 |
+
CREATE INDEX IF NOT EXISTS idx_chatkeywords_chat_id ON ChatKeywords(chat_id);
|
131 |
+
""")
|
132 |
+
|
133 |
+
conn.commit()
|
134 |
+
logging.info("Database initialized successfully.")
|
135 |
+
except sqlite3.Error as e:
|
136 |
+
logging.error(f"SQLite error occurred during database initialization: {e}")
|
137 |
+
if conn:
|
138 |
+
conn.rollback()
|
139 |
+
raise
|
140 |
+
except Exception as e:
|
141 |
+
logging.error(f"Unexpected error occurred during database initialization: {e}")
|
142 |
+
if conn:
|
143 |
+
conn.rollback()
|
144 |
+
raise
|
145 |
+
finally:
|
146 |
+
if conn:
|
147 |
+
conn.close()
|
148 |
+
|
149 |
+
# Call initialize_database() at the start of your application
|
150 |
+
def setup_chat_database():
|
151 |
+
try:
|
152 |
+
initialize_database()
|
153 |
+
except Exception as e:
|
154 |
+
logging.critical(f"Failed to initialize database: {e}")
|
155 |
+
sys.exit(1)
|
156 |
+
|
157 |
+
setup_chat_database()
|
158 |
+
|
159 |
+
########################################################################################################
|
160 |
+
#
|
161 |
+
# Character Card handling
|
162 |
+
|
163 |
+
def parse_character_card(card_data: Dict[str, Any]) -> Dict[str, Any]:
|
164 |
+
"""Parse and validate a character card according to V2 specification."""
|
165 |
+
v2_data = {
|
166 |
+
'name': card_data.get('name', ''),
|
167 |
+
'description': card_data.get('description', ''),
|
168 |
+
'personality': card_data.get('personality', ''),
|
169 |
+
'scenario': card_data.get('scenario', ''),
|
170 |
+
'first_mes': card_data.get('first_mes', ''),
|
171 |
+
'mes_example': card_data.get('mes_example', ''),
|
172 |
+
'creator_notes': card_data.get('creator_notes', ''),
|
173 |
+
'system_prompt': card_data.get('system_prompt', ''),
|
174 |
+
'post_history_instructions': card_data.get('post_history_instructions', ''),
|
175 |
+
'alternate_greetings': json.dumps(card_data.get('alternate_greetings', [])),
|
176 |
+
'tags': json.dumps(card_data.get('tags', [])),
|
177 |
+
'creator': card_data.get('creator', ''),
|
178 |
+
'character_version': card_data.get('character_version', ''),
|
179 |
+
'extensions': json.dumps(card_data.get('extensions', {}))
|
180 |
+
}
|
181 |
+
|
182 |
+
# Handle 'image' separately as it might be binary data
|
183 |
+
if 'image' in card_data:
|
184 |
+
v2_data['image'] = card_data['image']
|
185 |
+
|
186 |
+
return v2_data
|
187 |
+
|
188 |
+
|
189 |
+
def add_character_card(card_data: Dict[str, Any]) -> Optional[int]:
|
190 |
+
"""Add or update a character card in the database."""
|
191 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
192 |
+
cursor = conn.cursor()
|
193 |
+
try:
|
194 |
+
parsed_card = parse_character_card(card_data)
|
195 |
+
|
196 |
+
# Check if character already exists
|
197 |
+
cursor.execute("SELECT id FROM CharacterCards WHERE name = ?", (parsed_card['name'],))
|
198 |
+
row = cursor.fetchone()
|
199 |
+
|
200 |
+
if row:
|
201 |
+
# Update existing character
|
202 |
+
character_id = row[0]
|
203 |
+
update_query = """
|
204 |
+
UPDATE CharacterCards
|
205 |
+
SET description = ?, personality = ?, scenario = ?, image = ?,
|
206 |
+
post_history_instructions = ?, first_mes = ?, mes_example = ?,
|
207 |
+
creator_notes = ?, system_prompt = ?, alternate_greetings = ?,
|
208 |
+
tags = ?, creator = ?, character_version = ?, extensions = ?
|
209 |
+
WHERE id = ?
|
210 |
+
"""
|
211 |
+
cursor.execute(update_query, (
|
212 |
+
parsed_card['description'], parsed_card['personality'], parsed_card['scenario'],
|
213 |
+
parsed_card['image'], parsed_card['post_history_instructions'], parsed_card['first_mes'],
|
214 |
+
parsed_card['mes_example'], parsed_card['creator_notes'], parsed_card['system_prompt'],
|
215 |
+
parsed_card['alternate_greetings'], parsed_card['tags'], parsed_card['creator'],
|
216 |
+
parsed_card['character_version'], parsed_card['extensions'], character_id
|
217 |
+
))
|
218 |
+
else:
|
219 |
+
# Insert new character
|
220 |
+
insert_query = """
|
221 |
+
INSERT INTO CharacterCards (name, description, personality, scenario, image,
|
222 |
+
post_history_instructions, first_mes, mes_example, creator_notes, system_prompt,
|
223 |
+
alternate_greetings, tags, creator, character_version, extensions)
|
224 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
225 |
+
"""
|
226 |
+
cursor.execute(insert_query, (
|
227 |
+
parsed_card['name'], parsed_card['description'], parsed_card['personality'],
|
228 |
+
parsed_card['scenario'], parsed_card['image'], parsed_card['post_history_instructions'],
|
229 |
+
parsed_card['first_mes'], parsed_card['mes_example'], parsed_card['creator_notes'],
|
230 |
+
parsed_card['system_prompt'], parsed_card['alternate_greetings'], parsed_card['tags'],
|
231 |
+
parsed_card['creator'], parsed_card['character_version'], parsed_card['extensions']
|
232 |
+
))
|
233 |
+
character_id = cursor.lastrowid
|
234 |
+
|
235 |
+
conn.commit()
|
236 |
+
return character_id
|
237 |
+
except sqlite3.IntegrityError as e:
|
238 |
+
logging.error(f"Error adding character card: {e}")
|
239 |
+
return None
|
240 |
+
except Exception as e:
|
241 |
+
logging.error(f"Unexpected error adding character card: {e}")
|
242 |
+
return None
|
243 |
+
finally:
|
244 |
+
conn.close()
|
245 |
+
|
246 |
+
# def add_character_card(card_data: Dict) -> Optional[int]:
|
247 |
+
# """Add or update a character card in the database.
|
248 |
+
#
|
249 |
+
# Returns the ID of the inserted character or None if failed.
|
250 |
+
# """
|
251 |
+
# conn = sqlite3.connect(chat_DB_PATH)
|
252 |
+
# cursor = conn.cursor()
|
253 |
+
# try:
|
254 |
+
# # Ensure all required fields are present
|
255 |
+
# required_fields = ['name', 'description', 'personality', 'scenario', 'image', 'post_history_instructions', 'first_message']
|
256 |
+
# for field in required_fields:
|
257 |
+
# if field not in card_data:
|
258 |
+
# card_data[field] = '' # Assign empty string if field is missing
|
259 |
+
#
|
260 |
+
# # Check if character already exists
|
261 |
+
# cursor.execute("SELECT id FROM CharacterCards WHERE name = ?", (card_data['name'],))
|
262 |
+
# row = cursor.fetchone()
|
263 |
+
#
|
264 |
+
# if row:
|
265 |
+
# # Update existing character
|
266 |
+
# character_id = row[0]
|
267 |
+
# cursor.execute("""
|
268 |
+
# UPDATE CharacterCards
|
269 |
+
# SET description = ?, personality = ?, scenario = ?, image = ?, post_history_instructions = ?, first_message = ?
|
270 |
+
# WHERE id = ?
|
271 |
+
# """, (
|
272 |
+
# card_data['description'],
|
273 |
+
# card_data['personality'],
|
274 |
+
# card_data['scenario'],
|
275 |
+
# card_data['image'],
|
276 |
+
# card_data['post_history_instructions'],
|
277 |
+
# card_data['first_message'],
|
278 |
+
# character_id
|
279 |
+
# ))
|
280 |
+
# else:
|
281 |
+
# # Insert new character
|
282 |
+
# cursor.execute("""
|
283 |
+
# INSERT INTO CharacterCards (name, description, personality, scenario, image, post_history_instructions, first_message)
|
284 |
+
# VALUES (?, ?, ?, ?, ?, ?, ?)
|
285 |
+
# """, (
|
286 |
+
# card_data['name'],
|
287 |
+
# card_data['description'],
|
288 |
+
# card_data['personality'],
|
289 |
+
# card_data['scenario'],
|
290 |
+
# card_data['image'],
|
291 |
+
# card_data['post_history_instructions'],
|
292 |
+
# card_data['first_message']
|
293 |
+
# ))
|
294 |
+
# character_id = cursor.lastrowid
|
295 |
+
#
|
296 |
+
# conn.commit()
|
297 |
+
# return cursor.lastrowid
|
298 |
+
# except sqlite3.IntegrityError as e:
|
299 |
+
# logging.error(f"Error adding character card: {e}")
|
300 |
+
# return None
|
301 |
+
# except Exception as e:
|
302 |
+
# logging.error(f"Unexpected error adding character card: {e}")
|
303 |
+
# return None
|
304 |
+
# finally:
|
305 |
+
# conn.close()
|
306 |
+
|
307 |
+
|
308 |
+
def get_character_cards() -> List[Dict]:
|
309 |
+
"""Retrieve all character cards from the database."""
|
310 |
+
logging.debug(f"Fetching characters from DB: {chat_DB_PATH}")
|
311 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
312 |
+
cursor = conn.cursor()
|
313 |
+
cursor.execute("SELECT * FROM CharacterCards")
|
314 |
+
rows = cursor.fetchall()
|
315 |
+
columns = [description[0] for description in cursor.description]
|
316 |
+
conn.close()
|
317 |
+
characters = [dict(zip(columns, row)) for row in rows]
|
318 |
+
#logging.debug(f"Characters fetched from DB: {characters}")
|
319 |
+
return characters
|
320 |
+
|
321 |
+
|
322 |
+
def get_character_card_by_id(character_id: Union[int, Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
323 |
+
"""
|
324 |
+
Retrieve a single character card by its ID.
|
325 |
+
|
326 |
+
Args:
|
327 |
+
character_id: Can be either an integer ID or a dictionary containing character data.
|
328 |
+
|
329 |
+
Returns:
|
330 |
+
A dictionary containing the character card data, or None if not found.
|
331 |
+
"""
|
332 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
333 |
+
cursor = conn.cursor()
|
334 |
+
try:
|
335 |
+
if isinstance(character_id, dict):
|
336 |
+
# If a dictionary is passed, assume it's already a character card
|
337 |
+
return character_id
|
338 |
+
elif isinstance(character_id, int):
|
339 |
+
# If an integer is passed, fetch the character from the database
|
340 |
+
cursor.execute("SELECT * FROM CharacterCards WHERE id = ?", (character_id,))
|
341 |
+
row = cursor.fetchone()
|
342 |
+
if row:
|
343 |
+
columns = [description[0] for description in cursor.description]
|
344 |
+
return dict(zip(columns, row))
|
345 |
+
else:
|
346 |
+
logging.warning(f"Invalid type for character_id: {type(character_id)}")
|
347 |
+
return None
|
348 |
+
except Exception as e:
|
349 |
+
logging.error(f"Error in get_character_card_by_id: {e}")
|
350 |
+
return None
|
351 |
+
finally:
|
352 |
+
conn.close()
|
353 |
+
|
354 |
+
|
355 |
+
def update_character_card(character_id: int, card_data: Dict) -> bool:
|
356 |
+
"""Update an existing character card."""
|
357 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
358 |
+
cursor = conn.cursor()
|
359 |
+
try:
|
360 |
+
cursor.execute("""
|
361 |
+
UPDATE CharacterCards
|
362 |
+
SET name = ?, description = ?, personality = ?, scenario = ?, image = ?, post_history_instructions = ?, first_message = ?
|
363 |
+
WHERE id = ?
|
364 |
+
""", (
|
365 |
+
card_data.get('name'),
|
366 |
+
card_data.get('description'),
|
367 |
+
card_data.get('personality'),
|
368 |
+
card_data.get('scenario'),
|
369 |
+
card_data.get('image'),
|
370 |
+
card_data.get('post_history_instructions', ''),
|
371 |
+
card_data.get('first_message', "Hello! I'm ready to chat."),
|
372 |
+
character_id
|
373 |
+
))
|
374 |
+
conn.commit()
|
375 |
+
return cursor.rowcount > 0
|
376 |
+
except sqlite3.IntegrityError as e:
|
377 |
+
logging.error(f"Error updating character card: {e}")
|
378 |
+
return False
|
379 |
+
finally:
|
380 |
+
conn.close()
|
381 |
+
|
382 |
+
|
383 |
+
def delete_character_card(character_id: int) -> bool:
|
384 |
+
"""Delete a character card and its associated chats."""
|
385 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
386 |
+
cursor = conn.cursor()
|
387 |
+
try:
|
388 |
+
# Delete associated chats first due to foreign key constraint
|
389 |
+
cursor.execute("DELETE FROM CharacterChats WHERE character_id = ?", (character_id,))
|
390 |
+
cursor.execute("DELETE FROM CharacterCards WHERE id = ?", (character_id,))
|
391 |
+
conn.commit()
|
392 |
+
return cursor.rowcount > 0
|
393 |
+
except sqlite3.Error as e:
|
394 |
+
logging.error(f"Error deleting character card: {e}")
|
395 |
+
return False
|
396 |
+
finally:
|
397 |
+
conn.close()
|
398 |
+
|
399 |
+
|
400 |
+
def add_character_chat(character_id: int, conversation_name: str, chat_history: List[Tuple[str, str]], keywords: Optional[List[str]] = None, is_snapshot: bool = False) -> Optional[int]:
|
401 |
+
"""
|
402 |
+
Add a new chat history for a character, optionally associating keywords.
|
403 |
+
|
404 |
+
Args:
|
405 |
+
character_id (int): The ID of the character.
|
406 |
+
conversation_name (str): Name of the conversation.
|
407 |
+
chat_history (List[Tuple[str, str]]): List of (user, bot) message tuples.
|
408 |
+
keywords (Optional[List[str]]): List of keywords to associate with this chat.
|
409 |
+
is_snapshot (bool, optional): Whether this chat is a snapshot.
|
410 |
+
|
411 |
+
Returns:
|
412 |
+
Optional[int]: The ID of the inserted chat or None if failed.
|
413 |
+
"""
|
414 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
415 |
+
cursor = conn.cursor()
|
416 |
+
try:
|
417 |
+
chat_history_json = json.dumps(chat_history)
|
418 |
+
cursor.execute("""
|
419 |
+
INSERT INTO CharacterChats (character_id, conversation_name, chat_history, is_snapshot)
|
420 |
+
VALUES (?, ?, ?, ?)
|
421 |
+
""", (
|
422 |
+
character_id,
|
423 |
+
conversation_name,
|
424 |
+
chat_history_json,
|
425 |
+
is_snapshot
|
426 |
+
))
|
427 |
+
chat_id = cursor.lastrowid
|
428 |
+
|
429 |
+
if keywords:
|
430 |
+
# Insert keywords into ChatKeywords table
|
431 |
+
keyword_records = [(chat_id, keyword.strip().lower()) for keyword in keywords]
|
432 |
+
cursor.executemany("""
|
433 |
+
INSERT INTO ChatKeywords (chat_id, keyword)
|
434 |
+
VALUES (?, ?)
|
435 |
+
""", keyword_records)
|
436 |
+
|
437 |
+
conn.commit()
|
438 |
+
return chat_id
|
439 |
+
except sqlite3.Error as e:
|
440 |
+
logging.error(f"Error adding character chat: {e}")
|
441 |
+
return None
|
442 |
+
finally:
|
443 |
+
conn.close()
|
444 |
+
|
445 |
+
|
446 |
+
def get_character_chats(character_id: Optional[int] = None) -> List[Dict]:
|
447 |
+
"""Retrieve all chats, or chats for a specific character if character_id is provided."""
|
448 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
449 |
+
cursor = conn.cursor()
|
450 |
+
if character_id is not None:
|
451 |
+
cursor.execute("SELECT * FROM CharacterChats WHERE character_id = ?", (character_id,))
|
452 |
+
else:
|
453 |
+
cursor.execute("SELECT * FROM CharacterChats")
|
454 |
+
rows = cursor.fetchall()
|
455 |
+
columns = [description[0] for description in cursor.description]
|
456 |
+
conn.close()
|
457 |
+
return [dict(zip(columns, row)) for row in rows]
|
458 |
+
|
459 |
+
|
460 |
+
def get_character_chat_by_id(chat_id: int) -> Optional[Dict]:
|
461 |
+
"""Retrieve a single chat by its ID."""
|
462 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
463 |
+
cursor = conn.cursor()
|
464 |
+
cursor.execute("SELECT * FROM CharacterChats WHERE id = ?", (chat_id,))
|
465 |
+
row = cursor.fetchone()
|
466 |
+
conn.close()
|
467 |
+
if row:
|
468 |
+
columns = [description[0] for description in cursor.description]
|
469 |
+
chat = dict(zip(columns, row))
|
470 |
+
chat['chat_history'] = json.loads(chat['chat_history'])
|
471 |
+
return chat
|
472 |
+
return None
|
473 |
+
|
474 |
+
|
475 |
+
def search_character_chats(query: str, character_id: Optional[int] = None) -> Tuple[List[Dict], str]:
|
476 |
+
"""
|
477 |
+
Search for character chats using FTS5, optionally filtered by character_id.
|
478 |
+
|
479 |
+
Args:
|
480 |
+
query (str): The search query.
|
481 |
+
character_id (Optional[int]): The ID of the character to filter chats by.
|
482 |
+
|
483 |
+
Returns:
|
484 |
+
Tuple[List[Dict], str]: A list of matching chats and a status message.
|
485 |
+
"""
|
486 |
+
if not query.strip():
|
487 |
+
return [], "Please enter a search query."
|
488 |
+
|
489 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
490 |
+
cursor = conn.cursor()
|
491 |
+
try:
|
492 |
+
if character_id is not None:
|
493 |
+
# Search with character_id filter
|
494 |
+
cursor.execute("""
|
495 |
+
SELECT CharacterChats.id, CharacterChats.conversation_name, CharacterChats.chat_history
|
496 |
+
FROM CharacterChats_fts
|
497 |
+
JOIN CharacterChats ON CharacterChats_fts.rowid = CharacterChats.id
|
498 |
+
WHERE CharacterChats_fts MATCH ? AND CharacterChats.character_id = ?
|
499 |
+
ORDER BY rank
|
500 |
+
""", (query, character_id))
|
501 |
+
else:
|
502 |
+
# Search without character_id filter
|
503 |
+
cursor.execute("""
|
504 |
+
SELECT CharacterChats.id, CharacterChats.conversation_name, CharacterChats.chat_history
|
505 |
+
FROM CharacterChats_fts
|
506 |
+
JOIN CharacterChats ON CharacterChats_fts.rowid = CharacterChats.id
|
507 |
+
WHERE CharacterChats_fts MATCH ?
|
508 |
+
ORDER BY rank
|
509 |
+
""", (query,))
|
510 |
+
|
511 |
+
rows = cursor.fetchall()
|
512 |
+
columns = [description[0] for description in cursor.description]
|
513 |
+
results = [dict(zip(columns, row)) for row in rows]
|
514 |
+
|
515 |
+
if character_id is not None:
|
516 |
+
status_message = f"Found {len(results)} chat(s) matching '{query}' for the selected character."
|
517 |
+
else:
|
518 |
+
status_message = f"Found {len(results)} chat(s) matching '{query}' across all characters."
|
519 |
+
|
520 |
+
return results, status_message
|
521 |
+
except Exception as e:
|
522 |
+
logging.error(f"Error searching chats with FTS5: {e}")
|
523 |
+
return [], f"Error occurred during search: {e}"
|
524 |
+
finally:
|
525 |
+
conn.close()
|
526 |
+
|
527 |
+
def update_character_chat(chat_id: int, chat_history: List[Tuple[str, str]]) -> bool:
|
528 |
+
"""Update an existing chat history."""
|
529 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
530 |
+
cursor = conn.cursor()
|
531 |
+
try:
|
532 |
+
chat_history_json = json.dumps(chat_history)
|
533 |
+
cursor.execute("""
|
534 |
+
UPDATE CharacterChats
|
535 |
+
SET chat_history = ?
|
536 |
+
WHERE id = ?
|
537 |
+
""", (
|
538 |
+
chat_history_json,
|
539 |
+
chat_id
|
540 |
+
))
|
541 |
+
conn.commit()
|
542 |
+
return cursor.rowcount > 0
|
543 |
+
except sqlite3.Error as e:
|
544 |
+
logging.error(f"Error updating character chat: {e}")
|
545 |
+
return False
|
546 |
+
finally:
|
547 |
+
conn.close()
|
548 |
+
|
549 |
+
|
550 |
+
def delete_character_chat(chat_id: int) -> bool:
|
551 |
+
"""Delete a specific chat."""
|
552 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
553 |
+
cursor = conn.cursor()
|
554 |
+
try:
|
555 |
+
cursor.execute("DELETE FROM CharacterChats WHERE id = ?", (chat_id,))
|
556 |
+
conn.commit()
|
557 |
+
return cursor.rowcount > 0
|
558 |
+
except sqlite3.Error as e:
|
559 |
+
logging.error(f"Error deleting character chat: {e}")
|
560 |
+
return False
|
561 |
+
finally:
|
562 |
+
conn.close()
|
563 |
+
|
564 |
+
def fetch_keywords_for_chats(keywords: List[str]) -> List[int]:
|
565 |
+
"""
|
566 |
+
Fetch chat IDs associated with any of the specified keywords.
|
567 |
+
|
568 |
+
Args:
|
569 |
+
keywords (List[str]): List of keywords to search for.
|
570 |
+
|
571 |
+
Returns:
|
572 |
+
List[int]: List of chat IDs associated with the keywords.
|
573 |
+
"""
|
574 |
+
if not keywords:
|
575 |
+
return []
|
576 |
+
|
577 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
578 |
+
cursor = conn.cursor()
|
579 |
+
try:
|
580 |
+
# Construct the WHERE clause to search for each keyword
|
581 |
+
keyword_clauses = " OR ".join(["keyword = ?"] * len(keywords))
|
582 |
+
sql_query = f"SELECT DISTINCT chat_id FROM ChatKeywords WHERE {keyword_clauses}"
|
583 |
+
cursor.execute(sql_query, keywords)
|
584 |
+
rows = cursor.fetchall()
|
585 |
+
chat_ids = [row[0] for row in rows]
|
586 |
+
return chat_ids
|
587 |
+
except Exception as e:
|
588 |
+
logging.error(f"Error in fetch_keywords_for_chats: {e}")
|
589 |
+
return []
|
590 |
+
finally:
|
591 |
+
conn.close()
|
592 |
+
|
593 |
+
def save_chat_history_to_character_db(character_id: int, conversation_name: str, chat_history: List[Tuple[str, str]]) -> Optional[int]:
|
594 |
+
"""Save chat history to the CharacterChats table.
|
595 |
+
|
596 |
+
Returns the ID of the inserted chat or None if failed.
|
597 |
+
"""
|
598 |
+
return add_character_chat(character_id, conversation_name, chat_history)
|
599 |
+
|
600 |
+
def migrate_chat_to_media_db():
|
601 |
+
pass
|
602 |
+
|
603 |
+
|
604 |
+
def search_db(query: str, fields: List[str], where_clause: str = "", page: int = 1, results_per_page: int = 5) -> List[Dict[str, Any]]:
|
605 |
+
"""
|
606 |
+
Perform a full-text search on specified fields with optional filtering and pagination.
|
607 |
+
|
608 |
+
Args:
|
609 |
+
query (str): The search query.
|
610 |
+
fields (List[str]): List of fields to search in.
|
611 |
+
where_clause (str, optional): Additional SQL WHERE clause to filter results.
|
612 |
+
page (int, optional): Page number for pagination.
|
613 |
+
results_per_page (int, optional): Number of results per page.
|
614 |
+
|
615 |
+
Returns:
|
616 |
+
List[Dict[str, Any]]: List of matching chat records with content and metadata.
|
617 |
+
"""
|
618 |
+
if not query.strip():
|
619 |
+
return []
|
620 |
+
|
621 |
+
conn = sqlite3.connect(chat_DB_PATH)
|
622 |
+
cursor = conn.cursor()
|
623 |
+
try:
|
624 |
+
# Construct the MATCH query for FTS5
|
625 |
+
match_query = " AND ".join(fields) + f" MATCH ?"
|
626 |
+
# Adjust the query with the fields
|
627 |
+
fts_query = f"""
|
628 |
+
SELECT CharacterChats.id, CharacterChats.conversation_name, CharacterChats.chat_history
|
629 |
+
FROM CharacterChats_fts
|
630 |
+
JOIN CharacterChats ON CharacterChats_fts.rowid = CharacterChats.id
|
631 |
+
WHERE {match_query}
|
632 |
+
"""
|
633 |
+
if where_clause:
|
634 |
+
fts_query += f" AND ({where_clause})"
|
635 |
+
fts_query += " ORDER BY rank LIMIT ? OFFSET ?"
|
636 |
+
offset = (page - 1) * results_per_page
|
637 |
+
cursor.execute(fts_query, (query, results_per_page, offset))
|
638 |
+
rows = cursor.fetchall()
|
639 |
+
columns = [description[0] for description in cursor.description]
|
640 |
+
results = [dict(zip(columns, row)) for row in rows]
|
641 |
+
return results
|
642 |
+
except Exception as e:
|
643 |
+
logging.error(f"Error in search_db: {e}")
|
644 |
+
return []
|
645 |
+
finally:
|
646 |
+
conn.close()
|
647 |
+
|
648 |
+
|
649 |
+
def perform_full_text_search_chat(query: str, relevant_chat_ids: List[int], page: int = 1, results_per_page: int = 5) -> \
|
650 |
+
List[Dict[str, Any]]:
|
651 |
+
"""
|
652 |
+
Perform a full-text search within the specified chat IDs using FTS5.
|
653 |
+
|
654 |
+
Args:
|
655 |
+
query (str): The user's query.
|
656 |
+
relevant_chat_ids (List[int]): List of chat IDs to search within.
|
657 |
+
page (int): Pagination page number.
|
658 |
+
results_per_page (int): Number of results per page.
|
659 |
+
|
660 |
+
Returns:
|
661 |
+
List[Dict[str, Any]]: List of search results with content and metadata.
|
662 |
+
"""
|
663 |
+
try:
|
664 |
+
# Construct a WHERE clause to limit the search to relevant chat IDs
|
665 |
+
where_clause = " OR ".join([f"media_id = {chat_id}" for chat_id in relevant_chat_ids])
|
666 |
+
if not where_clause:
|
667 |
+
where_clause = "1" # No restriction if no chat IDs
|
668 |
+
|
669 |
+
# Perform full-text search using FTS5
|
670 |
+
fts_results = search_db(query, ["content"], where_clause, page=page, results_per_page=results_per_page)
|
671 |
+
|
672 |
+
filtered_fts_results = [
|
673 |
+
{
|
674 |
+
"content": result['content'],
|
675 |
+
"metadata": {"media_id": result['id']}
|
676 |
+
}
|
677 |
+
for result in fts_results
|
678 |
+
if result['id'] in relevant_chat_ids
|
679 |
+
]
|
680 |
+
return filtered_fts_results
|
681 |
+
except Exception as e:
|
682 |
+
logging.error(f"Error in perform_full_text_search_chat: {str(e)}")
|
683 |
+
return []
|
684 |
+
|
685 |
+
|
686 |
+
def fetch_all_chats() -> List[Dict[str, Any]]:
|
687 |
+
"""
|
688 |
+
Fetch all chat messages from the database.
|
689 |
+
|
690 |
+
Returns:
|
691 |
+
List[Dict[str, Any]]: List of chat messages with relevant metadata.
|
692 |
+
"""
|
693 |
+
try:
|
694 |
+
chats = get_character_chats() # Modify this function to retrieve all chats
|
695 |
+
return chats
|
696 |
+
except Exception as e:
|
697 |
+
logging.error(f"Error fetching all chats: {str(e)}")
|
698 |
+
return []
|
699 |
+
|
700 |
+
#
|
701 |
+
# End of Character_Chat_DB.py
|
702 |
+
#######################################################################################################################
|