NaimaAqeel commited on
Commit
8d35da0
·
verified ·
1 Parent(s): ad8e307

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -101
app.py CHANGED
@@ -1,21 +1,24 @@
1
  import os
2
- import faiss
3
- import numpy as np
4
- import PyPDF2
5
  import io
 
 
6
  from docx import Document
 
7
  from nltk.tokenize import sent_tokenize
8
  from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
9
  from sentence_transformers import SentenceTransformer
10
- from langchain_community.vectorstores import FAISS
11
- from langchain_community.embeddings import HuggingFaceEmbeddings
12
  import gradio as gr
13
- import pickle
14
 
15
  # Download NLTK punkt tokenizer if not already downloaded
16
  import nltk
17
  nltk.download('punkt')
18
 
 
 
 
 
 
 
19
  # Function to extract text from a PDF file
20
  def extract_text_from_pdf(pdf_data):
21
  text = ""
@@ -37,37 +40,12 @@ def extract_text_from_docx(docx_data):
37
  print(f"Error extracting text from DOCX: {e}")
38
  return text
39
 
40
- # Initialize Sentence Transformer model for embeddings
41
- embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
42
-
43
- # Initialize Hugging Face API token
44
- api_token = os.getenv('HUGGINGFACEHUB_API_TOKEN')
45
- if not api_token:
46
- raise ValueError("HUGGINGFACEHUB_API_TOKEN environment variable is not set")
47
-
48
- # Initialize RAG models from Hugging Face
49
- generator_model_name = "facebook/bart-base"
50
- retriever_model_name = "facebook/bart-base"
51
- generator = AutoModelForSeq2SeqLM.from_pretrained(generator_model_name)
52
- generator_tokenizer = AutoTokenizer.from_pretrained(generator_model_name)
53
- retriever = AutoModelForSeq2SeqLM.from_pretrained(retriever_model_name)
54
- retriever_tokenizer = AutoTokenizer.from_pretrained(retriever_model_name)
55
-
56
- # Initialize FAISS index using LangChain
57
- hf_embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
58
-
59
- # Load or create FAISS index
60
- index_path = "faiss_index.pkl"
61
- if os.path.exists(index_path):
62
- with open(index_path, "rb") as f:
63
- faiss_index = pickle.load(f)
64
- print("Loaded FAISS index from faiss_index.pkl")
65
- else:
66
- faiss_index = FAISS(embedding_function=hf_embeddings)
67
-
68
  def preprocess_text(text):
69
  sentences = sent_tokenize(text)
70
  return sentences
 
 
71
  def upload_files(files):
72
  global faiss_index
73
  try:
@@ -92,79 +70,51 @@ def upload_files(files):
92
 
93
  # Encode sentences and add to FAISS index
94
  embeddings = embedding_model.encode(sentences)
95
- for embedding in embeddings:
96
- faiss_index.add(np.expand_dims(embedding, axis=0))
 
97
 
98
- # Save the updated index
99
- with open(index_path, "wb") as f:
100
- pickle.dump(faiss_index, f)
101
 
102
  return {"message": "Files processed successfully"}
103
  except Exception as e:
104
  print(f"Error processing files: {e}")
105
  return {"error": str(e)} # Provide informative error message
106
 
107
-
108
  def process_and_query(state, question):
109
  if question:
