ZacBl commited on
Commit
79a5c64
·
verified ·
1 Parent(s): 76894b4

Optimisation for faster exec

Browse files
Files changed (3) hide show
  1. app.py +52 -25
  2. doc_preprocessing.py +3 -2
  3. vector_DB.py +1 -0
app.py CHANGED
@@ -10,33 +10,18 @@ from llm_interaction import get_answer
10
  vector_database = VectorDatabase() #Instantiate the VectorDatabase Class
11
  chunks_metadata = []
12
 
13
- def main():
14
- st.title("Document Query App")
15
-
16
- uploaded_files = st.file_uploader(
17
- "Upload PDF or Word files", accept_multiple_files=True, type=["pdf", "docx"]
18
- )
19
 
20
- query = st.text_input("Enter your query:")
21
-
22
- if uploaded_files:
23
- global chunks_metadata
24
- all_chunks, all_embeddings, chunks_metadata = process_files(uploaded_files)
25
- vector_database.add_data(all_embeddings, all_chunks, chunks_metadata) # use the method
26
-
27
- st.session_state.files_processed = True
28
-
29
- if query:
30
- results = process_query(query)
31
- display_results(results)
32
 
 
33
  def process_query(query):
34
  if vector_database.is_empty(): #Use the method
35
  return "Please upload files first."
36
 
37
  # query_embedding = get_embeddings([query])[0]
38
  # results = vector_database.query(query_embedding, k=3) # use the method
 
39
  query_embedding = get_embeddings([query])[0] # Get the embedding for the query
 
40
  results = vector_database.query(query_embedding, k=10) # Get the top 2 results
41
 
42
  return results
@@ -46,17 +31,59 @@ def normalize_line_breaks(text):
46
 
47
  return text
48
 
49
- def display_results(results):
50
  cpt = 1
51
  for result in (results):
52
  if result['score'] < 0.5:
53
- st.subheader(f"Réponse {cpt+1} :")
54
- st.write(f"Source File: {result['file_name']}, Chunk: {result['chunk_index']}, Score: {round((1-result['score'])*100,2)}%")
55
- st.subheader("Citations depuis le document :")
56
- st.write(normalize_line_breaks(result["chunk_text"]))
57
- st_copy_to_clipboard(normalize_line_breaks(result["chunk_text"]))
58
- cpt += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  if __name__ == "__main__":
62
  main()
 
10
  vector_database = VectorDatabase() #Instantiate the VectorDatabase Class
11
  chunks_metadata = []
12
 
 
 
 
 
 
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ @st.cache_data
16
  def process_query(query):
17
  if vector_database.is_empty(): #Use the method
18
  return "Please upload files first."
19
 
20
  # query_embedding = get_embeddings([query])[0]
21
  # results = vector_database.query(query_embedding, k=3) # use the method
22
+ print('Query:', query)
23
  query_embedding = get_embeddings([query])[0] # Get the embedding for the query
24
+ print('Asking Queries..................')
25
  results = vector_database.query(query_embedding, k=10) # Get the top 2 results
26
 
27
  return results
 
31
 
32
  return text
33
 
34
+ def display_results(results, chunks):
35
  cpt = 1
36
  for result in (results):
37
  if result['score'] < 0.5:
38
+ st.subheader(f"Réponse {cpt} :")
39
+ st.write(f"Source File: {result['file_name']}, Score: {round(1./(1+result['score'])*100,2)}%") #
40
+
41
+ text_to_display = result['chunk_text']
42
+ col1, col2 = st.columns(2)
43
+ with col1:
44
+ previous_chunk_index = result['chunk_index'] - 1
45
+ if previous_chunk_index >= 0:
46
+ try:
47
+ previous_chunk_text = chunks[previous_chunk_index]
48
+ if st.button(f"Ajouter la portion de texte précédente", key=f"before_{cpt}"):
49
+ text_to_display = previous_chunk_text[:-50] + result['chunk_text']
50
+ except IndexError:
51
+ pass #silently ignore
52
+ with col2:
53
+ next_chunk_index = result['chunk_index'] + 1
54
+ if next_chunk_index < len(chunks):
55
+ try:
56
+ next_chunk_text = chunks[next_chunk_index]
57
+ if st.button(f"Ajouter la portion de texte suivante", key=f"after_{cpt}"):
58
+ text_to_display = result['chunk_text'] + next_chunk_text[50:]
59
+ except IndexError:
60
+ pass
61
+
62
+ st.write("Citations depuis le document :")
63
+ st.write(normalize_line_breaks(text_to_display))
64
+ st_copy_to_clipboard(normalize_line_breaks(text_to_display))
65
+ cpt += 1
66
+
67
 
68
+ def main():
69
+ st.title("Document Query App")
70
+
71
+ uploaded_files = st.file_uploader(
72
+ "Upload PDF or Word files", accept_multiple_files=True, type=["pdf", "docx"]
73
+ )
74
+
75
+ query = st.text_input("Enter your query:")
76
+
77
+ if uploaded_files:
78
+ global chunks_metadata
79
+ all_chunks, all_embeddings, chunks_metadata = process_files(uploaded_files)
80
+ vector_database.add_data(all_embeddings, all_chunks, chunks_metadata) # use the method
81
+
82
+ st.session_state.files_processed = True
83
+
84
+ if query:
85
+ results = process_query(query)
86
+ display_results(results, all_chunks)
87
 
88
  if __name__ == "__main__":
89
  main()
doc_preprocessing.py CHANGED
@@ -6,8 +6,8 @@ import streamlit as st
6
  import numpy as np
7
  import os
8
 
9
- emb_model = "intfloat/multilingual-e5-large-instruct"
10
- emb_model2 = "DeepPavlov/distilrubert-small-cased-conversational"
11
  def extract_text(file):
12
  text = ""
13
  # Check if the input is a file path (string) or a file-like object
@@ -69,6 +69,7 @@ def get_embeddings(texts)-> np.ndarray:
69
  st.error(f"Error generating embeddings: {e}")
70
  return np.array([])
71
 
 
72
  def process_files(files):
73
  all_chunks = []
74
  all_embeddings = []
 
6
  import numpy as np
7
  import os
8
 
9
+ # emb_model_ = "intfloat/multilingual-e5-large-instruct"
10
+ emb_model = "intfloat/multilingual-e5-base"
11
  def extract_text(file):
12
  text = ""
13
  # Check if the input is a file path (string) or a file-like object
 
69
  st.error(f"Error generating embeddings: {e}")
70
  return np.array([])
71
 
72
+ @st.cache_data
73
  def process_files(files):
74
  all_chunks = []
75
  all_embeddings = []
vector_DB.py CHANGED
@@ -75,6 +75,7 @@ class VectorDatabase:
75
  query_embedding = np.array(query_embedding, dtype=np.float32).reshape(1, -1) # Reshape for FAISS
76
 
77
  dist, indices = self.index.search(query_embedding, k=k)
 
78
  results = []
79
  for (i, j) in zip(indices[0], dist[0]):
80
  chunk_text = self.chunks[i]
 
75
  query_embedding = np.array(query_embedding, dtype=np.float32).reshape(1, -1) # Reshape for FAISS
76
 
77
  dist, indices = self.index.search(query_embedding, k=k)
78
+
79
  results = []
80
  for (i, j) in zip(indices[0], dist[0]):
81
  chunk_text = self.chunks[i]