reab5555 commited on
Commit
72d74b8
·
verified ·
1 Parent(s): c8bdd53

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -0
app.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import faiss
4
+ import numpy as np
5
+ from langchain_huggingface import HuggingFaceEmbeddings
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain_community.vectorstores import FAISS
8
+ from langchain.chains import ConversationalRetrievalChain
9
+ from langchain.memory import ConversationBufferMemory
10
+ from langchain_core.documents import Document
11
+ from PyPDF2 import PdfReader
12
+ from langchain_anthropic import ChatAnthropic
13
+
14
+ API_KEY = os.getenv('CLAUDE_API_KEY')
15
+
16
+ llm = ChatAnthropic(model="claude-3-5-sonnet-20240620", temperature=0.5, max_tokens=8192, anthropic_api_key=API_KEY)
17
+
18
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
19
+
20
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
21
+
22
+ vector_store = None
23
+
24
+
25
+ def process_file(file_path):
26
+ _, ext = os.path.splitext(file_path)
27
+ try:
28
+ if ext.lower() == '.txt':
29
+ with open(file_path, 'r', encoding='utf-8') as file:
30
+ text = file.read()
31
+ elif ext.lower() == '.docx':
32
+ with open(file_path, 'rb') as file:
33
+ content = file.read()
34
+ text = content.decode('utf-8', errors='ignore')
35
+ elif ext.lower() == '.pdf':
36
+ with open(file_path, 'rb') as file:
37
+ pdf_reader = PdfReader(file)
38
+ text = '\n'.join([page.extract_text() for page in pdf_reader.pages if page.extract_text()])
39
+ else:
40
+ print(f"Unsupported file type: {ext}")
41
+ return None
42
+
43
+ return [Document(page_content=text, metadata={"source": file_path})]
44
+ except Exception as e:
45
+ print(f"Error processing file {file_path}: {str(e)}")
46
+ return None
47
+
48
+
49
+ def process_files(file_list, progress=gr.Progress()):
50
+ global vector_store
51
+ documents = []
52
+ total_files = len(file_list)
53
+
54
+ for i, file in enumerate(file_list):
55
+ progress((i + 1) / total_files, f"Processing file {i + 1} of {total_files}")
56
+ if file.name.lower().endswith(('.txt', '.docx', '.pdf')):
57
+ docs = process_file(file.name)
58
+ if docs:
59
+ documents.extend(docs)
60
+
61
+ if not documents:
62
+ return "No documents were successfully processed. Please check your files and try again."
63
+
64
+ progress(0.5, "Splitting text")
65
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=200)
66
+ texts = text_splitter.split_documents(documents)
67
+
68
+ progress(0.7, "Creating embeddings")
69
+ vector_store = FAISS.from_documents(texts, embeddings)
70
+
71
+ progress(0.9, "Saving vector store")
72
+ vector_store.save_local("faiss_index")
73
+
74
+ progress(1.0, "Completed")
75
+ return f"Embedding process completed and database created. Processed {len(documents)} files. You can now start chatting!"
76
+
77
+
78
+ def load_existing_index(folder_path):
79
+ global vector_store
80
+ try:
81
+ index_file = os.path.join(folder_path, "index.faiss")
82
+ pkl_file = os.path.join(folder_path, "index.pkl")
83
+
84
+ if not os.path.exists(index_file) or not os.path.exists(pkl_file):
85
+ return f"Error: FAISS index files not found in {folder_path}. Please ensure both 'index.faiss' and 'index.pkl' are present."
86
+
87
+ vector_store = FAISS.load_local(folder_path, embeddings, allow_dangerous_deserialization=True)
88
+ return f"Successfully loaded existing index from {folder_path}."
89
+ except Exception as e:
90
+ return f"Error loading index: {str(e)}"
91
+
92
+
93
+ def chat(message, history):
94
+ global vector_store
95
+ if vector_store is None:
96
+ return "Please load documents or an existing index first."
97
+
98
+ qa_chain = ConversationalRetrievalChain.from_llm(
99
+ llm,
100
+ vector_store.as_retriever(),
101
+ memory=memory
102
+ )
103
+
104
+ result = qa_chain.invoke({"question": message, "chat_history": history})
105
+ return result['answer']
106
+
107
+
108
+ def reset_chat():
109
+ global memory
110
+ memory.clear()
111
+ return []
112
+
113
+
114
+ with gr.Blocks() as demo:
115
+ gr.Markdown("# Document-based Chatbot")
116
+
117
+ with gr.Row():
118
+ with gr.Column():
119
+ file_input = gr.File(label="Select Files", file_count="multiple", file_types=[".pdf", ".docx", ".txt"])
120
+ process_button = gr.Button("Process Files")
121
+ with gr.Column():
122
+ index_folder = gr.Textbox(label="Existing Index Folder Path",
123
+ value="C:\\Works\\Data\\projects\\Python\\QA_Chatbot\\faiss_index")
124
+ load_index_button = gr.Button("Load Existing Index")
125
+
126
+ output = gr.Textbox(label="Processing Output")
127
+
128
+ chatbot = gr.Chatbot()
129
+ msg = gr.Textbox()
130
+ send = gr.Button("Send")
131
+ clear = gr.Button("Clear")
132
+
133
+
134
+ def process_selected_files(files):
135
+ if files:
136
+ return process_files(files)
137
+ else:
138
+ return "No files selected. Please select files and try again."
139
+
140
+
141
+ def load_selected_index(folder_path):
142
+ return load_existing_index(folder_path)
143
+
144
+
145
+ process_button.click(process_selected_files, file_input, output)
146
+ load_index_button.click(load_selected_index, index_folder, output)
147
+
148
+
149
+ def respond(message, chat_history):
150
+ bot_message = chat(message, chat_history)
151
+ chat_history.append((message, bot_message))
152
+ return "", chat_history
153
+
154
+
155
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
156
+ send.click(respond, [msg, chatbot], [msg, chatbot])
157
+ clear.click(reset_chat, None, chatbot)
158
+
159
+ if __name__ == "__main__":
160
+ demo.launch()