110
- # Preprocess the question
111
- question_embedding = embedding_model.encode([question])
112
-
113
- # Search the FAISS index for similar passages
114
- D, I = faiss_index.search(np.array(question_embedding), k=5)
115
- retrieved_passages = [faiss_index.index_to_text(i) for i in I[0]]
116
-
117
- # Use generator model to generate response based on question and retrieved passages
118
- prompt_template = """
119
- Answer the question as detailed as possible from the provided context,
120
- make sure to provide all the details, if the answer is not in
121
- provided context just say, "answer is not available in the context",
122
- don't provide the wrong answer
123
-
124
- Context:\n{context}\n
125
- Question:\n{question}\n
126
- Answer:
127
- """
128
- combined_input = prompt_template.format(context=' '.join(retrieved_passages), question=question)
129
- inputs = generator_tokenizer(combined_input, return_tensors="pt")
130
- with torch.no_grad():
131
- generator_outputs = generator.generate(**inputs)
132
- generated_text = generator_tokenizer.decode(generator_outputs[0], skip_special_tokens=True)
133
-
134
- # Update conversation history
135
- state.append({"question": question, "answer": generated_text})
136
-
137
- return {"message": generated_text, "conversation": state}
138
-
139
- return {"error": "No question provided"}
140
-
141
- # Initialize an empty state variable to store conversation history
142
- state = []
143
-
144
- # Create Gradio interface
145
- with gr.Interface(fn=None, live=True, capture_session=True) as demo:
146
- gr.Markdown("## Document Upload and Query System")
147
-
148
- with gr.Tab("Upload Files"):
149
- upload = gr.File(file_count="multiple", label="Upload PDF or DOCX files")
150
- upload_button = gr.Button("Upload")
151
- upload_output = gr.Textbox()
152
- upload_button.click(upload_files, inputs=upload, outputs=upload_output)
153
-
154
- with gr.Tab("Query"):
155
- query_input = gr.Textbox(label="Enter your query")
156
- query_output = gr.Textbox()
157
-
158
- # Define function to handle query and update state
159
- def query_handler():
160
- question = query_input.value # Get user's question from the input box
161
- state = [] # Initialize or update state as needed
162
- response = process_and_query(state, question) # Process query and retrieve response
163
- query_output.value = response.get("message", "Error: No response") # Update output textbox
164
-
165
- # Setup the click event with correct inputs and outputs
166
- query_button = gr.Button("Search", click=query_handler)
167
- demo.Interface(layout="vertical").launch()
168
-
169
-
170
-
 
1
  import os
 
 
 
2
  import io
3
+ import pickle
4
+ import PyPDF2
5
  from docx import Document
6
+ import numpy as np
7
  from nltk.tokenize import sent_tokenize
8
  from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
9
  from sentence_transformers import SentenceTransformer
 
 
10
  import gradio as gr
 
11
 
12
  # Download NLTK punkt tokenizer if not already downloaded
13
  import nltk
14
  nltk.download('punkt')
15
 
16
+ # Initialize Sentence Transformer model for embeddings
17
+ embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
18
+
19
+ # Initialize FAISS index using LangChain
20
+ faiss_index = None # Initialize or load your FAISS index as needed
21
+
22
  # Function to extract text from a PDF file
23
  def extract_text_from_pdf(pdf_data):
24
  text = ""
 
40
  print(f"Error extracting text from DOCX: {e}")
41
  return text
42
 
43
+ # Function to preprocess text into sentences
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  def preprocess_text(text):
45
  sentences = sent_tokenize(text)
46
  return sentences
47
+
48
+ # Function to handle file uploads
49
  def upload_files(files):
50
  global faiss_index
51
  try:
 
70
 
71
  # Encode sentences and add to FAISS index
72
  embeddings = embedding_model.encode(sentences)
73
+ if faiss_index is not None:
74
+ for embedding in embeddings:
75
+ faiss_index.add(np.expand_dims(embedding, axis=0))
76
 
77
+ # Save the updated index (if needed)
78
+ # Add your logic here to save the FAISS index if you're using persistence
 
79
 
80
  return {"message": "Files processed successfully"}
81
  except Exception as e:
82
  print(f"Error processing files: {e}")
83
  return {"error": str(e)} # Provide informative error message
84
 
85
+ # Function to process queries
86
  def process_and_query(state, question):
87
  if question:
88
+ try:
89
+ # Placeholder response based on query processing
90
+ response_message = "Placeholder response based on query processing"
91
+ return {"message": response_message, "conversation": state}
92
+ except Exception as e:
93
+ print(f"Error processing query: {e}")
94
+ return {"error": str(e)}
95
+ else:
96
+ return {"error": "No question provided"}
97
+
98
+ # Define the Gradio interface
99
+ def main():
100
+ gr.Interface(
101
+ fn=None, # Replace with your function that handles interface logic
102
+ inputs=gr.Interface.Layout([
103
+ gr.Tab("Upload Files", gr.Interface.Layout([
104
+ gr.File(label="Upload PDF or DOCX files", multiple=True),
105
+ gr.Button("Upload", onclick=upload_files),
106
+ gr.Textbox("Upload Status", default="No file uploaded yet", multiline=True)
107
+ ])),
108
+ gr.Tab("Query", gr.Interface.Layout([
109
+ gr.Textbox("Enter your query", label="Query Input"),
110
+ gr.Button("Search", onclick=process_and_query),
111
+ gr.Textbox("Query Response", default="No query processed yet", multiline=True)
112
+ ]))
113
+ ]),
114
+ outputs=gr.Textbox("Output", label="Output", default="Output will be shown here", multiline=True),
115
+ live=True,
116
+ capture_session=True
117
+ ).launch()
118
+
119
+ if __name__ == "__main__":
120
+ main()