Carlos Salgado commited on
Commit
cdb3fec
2 Parent(s): 485711d a565cf7

try to fix app bug

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -1
  2. app.py +21 -14
  3. app_V2.py +247 -0
Dockerfile CHANGED
@@ -25,7 +25,7 @@ COPY backend .
25
 
26
  # Install backend dependencies
27
  COPY backend/requirements.txt .
28
- RUN pip install --no-cache-dir -r requirements.txt --vvv
29
 
30
  # Stage 3: Serve frontend and backend using nginx and gunicorn
31
  FROM nginx:latest AS production
 
25
 
26
  # Install backend dependencies
27
  COPY backend/requirements.txt .
28
+ RUN pip install --no-cache-dir -r requirements.txt
29
 
30
  # Stage 3: Serve frontend and backend using nginx and gunicorn
31
  FROM nginx:latest AS production
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import io
2
  import os
3
  import streamlit as st
@@ -8,6 +9,23 @@ from scripts import analyze_metadata, generate_metadata, ingest, MODEL_NAME
8
  st.title('# DocVerifyRAG')
9
  st.write('## Anomaly detection for BIM document metadata')
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  with st.form('analyze_form'):
12
  st.write('Enter your file metadata in the following schema:')
13
  text = st.text_input(label='Filename, Description, Discipline',
@@ -25,21 +43,10 @@ with st.form('analyze_form'):
25
  st.write('## Generate metadata?')
26
  uploaded_file = st.file_uploader("Choose a PDF file", type=["pdf","txt"])
27
 
28
- if uploaded_file is not None:
29
- extension = uploaded_file.name.split('.')[-1]
30
-
31
- with tempfile.NamedTemporaryFile(delete=False) as tmp:
32
- tmp.write(uploaded_file.read())
33
- file_path = f'{tmp.name}.{extension}'
34
- st.write(f'Created temporary file {file_path}')
35
-
36
- docs = ingest(file_path)
37
- st.write('## Querying Together.ai API')
38
- metadata = generate_metadata(docs)
39
 
40
- form = st.form(key='generate_form')
41
- st.write(f'## Suggested Metadata Generated by {MODEL_NAME}')
42
- st.write(f'### {metadata}')
43
  delete_file_button = form.form_submit_button(label='Delete file')
44
  if delete_file_button:
45
  os.remove(file_path)
 
1
+ import os
2
  import io
3
  import os
4
  import streamlit as st
 
9
  st.title('# DocVerifyRAG')
10
  st.write('## Anomaly detection for BIM document metadata')
11
 
12
+ def suggest_metadata(file_upload):
13
+ extension = uploaded_file.name.split('.')[-1]
14
+
15
+ with tempfile.NamedTemporaryFile(delete=False) as tmp:
16
+ tmp.write(uploaded_file.read())
17
+ file_path = f'{tmp.name}.{extension}'
18
+ st.write(f'Created temporary file {file_path}')
19
+
20
+ st.write('## Processing file with Unstructured')
21
+ docs = ingest(file_path)
22
+ metadata = generate_metadata(docs)
23
+
24
+ st.write('## Querying Together.ai API')
25
+ form = st.form(key='generate_form')
26
+ st.write(f'## Suggested Metadata Generated by {MODEL_NAME}')
27
+ st.write(f'### {metadata}')
28
+
29
  with st.form('analyze_form'):
30
  st.write('Enter your file metadata in the following schema:')
31
  text = st.text_input(label='Filename, Description, Discipline',
 
43
  st.write('## Generate metadata?')
44
  uploaded_file = st.file_uploader("Choose a PDF file", type=["pdf","txt"])
45
 
46
+ if uploaded_file is not None:
 
 
 
 
 
 
 
 
 
 
47
 
48
+ suggest_metadata(uploaded_file)
49
+
 
50
  delete_file_button = form.form_submit_button(label='Delete file')
51
  if delete_file_button:
52
  os.remove(file_path)
app_V2.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import streamlit as st
3
+ from PyPDF2 import PdfReader
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.embeddings import OpenAIEmbeddings
6
+ from langchain.vectorstores import FAISS
7
+ from langchain.chat_models import ChatOpenAI
8
+ from langchain.memory import ConversationBufferMemory
9
+ from langchain.chains import ConversationalRetrievalChain
10
+ import os
11
+ import pickle
12
+ from datetime import datetime
13
+ from backend.generate_metadata import generate_metadata, ingest
14
+
15
+ MODEL_NAME = "mixtral"
16
+ css = '''
17
+ <style>
18
+ .chat-message {
19
+ padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
20
+ }
21
+ .chat-message.user {
22
+ background-color: #2b313e
23
+ }
24
+ .chat-message.bot {
25
+ background-color: #475063
26
+ }
27
+ .chat-message .avatar {
28
+ width: 20%;
29
+ }
30
+ .chat-message .avatar img {
31
+ max-width: 78px;
32
+ max-height: 78px;
33
+ border-radius: 50%;
34
+ object-fit: cover;
35
+ }
36
+ .chat-message .message {
37
+ width: 80%;
38
+ padding: 0 1.5rem;
39
+ color: #fff;
40
+ }
41
+ '''
42
+ bot_template = '''
43
+ <div class="chat-message bot">
44
+ <div class="avatar">
45
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png"
46
+ style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
47
+ </div>
48
+ <div class="message">{{MSG}}</div>
49
+ </div>
50
+ '''
51
+ user_template = '''
52
+ <div class="chat-message user">
53
+ <div class="avatar">
54
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
55
+ </div>
56
+ <div class="message">{{MSG}}</div>
57
+ </div>
58
+ '''
59
+
60
+
61
+ def get_pdf_text(pdf_docs):
62
+ text = ""
63
+ for pdf in pdf_docs:
64
+ pdf_reader = PdfReader(pdf)
65
+ for page in pdf_reader.pages:
66
+ text += page.extract_text()
67
+ return text
68
+
69
+
70
+ def get_text_chunks(text):
71
+ text_splitter = CharacterTextSplitter(
72
+ separator="\n",
73
+ chunk_size=1000,
74
+ chunk_overlap=200,
75
+ length_function=len
76
+ )
77
+ chunks = text_splitter.split_text(text)
78
+ return chunks
79
+
80
+
81
+ def get_vectorstore(text_chunks):
82
+ embeddings = OpenAIEmbeddings()
83
+ # embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
84
+ vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
85
+ return vectorstore
86
+
87
+
88
+ def get_conversation_chain(vectorstore):
89
+ llm = ChatOpenAI()
90
+ # llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.5, "max_length":512})
91
+
92
+ memory = ConversationBufferMemory(
93
+ memory_key='chat_history', return_messages=True)
94
+ conversation_chain = ConversationalRetrievalChain.from_llm(
95
+ llm=llm,
96
+ retriever=vectorstore.as_retriever(),
97
+ memory=memory
98
+ )
99
+ return conversation_chain
100
+
101
+
102
+ def handle_userinput(user_question):
103
+ response = st.session_state.conversation({'question': user_question})
104
+ st.session_state.chat_history = response['chat_history']
105
+
106
+ for i, message in enumerate(st.session_state.chat_history):
107
+ # Display user message
108
+ if i % 2 == 0:
109
+ st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
110
+ else:
111
+ print(message)
112
+ # Display AI response
113
+ st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
114
+
115
+
116
+ def safe_vec_store():
117
+ # USE VECTARA INSTEAD
118
+ os.makedirs('vectorstore', exist_ok=True)
119
+ filename = 'vectors' + datetime.now().strftime('%Y%m%d%H%M') + '.pkl'
120
+ file_path = os.path.join('vectorstore', filename)
121
+ vector_store = st.session_state.vectorstore
122
+
123
+ # Serialize and save the entire FAISS object using pickle
124
+ with open(file_path, 'wb') as f:
125
+ pickle.dump(vector_store, f)
126
+
127
+
128
+ """
129
+ def main():
130
+
131
+
132
+
133
+ st.subheader("Your documents")
134
+
135
+ if st.session_state.classify:
136
+ pdf_doc = st.file_uploader("Upload your PDFs here and click on 'Process'", accept_multiple_files=False)
137
+ else:
138
+ pdf_docs = st.file_uploader("Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
139
+ filenames = [file.name for file in pdf_docs if file is not None]
140
+ if st.button("Process"):
141
+ with st.spinner("Processing"):
142
+ if st.session_state.classify:
143
+ # THE CLASSIFICATION APP
144
+ st.write("Classifying")
145
+ plain_text_doc = ingest(pdf_doc.name)
146
+ classification_result = generate_metadata(plain_text_doc)
147
+ st.write(classification_result)
148
+ else:
149
+ # NORMAL RAG
150
+ loaded_vec_store = None
151
+ for filename in filenames:
152
+ if ".pkl" in filename:
153
+ file_path = os.path.join('vectorstore', filename)
154
+ with open(file_path, 'rb') as f:
155
+ loaded_vec_store = pickle.load(f)
156
+ raw_text = get_pdf_text(pdf_docs)
157
+ text_chunks = get_text_chunks(raw_text)
158
+ vec = get_vectorstore(text_chunks)
159
+ if loaded_vec_store:
160
+ vec.merge_from(loaded_vec_store)
161
+ st.warning("loaded vectorstore")
162
+ if "vectorstore" in st.session_state:
163
+ vec.merge_from(st.session_state.vectorstore)
164
+ st.warning("merged to existing")
165
+ st.session_state.vectorstore = vec
166
+ st.session_state.conversation = get_conversation_chain(vec)
167
+ st.success("data loaded")
168
+
169
+ if "conversation" not in st.session_state:
170
+ st.session_state.conversation = None
171
+ if "chat_history" not in st.session_state:
172
+ st.session_state.chat_history = None
173
+
174
+ user_question = st.text_input("Ask a question about your documents:")
175
+ if user_question:
176
+ handle_userinput(user_question)
177
+ with st.sidebar:
178
+ st.subheader("Classification instructions")
179
+ classifier_docs = st.file_uploader("Upload your instructions here and click on 'Process'",
180
+ accept_multiple_files=True)
181
+ filenames = [file.name for file in classifier_docs if file is not None]
182
+
183
+ if st.button("Process Classification"):
184
+ st.session_state.classify = True
185
+ with st.spinner("Processing"):
186
+ st.warning("set classify")
187
+ time.sleep(3)
188
+
189
+ if st.button("Save Embeddings"):
190
+ if "vectorstore" in st.session_state:
191
+ safe_vec_store()
192
+ # st.session_state.vectorstore.save_local("faiss_index")
193
+ st.sidebar.success("saved")
194
+ else:
195
+ st.sidebar.warning("No embeddings to save. Please process documents first.")
196
+
197
+ if st.button("Load Embeddings"):
198
+ st.warning("this function is not in use, just upload the vectorstore")
199
+ """
200
+
201
+
202
+ def main():
203
+
204
+ st.set_page_config(page_title="Doc Verify RAG", page_icon=":mag:")
205
+ st.write('Anomaly detection for document metadata', unsafe_allow_html=True)
206
+ st.header("Doc Verify RAG :mag:")
207
+
208
+ def set_pw():
209
+ st.session_state.openai_api_key = True
210
+
211
+ if "openai_api_key" not in st.session_state:
212
+ st.session_state.openai_api_key = False
213
+ if "openai_org" not in st.session_state:
214
+ st.session_state.openai_org = False
215
+ if "classify" not in st.session_state:
216
+ st.session_state.classify = False
217
+
218
+ col1, col2 = st.columns(2)
219
+ with col1:
220
+ uploaded_file = st.file_uploader("Choose a PDF file", type=["pdf", "txt"])
221
+
222
+ if uploaded_file is not None:
223
+ try:
224
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp:
225
+ tmp.write(uploaded_file.read())
226
+ file_path = tmp.name
227
+ st.write(f'Created temporary file {file_path}')
228
+
229
+ docs = ingest(file_path)
230
+ st.write('## Querying Together.ai API')
231
+ metadata = generate_metadata(docs)
232
+ st.write(f'## Metadata Generated by {MODEL_NAME}')
233
+ st.write(metadata)
234
+
235
+ # Clean up the temporary file
236
+ os.remove(file_path)
237
+
238
+ except Exception as e:
239
+ st.error(f'Error: {e}')
240
+ with col2:
241
+ OPENAI_API_KEY = st.text_input("OPENAI API KEY:", type="password",
242
+ disabled=st.session_state.openai_api_key, on_change=set_pw)
243
+ classification = st.file_uploader("upload the metadata", type=["csv", "txt"])
244
+
245
+
246
+ if __name__ == '__main__':
247
+ main()