Spaces:
Build error
Build error
File size: 41,407 Bytes
7333afe 292eb86 2329f67 61cecf9 03a5156 61cecf9 2329f67 61cecf9 2329f67 8a72544 7333afe 64b3386 10c877a 64b3386 03a5156 50e05f5 4e1e6ae 03a5156 f293d04 f9851ce 292eb86 03a5156 292eb86 9f3cc4f 03a5156 f9851ce 03a5156 041398a 03a5156 50ec00d b877222 ce57518 50ec00d b877222 50ec00d b877222 50ec00d ce57518 50ec00d ce57518 50ec00d ce57518 50ec00d b877222 50ec00d b877222 50ec00d b877222 50ec00d b877222 50ec00d b877222 50ec00d b877222 03a5156 50ec00d b877222 292eb86 03a5156 292eb86 03a5156 44d3a72 10c877a f4fbfef 292eb86 f4fbfef 292eb86 f4fbfef 292eb86 f4fbfef f9851ce 292eb86 f4fbfef 292eb86 f4fbfef 292eb86 f4fbfef 292eb86 f4fbfef 35cf712 292eb86 44d3a72 292eb86 35cf712 292eb86 35cf712 292eb86 35cf712 f9851ce 292eb86 35cf712 292eb86 6ab15d2 292eb86 6ab15d2 292eb86 6ab15d2 292eb86 6ab15d2 f61c1a4 b5ab699 292eb86 b5ab699 292eb86 f61c1a4 f777bc6 292eb86 b5ab699 f61c1a4 292eb86 f61c1a4 292eb86 f61c1a4 b5ab699 292eb86 f61c1a4 b5ab699 f61c1a4 292eb86 10c877a f61c1a4 292eb86 10c877a 292eb86 b5ab699 10c877a 292eb86 10c877a 292eb86 10c877a 292eb86 10c877a 292eb86 b5ab699 10c877a b5ab699 10c877a 292eb86 10c877a 292eb86 10c877a 292eb86 b5ab699 10c877a 292eb86 f61c1a4 b5ab699 292eb86 f61c1a4 b5ab699 f61c1a4 292eb86 f61c1a4 292eb86 b5ab699 292eb86 b5ab699 292eb86 b5ab699 292eb86 f61c1a4 292eb86 b5ab699 292eb86 f61c1a4 b5ab699 f777bc6 b5ab699 292eb86 2aceabb 31e950a 2aceabb 31e950a 4a62598 b5ab699 1118663 292eb86 1957e91 292eb86 1957e91 292eb86 1957e91 8ea261f 292eb86 1957e91 292eb86 1957e91 292eb86 1957e91 292eb86 1957e91 292eb86 1957e91 292eb86 1957e91 8ea261f 2bd9b5d 7333afe 292eb86 7333afe 09d4055 7333afe 10c877a 028c9cb 7333afe 2bd9b5d 10c877a 2bd9b5d 8c249d6 4571b33 65fc39c fccb2e5 311a114 fccb2e5 65fc39c fccb2e5 292eb86 8c249d6 939f85b cbeca91 2329f67 cbeca91 d39a1aa 914b163 2329f67 8c249d6 2329f67 7333afe 4571b33 7333afe 292eb86 03a5156 7333afe 292eb86 7333afe 59815da 7333afe 59815da 7333afe 292eb86 03a5156 59815da 7333afe 292eb86 7333afe 59815da 7333afe 292eb86 | 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 311 312 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 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 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 464 465 466 467 468 469 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 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 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 | # utils/database.py
# Update the imports first
from langchain_community.chat_models import ChatOpenAI
from langchain_core.messages import (
HumanMessage,
AIMessage,
SystemMessage,
BaseMessage
)
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnablePassthrough
from langchain.chains import ConversationalRetrievalChain
from langchain.chat_models import ChatOpenAI
from langchain.agents import AgentExecutor, Tool, create_openai_tools_agent
from langchain.agents.format_scratchpad.tools import format_to_tool_messages
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
from langchain.vectorstores import FAISS
import os
import streamlit as st
import sqlite3
import traceback
import time
import io
import tempfile
from sqlite3 import Error
from threading import Lock
from typing import Dict, List, Optional, Any
from datetime import datetime
from threading import Lock
# Create a lock for database connection
conn_lock = Lock()
def create_connection(db_file):
"""
Create a database connection to the SQLite database.
Args:
db_file (str): Path to the SQLite database file.
Returns:
sqlite3.Connection: Database connection object or None if an error occurs.
"""
conn = None
try:
conn = sqlite3.connect(db_file, check_same_thread=False)
return conn
except Error as e:
st.error("Failed to connect to database. Please try again or contact support.")
return None
def create_connection(db_file: str) -> Optional[sqlite3.Connection]:
"""Create a database connection."""
try:
conn = sqlite3.connect(db_file, check_same_thread=False)
return conn
except sqlite3.Error as e:
st.error(f"Error connecting to database: {e}")
return None
# utils/database.py
# Add this version of create_tables (replacing the existing one)
# utils/database.py
def create_tables(conn: sqlite3.Connection) -> None:
"""Create all necessary tables in the database."""
try:
with conn_lock:
cursor = conn.cursor()
# Force create collections tables first
collections_tables = [
'''
CREATE TABLE IF NOT EXISTS collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''',
'''
CREATE TABLE IF NOT EXISTS document_collections (
document_id INTEGER,
collection_id INTEGER,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (document_id, collection_id),
FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE,
FOREIGN KEY (collection_id) REFERENCES collections (id) ON DELETE CASCADE
)
'''
]
# Execute collections tables creation separately
for table_sql in collections_tables:
try:
cursor.execute(table_sql)
conn.commit()
except sqlite3.Error as e:
st.error(f"Error creating collections table: {e}")
st.error(f"SQL that failed: {table_sql}")
raise
# Create other tables
other_tables = [
'''
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
content TEXT NOT NULL,
upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''',
'''
CREATE TABLE IF NOT EXISTS queries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
query TEXT NOT NULL,
response TEXT NOT NULL,
document_id INTEGER,
query_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE
)
''',
'''
CREATE TABLE IF NOT EXISTS annotations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
document_id INTEGER NOT NULL,
annotation TEXT NOT NULL,
page_number INTEGER,
annotation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE
)
'''
]
# Execute other tables creation
for table_sql in other_tables:
try:
cursor.execute(table_sql)
conn.commit()
except sqlite3.Error as e:
st.error(f"Error creating table: {e}")
st.error(f"SQL that failed: {table_sql}")
raise
# Create indices
indices = [
'CREATE INDEX IF NOT EXISTS idx_doc_name ON documents(name)',
'CREATE INDEX IF NOT EXISTS idx_collection_name ON collections(name)',
'CREATE INDEX IF NOT EXISTS idx_doc_collections ON document_collections(collection_id)'
]
# Execute indices creation
for index_sql in indices:
try:
cursor.execute(index_sql)
conn.commit()
except sqlite3.Error as e:
st.error(f"Error creating index: {e}")
st.error(f"SQL that failed: {index_sql}")
# Verify collections table was created
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='collections'")
if not cursor.fetchone():
st.error("Failed to create collections table despite no errors")
raise Exception("Collections table creation failed silently")
conn.commit()
except sqlite3.Error as e:
st.error(f"Error in create_tables: {e}")
raise
except Exception as e:
st.error(f"Unexpected error in create_tables: {e}")
raise
def force_recreate_collections_tables(conn: sqlite3.Connection) -> bool:
"""Force recreate collections tables if they're missing."""
try:
with conn_lock:
cursor = conn.cursor()
# Drop existing tables if they exist
cursor.execute("DROP TABLE IF EXISTS document_collections")
cursor.execute("DROP TABLE IF EXISTS collections")
# Create collections table
cursor.execute('''
CREATE TABLE collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create document_collections table
cursor.execute('''
CREATE TABLE document_collections (
document_id INTEGER,
collection_id INTEGER,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (document_id, collection_id),
FOREIGN KEY (document_id) REFERENCES documents (id) ON DELETE CASCADE,
FOREIGN KEY (collection_id) REFERENCES collections (id) ON DELETE CASCADE
)
''')
# Create indices
cursor.execute('CREATE INDEX IF NOT EXISTS idx_collection_name ON collections(name)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_doc_collections ON document_collections(collection_id)')
conn.commit()
return True
except sqlite3.Error as e:
st.error(f"Error recreating collections tables: {e}")
return False
def get_all_documents(conn: sqlite3.Connection) -> List[Dict]:
"""Get all documents with their metadata and collections."""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
SELECT
d.id,
d.name,
d.content,
d.upload_date,
GROUP_CONCAT(c.name) as collections
FROM documents d
LEFT JOIN document_collections dc ON d.id = dc.document_id
LEFT JOIN collections c ON dc.collection_id = c.id
GROUP BY d.id
ORDER BY d.upload_date DESC
''')
documents = []
for row in cursor.fetchall():
documents.append({
'id': row[0],
'name': row[1],
'content': row[2],
'upload_date': row[3],
'collections': row[4].split(',') if row[4] else []
})
return documents
except sqlite3.Error as e:
st.error(f"Error retrieving documents: {e}")
return []
def get_document_queries(conn: sqlite3.Connection, document_id: int) -> List[Dict]:
"""Get all queries associated with a document."""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
SELECT id, query, response, query_date
FROM queries
WHERE document_id = ?
ORDER BY query_date DESC
''', (document_id,))
queries = []
for row in cursor.fetchall():
queries.append({
'id': row[0],
'query': row[1],
'response': row[2],
'query_date': row[3]
})
return queries
except sqlite3.Error as e:
st.error(f"Error retrieving document queries: {e}")
return []
def add_query(conn: sqlite3.Connection, query: str, response: str, document_id: Optional[int] = None) -> bool:
"""Add a new query and its response."""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO queries (query, response, document_id)
VALUES (?, ?, ?)
''', (query, response, document_id))
conn.commit()
return True
except sqlite3.Error as e:
st.error(f"Error adding query: {e}")
return False
def add_annotation(conn: sqlite3.Connection, document_id: int, annotation: str, page_number: Optional[int] = None) -> bool:
"""Add an annotation to a document."""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO annotations (document_id, annotation, page_number)
VALUES (?, ?, ?)
''', (document_id, annotation, page_number))
conn.commit()
return True
except sqlite3.Error as e:
st.error(f"Error adding annotation: {e}")
return False
def create_tables(conn):
"""
Create necessary tables in the database.
Args:
conn (sqlite3.Connection): SQLite database connection.
"""
try:
sql_create_documents_table = '''
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
content TEXT NOT NULL,
upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
'''
sql_create_queries_table = '''
CREATE TABLE IF NOT EXISTS queries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
query TEXT NOT NULL,
response TEXT NOT NULL,
document_id INTEGER,
query_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (document_id) REFERENCES documents (id)
);
'''
sql_create_annotations_table = '''
CREATE TABLE IF NOT EXISTS annotations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
document_id INTEGER NOT NULL,
annotation TEXT NOT NULL,
page_number INTEGER,
annotation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (document_id) REFERENCES documents (id)
);
'''
conn.execute(sql_create_documents_table)
conn.execute(sql_create_queries_table)
conn.execute(sql_create_annotations_table)
except Error as e:
st.error(f"Error: {e}")
def get_documents(conn):
"""
Retrieve all documents from the database.
Args:
conn (sqlite3.Connection): SQLite database connection.
Returns:
tuple: (list of document contents, list of document names).
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute("SELECT content, name FROM documents")
results = cursor.fetchall()
if not results:
return [], []
# Separate contents and names
document_contents = [row[0] for row in results]
document_names = [row[1] for row in results]
return document_contents, document_names
except Error as e:
st.error(f"Error retrieving documents: {e}")
return [], []
def insert_document(conn, name, content):
"""
Insert a new document into the database.
Args:
conn (sqlite3.Connection): SQLite database connection.
name (str): Name of the document.
content (str): Content of the document.
Returns:
int: ID of the inserted document, or None if insertion failed.
"""
try:
with conn_lock:
cursor = conn.cursor()
sql = '''INSERT INTO documents (name, content)
VALUES (?, ?)'''
cursor.execute(sql, (name, content))
conn.commit()
return cursor.lastrowid
except Error as e:
st.error(f"Error inserting document: {e}")
return None
def verify_vector_store(vector_store):
"""
Verify that the vector store has documents loaded.
Args:
vector_store (FAISS): FAISS vector store instance.
Returns:
bool: True if vector store is properly initialized with documents.
"""
try:
# Try to perform a simple similarity search
test_results = vector_store.similarity_search("test", k=1)
return len(test_results) > 0
except Exception as e:
st.error(f"Vector store verification failed: {e}")
return False
def handle_document_upload(uploaded_files, **kwargs):
"""
Handle document upload with progress tracking and collection support.
Args:
uploaded_files (list): List of uploaded files
**kwargs: Additional arguments including:
- collection_id (int, optional): ID of the collection to add documents to
"""
try:
# Initialize session state variables if they don't exist
if 'qa_system' not in st.session_state:
st.session_state.qa_system = None
if 'vector_store' not in st.session_state:
st.session_state.vector_store = None
# Create progress containers
progress_container = st.empty()
status_container = st.empty()
details_container = st.empty()
# Initialize progress bar
progress_bar = progress_container.progress(0)
status_container.info("π Initializing document processing...")
# Reset existing states
st.session_state.vector_store = None
st.session_state.qa_system = None
# Initialize embeddings (10% progress)
status_container.info("π Initializing embeddings model...")
embeddings = get_embeddings_model()
if not embeddings:
status_container.error("β Failed to initialize embeddings model")
return False
progress_bar.progress(10)
# Process documents
all_chunks = []
documents = []
document_names = []
progress_per_file = 70 / len(uploaded_files)
current_progress = 10
collection_id = kwargs.get('collection_id')
for idx, uploaded_file in enumerate(uploaded_files):
file_name = uploaded_file.name
status_container.info(f"π Processing document {idx + 1}/{len(uploaded_files)}: {file_name}")
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_file.flush()
# Process document with chunking
chunks, content = process_document(tmp_file.name)
# Store in database
doc_id = insert_document(st.session_state.db_conn, file_name, content)
if not doc_id:
status_container.error(f"β Failed to store document: {file_name}")
continue
# Add to collection if specified
if collection_id:
if not add_document_to_collection(st.session_state.db_conn, doc_id, collection_id):
status_container.warning(f"β οΈ Failed to add document to collection: {file_name}")
# Add chunks with metadata
for chunk in chunks:
chunk.metadata.update({
"source": file_name,
"document_id": doc_id,
"collection_id": collection_id if collection_id else None
})
all_chunks.extend(chunks)
documents.append(content)
document_names.append(file_name)
current_progress += progress_per_file
progress_bar.progress(int(current_progress))
# Initialize vector store with chunks
status_container.info("π Initializing vector store...")
vector_store = FAISS.from_documents(
all_chunks,
embeddings
)
# Verify vector store
status_container.info("π Verifying document indexing...")
details_container.text("β¨ Performing final checks...")
if not verify_vector_store(vector_store):
status_container.error("β Vector store verification failed")
return False
# Initialize QA system (90-100% progress)
status_container.info("π Setting up QA system...")
qa_system = initialize_qa_system(vector_store)
if not qa_system:
status_container.error("β Failed to initialize QA system")
return False
# Store in session state
if collection_id:
if 'vector_stores' not in st.session_state:
st.session_state.vector_stores = {}
st.session_state.vector_stores[collection_id] = vector_store
else:
st.session_state.vector_store = vector_store
st.session_state.qa_system = qa_system
# Complete!
progress_bar.progress(100)
status_container.success("β
Documents processed successfully!")
details_container.markdown(
f"""
π **Ready to chat!**
- Documents processed: {len(documents)}
- Total content size: {sum(len(doc) for doc in documents) / 1024:.2f} KB
- {"Added to collection" if collection_id else "Processed as standalone documents"}
You can now start asking questions about your documents!
"""
)
# Add notification
st.balloons()
# Clean up progress display after 3 seconds
time.sleep(3)
progress_container.empty()
status_container.empty()
details_container.empty()
return True
except Exception as e:
st.error(f"β Error processing documents: {str(e)}")
if status_container:
status_container.error(traceback.format_exc())
# Reset states on error
st.session_state.vector_store = None
st.session_state.qa_system = None
st.session_state.chat_ready = False
return False
# Add these to your database.py file
def remove_from_collection(conn: sqlite3.Connection, document_id: int, collection_id: int) -> bool:
"""
Remove a document from a collection.
Args:
conn (sqlite3.Connection): Database connection
document_id (int): ID of the document to remove
collection_id (int): ID of the collection
Returns:
bool: True if successful
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
DELETE FROM document_collections
WHERE document_id = ? AND collection_id = ?
''', (document_id, collection_id))
conn.commit()
return True
except sqlite3.Error as e:
st.error(f"Error removing document from collection: {e}")
return False
def update_collection(conn: sqlite3.Connection, collection_id: int, name: Optional[str] = None,
description: Optional[str] = None) -> bool:
"""
Update collection details.
Args:
conn (sqlite3.Connection): Database connection
collection_id (int): ID of the collection to update
name (Optional[str]): New name for the collection
description (Optional[str]): New description for the collection
Returns:
bool: True if successful
"""
try:
with conn_lock:
updates = []
params = []
if name is not None:
updates.append("name = ?")
params.append(name)
if description is not None:
updates.append("description = ?")
params.append(description)
if not updates:
return True # Nothing to update
params.append(collection_id)
cursor = conn.cursor()
cursor.execute(f'''
UPDATE collections
SET {", ".join(updates)}
WHERE id = ?
''', params)
conn.commit()
return True
except sqlite3.Error as e:
st.error(f"Error updating collection: {e}")
return False
def search_documents(conn: sqlite3.Connection, query: str,
collection_id: Optional[int] = None,
filters: Optional[Dict] = None) -> List[Dict]:
"""
Search documents using fuzzy matching and filters.
Args:
conn (sqlite3.Connection): Database connection
query (str): Search query
collection_id (Optional[int]): Filter by collection
filters (Optional[Dict]): Additional filters
Returns:
List[Dict]: List of matching documents
"""
try:
with conn_lock:
cursor = conn.cursor()
# Base query
sql = """
SELECT DISTINCT
d.id,
d.name,
d.content,
d.upload_date,
GROUP_CONCAT(c.name) as collections
FROM documents d
LEFT JOIN document_collections dc ON d.id = dc.document_id
LEFT JOIN collections c ON dc.collection_id = c.id
"""
params = []
where_clauses = []
# Add collection filter if specified
if collection_id:
where_clauses.append("dc.collection_id = ?")
params.append(collection_id)
# Add date filters if specified
if filters and 'date_range' in filters:
start_date, end_date = filters['date_range']
where_clauses.append("d.upload_date BETWEEN ? AND ?")
params.extend([start_date, end_date])
# Add text search
if query:
where_clauses.append("(d.name LIKE ? OR d.content LIKE ?)")
search_term = f"%{query}%"
params.extend([search_term, search_term])
# Combine WHERE clauses
if where_clauses:
sql += " WHERE " + " AND ".join(where_clauses)
sql += " GROUP BY d.id ORDER BY d.upload_date DESC"
# Execute query
cursor.execute(sql, params)
documents = []
for row in cursor.fetchall():
documents.append({
'id': row[0],
'name': row[1],
'content': row[2],
'upload_date': row[3],
'collections': row[4].split(',') if row[4] else []
})
return documents
except sqlite3.Error as e:
st.error(f"Error searching documents: {e}")
return []
def get_all_documents(conn: sqlite3.Connection) -> List[Dict]:
"""
Get all documents with their metadata and collection info.
Args:
conn (sqlite3.Connection): Database connection
Returns:
List[Dict]: List of documents with their metadata
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
SELECT
d.id,
d.name,
d.content,
d.upload_date,
GROUP_CONCAT(c.name) as collections
FROM documents d
LEFT JOIN document_collections dc ON d.id = dc.document_id
LEFT JOIN collections c ON dc.collection_id = c.id
GROUP BY d.id
ORDER BY d.upload_date DESC
''')
documents = []
for row in cursor.fetchall():
documents.append({
'id': row[0],
'name': row[1],
'content': row[2],
'upload_date': row[3],
'collections': row[4].split(',') if row[4] else []
})
return documents
except sqlite3.Error as e:
st.error(f"Error retrieving documents: {e}")
return []
def get_document_by_id(conn: sqlite3.Connection, document_id: int) -> Optional[Dict]:
"""
Get a single document by its ID.
Args:
conn (sqlite3.Connection): Database connection
document_id (int): ID of the document to retrieve
Returns:
Optional[Dict]: Document data if found, None otherwise
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
SELECT
d.id,
d.name,
d.content,
d.upload_date,
GROUP_CONCAT(c.name) as collections
FROM documents d
LEFT JOIN document_collections dc ON d.id = dc.document_id
LEFT JOIN collections c ON dc.collection_id = c.id
WHERE d.id = ?
GROUP BY d.id
''', (document_id,))
row = cursor.fetchone()
if row:
return {
'id': row[0],
'name': row[1],
'content': row[2],
'upload_date': row[3],
'collections': row[4].split(',') if row[4] else []
}
return None
except sqlite3.Error as e:
st.error(f"Error retrieving document: {e}")
return None
def get_recent_documents(conn: sqlite3.Connection, limit: int = 5) -> List[Dict]:
"""
Get most recently uploaded documents.
Args:
conn (sqlite3.Connection): Database connection
limit (int): Maximum number of documents to return
Returns:
List[Dict]: List of recent documents
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
SELECT
d.id,
d.name,
d.content,
d.upload_date,
GROUP_CONCAT(c.name) as collections
FROM documents d
LEFT JOIN document_collections dc ON d.id = dc.document_id
LEFT JOIN collections c ON dc.collection_id = c.id
GROUP BY d.id
ORDER BY d.upload_date DESC
LIMIT ?
''', (limit,))
documents = []
for row in cursor.fetchall():
documents.append({
'id': row[0],
'name': row[1],
'content': row[2],
'upload_date': row[3],
'collections': row[4].split(',') if row[4] else []
})
return documents
except sqlite3.Error as e:
st.error(f"Error retrieving recent documents: {e}")
return []
def get_collections(conn: sqlite3.Connection) -> List[Dict]:
"""
Get all collections with their document counts.
Args:
conn (sqlite3.Connection): Database connection
Returns:
List[Dict]: List of collections with metadata
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
SELECT
c.id,
c.name,
c.description,
c.created_at,
COUNT(DISTINCT dc.document_id) as doc_count
FROM collections c
LEFT JOIN document_collections dc ON c.id = dc.collection_id
GROUP BY c.id
ORDER BY c.name
''')
collections = []
for row in cursor.fetchall():
collections.append({
'id': row[0],
'name': row[1],
'description': row[2],
'created_at': row[3],
'doc_count': row[4]
})
return collections
except sqlite3.Error as e:
st.error(f"Error retrieving collections: {e}")
return []
def get_collection_documents(conn: sqlite3.Connection, collection_id: int) -> List[Dict]:
"""
Get all documents in a specific collection.
Args:
conn (sqlite3.Connection): Database connection
collection_id (int): ID of the collection
Returns:
List[Dict]: List of documents in the collection
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
SELECT
d.id,
d.name,
d.content,
d.upload_date
FROM documents d
JOIN document_collections dc ON d.id = dc.document_id
WHERE dc.collection_id = ?
ORDER BY d.upload_date DESC
''', (collection_id,))
documents = []
for row in cursor.fetchall():
documents.append({
'id': row[0],
'name': row[1],
'content': row[2],
'upload_date': row[3]
})
return documents
except sqlite3.Error as e:
st.error(f"Error retrieving collection documents: {e}")
return []
def create_collection(conn: sqlite3.Connection, name: str, description: str = "") -> Optional[int]:
"""
Create a new collection.
Args:
conn (sqlite3.Connection): Database connection
name (str): Name of the collection
description (str): Optional description
Returns:
Optional[int]: ID of the created collection if successful
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO collections (name, description)
VALUES (?, ?)
''', (name, description))
conn.commit()
return cursor.lastrowid
except sqlite3.Error as e:
st.error(f"Error creating collection: {e}")
return None
def add_document_to_collection(conn: sqlite3.Connection, document_id: int, collection_id: int) -> bool:
"""
Add a document to a collection.
Args:
conn (sqlite3.Connection): Database connection
document_id (int): ID of the document
collection_id (int): ID of the collection
Returns:
bool: True if successful
"""
try:
with conn_lock:
cursor = conn.cursor()
cursor.execute('''
INSERT OR IGNORE INTO document_collections (document_id, collection_id)
VALUES (?, ?)
''', (document_id, collection_id))
conn.commit()
return True
except sqlite3.Error as e:
st.error(f"Error adding document to collection: {e}")
return False
def process_document(file_path):
"""
Process a PDF document with proper chunking.
Args:
file_path (str): Path to the PDF file
Returns:
tuple: (list of document chunks, full content of the document)
"""
# Load PDF
loader = PyPDFLoader(file_path)
documents = loader.load()
# Create text splitter
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
length_function=len,
separators=["\n\n", "\n", " ", ""]
)
# Split documents into chunks
chunks = text_splitter.split_documents(documents)
# Extract full content for database storage
full_content = "\n".join(doc.page_content for doc in documents)
return chunks, full_content
def display_vector_store_info():
"""
Display information about the current vector store state.
"""
if 'vector_store' not in st.session_state:
st.info("βΉοΈ No documents loaded yet.")
return
try:
# Get the vector store from session state
vector_store = st.session_state.vector_store
# Get basic stats
test_query = vector_store.similarity_search("test", k=1)
doc_count = len(test_query)
# Create an expander for detailed info
with st.expander("π Knowledge Base Status"):
col1, col2 = st.columns(2)
with col1:
st.metric(
label="Documents Loaded",
value=doc_count
)
with col2:
st.metric(
label="System Status",
value="Ready" if verify_vector_store(vector_store) else "Not Ready"
)
# Display sample queries
if verify_vector_store(vector_store):
st.markdown("### π Sample Document Snippets")
sample_docs = vector_store.similarity_search("", k=3)
for i, doc in enumerate(sample_docs, 1):
with st.container():
st.markdown(f"**Snippet {i}:**")
st.text(doc.page_content[:200] + "...")
except Exception as e:
st.error(f"Error displaying vector store info: {e}")
st.error(traceback.format_exc())
def initialize_qa_system(vector_store):
"""
Initialize QA system with optimized retrieval.
Args:
vector_store (FAISS): FAISS vector store instance.
Returns:
dict: QA system chain or None if initialization fails.
"""
try:
llm = ChatOpenAI(
temperature=0.5,
model_name="gpt-4",
max_tokens=4000, # Explicitly set max tokens
api_key=os.environ.get("OPENAI_API_KEY")
)
# Optimize retriever settings
retriever = vector_store.as_retriever(
search_kwargs={
"k": 3, # Retrieve fewer, more relevant chunks
"fetch_k": 5 # Consider more candidates before selecting top k
}
)
# Create a template that enforces clean formatting
prompt = ChatPromptTemplate.from_messages([
("system", """
You are an expert consultant specializing in analyzing Request for Proposal (RFP) documents. Your goal is to assist users by providing clear, concise, and professional insights based on the content provided. Please adhere to the following guidelines when crafting your responses:
Begin with a summary that highlights the key findings or answers the main query.
Structured Format: Use clear and descriptive section headers to organize the information logically.
Bullet Points: Utilize bullet points for lists or complex information to enhance readability.
Source Attribution: Cite specific sections or page numbers from the RFP document when referencing information.
Professional Formatting: Maintain a clean and professional layout using Markdown formatting, such as headings, bullet points, bold, italics, and tables where appropriate.
Use Markdown Syntax: Ensure the response is fully formatted using Markdown for optimal readability in the chat.
Focused Content: Keep your responses concise and directly related to the user's query, avoiding unnecessary information.
Scope Awareness: If a query falls outside the provided information or context, politely acknowledge this and suggest consulting the relevant sections or additional sources.
Confidentiality: Respect the confidentiality of the information provided and avoid sharing any sensitive data beyond the scope of the query.
Tone and Language: Use formal and professional language, ensuring clarity and precision in your responses.
Accuracy: Double-check all information for accuracy and completeness before providing it to the user.
"""),
MessagesPlaceholder(variable_name="chat_history"),
("human", "{input}\n\nContext: {context}")
])
def get_chat_history(inputs):
chat_history = inputs.get("chat_history", [])
if not isinstance(chat_history, list):
return []
return [msg for msg in chat_history if isinstance(msg, BaseMessage)]
def get_context(inputs):
docs = retriever.get_relevant_documents(inputs["input"])
context_parts = []
for doc in docs:
source = doc.metadata.get('source', 'Unknown source')
context_parts.append(f"\nFrom {source}:\n{doc.page_content}")
return "\n".join(context_parts)
chain = (
{
"context": get_context,
"chat_history": get_chat_history,
"input": lambda x: x["input"]
}
| prompt
| llm
)
return chain
except Exception as e:
st.error(f"Error initializing QA system: {e}")
return None
# FAISS vector store initialization
def initialize_faiss(embeddings, documents, document_names):
"""
Initialize FAISS vector store.
Args:
embeddings (Embeddings): Embeddings model to use.
documents (list): List of document contents.
document_names (list): List of document names.
Returns:
FAISS: FAISS vector store instance or None if initialization fails.
"""
try:
from langchain.vectorstores import FAISS
vector_store = FAISS.from_texts(
documents,
embeddings,
metadatas=[{"source": name} for name in document_names],
)
return vector_store
except Exception as e:
st.error(f"Error initializing FAISS: {e}")
return None
# Embeddings model retrieval
@st.cache_resource
def get_embeddings_model():
"""
Get the embeddings model.
Returns:
Embeddings: Embeddings model instance or None if loading fails.
"""
try:
from langchain.embeddings import HuggingFaceEmbeddings
model_name = "sentence-transformers/all-MiniLM-L6-v2"
embeddings = HuggingFaceEmbeddings(model_name=model_name)
return embeddings
except Exception as e:
st.error(f"Error loading embeddings model: {e}")
return None
|