ramshashaikh commited on
Commit
515d0b4
·
1 Parent(s): d6c0b61

Final Commit v1

Browse files
README.md CHANGED
@@ -1,12 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
- title: Ekatra QnA
3
- emoji: 💻
4
- colorFrom: red
5
- colorTo: blue
6
- sdk: streamlit
7
- sdk_version: 1.17.0
8
- app_file: app.py
9
- pinned: false
10
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
+ <h1 align="center">Welcome to Ekatra QnA System 👋</h1>
2
+ <p>
3
+ <a href="." target="_blank">
4
+ <img alt="Documentation" src="https://img.shields.io/badge/documentation-yes-brightgreen.svg" />
5
+ </a>
6
+ <a href="#" target="_blank">
7
+ <img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" />
8
+ </a>
9
+ <a href="https://twitter.com/ekatraone" target="_blank">
10
+ <img alt="Twitter: ekatraone" src="https://img.shields.io/twitter/follow/ekatraone.svg?style=social" />
11
+ </a>
12
+ </p>
13
+
14
+ > Ekatra QnA is a student-focused intelligent search engine that enables them to find answers across various sources.
15
+
16
+ ### 🏠 [Homepage](https://github.com/ekatraone/Ekatra-QnA-System)
17
+ ---
18
+ ### 🎥 Check out our [demo video](https://www.awesomescreenshot.com/video/15118083?key=c9f98dd8fcc835f6f97c1cefd7ac6317)
19
+ ---
20
+ ## Abstract
21
+
22
+ - The objective of this project is to create a smart search engine named [Ekatra](www.ekatra.one) QnA, which is intended to assist students in finding answers from various sources such as web links and PDF documents in a prompt and effective manner. The search engine employs NLP techniques, including text extraction, preprocessing, vectorization, and semantic similarity, to accurately and quickly identify the most suitable answers to students' queries. The intended target audience for this project is students worldwide who face difficulties in finding pertinent information from a vast amount of data.
23
+
24
+
25
+ - Ekatra QnA employs cutting-edge technologies such as OpenAI and Sentence Transformers to filter out irrelevant information and offer students the most useful and appropriate content. The system is built to boost productivity and save time for students as it efficiently identifies the required information, allowing them to concentrate more on learning and less on searching.
26
+
27
+ - Furthermore, it should be noted that all information in the search engine comes from a validated source. If the answer to a question is not present in the documents, the system is equipped to recognize this and prevent sharing misleading information.
28
+
29
+ *Learn more about Ekatra here: https://www.ekatra.one/*
30
+
31
+ ---
32
+
33
+ ## Features
34
+ Our proposed intelligent search engine for students offers several features that address the common challenges students face when searching for information. Here are more details on each of these features:
35
+
36
+ 1. **Multiple File Search:** The system allows students to search for answers across multiple files, including PDFs. This feature ensures that students have access to a broader range of information sources, enabling them to find answers to their queries faster and more efficiently.
37
+
38
+
39
+ 1. **Simultaneous Text Extraction:** The system can extract text from multiple sources simultaneously, enabling faster and more efficient searches.
40
+
41
+ 2. **Accurate and Condensed Presentation:**
42
+ The system presents the extracted text in the most accurate and condensed form, making it easier for students to read and understand.
43
+
44
+ 4. **Relevant Content:**
45
+ - One of the most important features is its capability to detect questions that are not relevant to the provided documents. This functionality helps prevent the system from providing erroneous or misleading answers to the student.
46
+ - The system filters out irrelevant information and selects the most appropriate answer by analyzing the given data, providing students with the most useful and pertinent content.
47
+
48
+ ---
49
+ ## Workflow
50
+
51
+ The proposed workflow for the intelligent search engine includes the following steps:
52
+
53
+ 1. Users are able to upload a PDF document to the system.
54
+ 2. The system employs the PyPDF2 library to extract the text from the uploaded PDF.
55
+ 3. The extracted text undergoes a preprocessing step to remove noise such as stop words and punctuation.
56
+ 4. A pre-trained model from Hugging Face is used to vectorize the preprocessed text and the user's question
57
+
58
+ 6. The resulting embeddings of the text and question are stored for future use.
59
+ 7. The stored embeddings are used to locate similar sentences from the text.
60
+ 8. The similar sentences are then combined to form a concise and accurate answer to the user's question.
61
+ 9. The system presents the final answer in the most appropriate format within the provided document. If the answer cannot be found within the document, the system displays "I don't know." to the user.
62
+ ----
63
+ ## Tech Stack
64
+
65
+ ### Programming Language
66
+
67
+ - [**Python**](https://www.python.org/doc/): A popular, high-level programming language known for its simplicity, readability, and versatility.
68
+
69
+ ### Data Processing and Analysis
70
+
71
+ - [**Numpy**](https://numpy.org): A library for scientific computing and numerical analysis in Python. It provides support for large, multi-dimensional arrays and matrices, as well as a collection of mathematical functions.
72
+
73
+ ### Natural Language Processing
74
+
75
+ - [**NLTK**](https://www.nltk.org): A suite of libraries and programs for natural language processing tasks such as tokenization, stemming, and part-of-speech tagging.
76
+
77
+ ### PDF Text Extraction
78
+
79
+ - [**PyPDF2**](https://pypi.org/project/PyPDF2/): A pure-python library for extracting text from PDF documents. It can also be used to extract metadata and other information from PDF files.
80
+
81
+ ### Web App Framework
82
+
83
+ - [**Streamlit**](https://pypi.org/project/PyPDF2/): An open-source web app framework for building interactive, customizable, and data-driven apps using Python. It provides an intuitive UI and fast feedback, making it easy to create and iterate on apps.
84
+
85
+ ### AI and Machine Learning Frameworks:
86
+
87
+ - [**OpenAI**](https://openai.com): OpenAI is known for its advanced language models such as GPT-3, which provide developers with powerful natural language processing capabilities for a wide range of applications. Their language models can perform tasks such as text completion, translation, and question-answering with impressive accuracy.
88
+
89
+ - [**Huggingface**](https://huggingface.co): A startup that develops state-of-the-art natural language processing technologies and tools, including pre-trained models, fine-tuning tools, and language generation tools.
90
+
91
+ - [**Sentence Transformers Library**](https://huggingface.co/sentence-transformers): The Sentence Transformers library is a core component of the tech stack as it provides pre-trained models for sentence embedding generation, as well as tools for fine-tuning and training new models.
92
+
93
+ ----
94
+ ## Architecture
95
+
96
+ ![System Architecture](./system-architecture.png)
97
+
98
+ - **Text extraction** refers to the process of extracting relevant text data from a given source, such as a PDF document, web page, or image.
99
+
100
+ - **Preprocessing** is the initial step in natural language processing, which involves cleaning and transforming raw text data into a format that is suitable for further analysis. This includes removing stop words, punctuations, converting all text to lowercase, and stemming.
101
+
102
+ - **Vectorization** is the process of converting text data into a numerical vector representation, allowing it to be processed and analyzed using mathematical algorithms. This involves converting each word or sentence into a high-dimensional vector using techniques such as Word2Vec or BERT.
103
+
104
+ - A **vector database** is a database system that stores and retrieves vectors efficiently. Vector databases are used in various applications, such as search engines, recommendation systems, and natural language processing.
105
+
106
+ - **Semantic similarity** refers to the degree of similarity between two pieces of text in terms of their meaning or semantic content. It is often measured by comparing the vector representations of the text using algorithms such as cosine similarity.
107
+
108
+ - **Answer synthesis** using OpenAI involves using pre-trained language models and natural language generation techniques to generate coherent and relevant responses to a user's query. The models use deep learning algorithms and large amounts of training data to generate human-like responses to natural language queries.
109
+
110
  ---
111
+ ## Open-source and Digital Public Goods leveraged/used:
112
+
113
+ 1. Python
114
+ 2. Numpy
115
+ 3. NLTK
116
+ 4. Streamlit
117
+ 5. Sentence Transformers
118
+
119
  ---
120
+ ## User's Guide 👥
121
+ Here's a quick guide to help you get started:
122
+
123
+ 1. Visit [Ekatra QnA](https://ramsha-ekatra-ekatra-qna.hf.space/)
124
+
125
+ 2. Once you're on our website, simply upload your PDF files using the easy upload feature.
126
+
127
+ 3. Once you have uploaded your files, simply wait for the **"Process Completed"** message before you start asking any questions related to the content of your PDF files.
128
+
129
+ 4. Our search engine will then be ready to provide you with the most relevant answers to your queries.
130
+
131
+
132
+ ---
133
+ ## Developer's Guide 💻
134
+
135
+ ### **Prerequisites: Obtain required OpenAPI Keys 🔑**
136
+
137
+ 1. Go to the [OpenAI](https://openai.com) website and click on the "Sign Up"/ "Login" button
138
+
139
+ 2. Once you have successfully registered/ logged in, go to the API dashboard and click on "Create API Key".
140
+
141
+ 3. Select the API plan that best suits your needs and click "Continue".
142
+
143
+ 4. Review the API agreement and accept the terms and conditions.
144
+
145
+ 5. Your API key will now be displayed on the dashboard. Copy the key and use it in your project.
146
+
147
+ *Note: Keep your API key confidential and do not share it with anyone. Also, make sure to follow the OpenAI API usage guidelines to avoid any misuse of the API.*
148
+
149
+ ### **Run on local server**
150
+ 1. Clone our github [repo](https://github.com/ekatraone/Ekatra-QnA-System.git)
151
+
152
+ ```bash
153
+ git clone https://github.com/ekatraone/Ekatra-QnA-System.git
154
+ ```
155
+ 2. Install dependencies
156
+
157
+ ```sh
158
+ pip install -r requirements.txt
159
+ ```
160
+
161
+ 3. Run app.py
162
+ ```
163
+ streamlit run app.py
164
+ ```
165
+
166
+ ---
167
+ ## Authors
168
+
169
+ 👤 **Ekatra Team**
170
+
171
+ * [Abheejit](https://github.com/iabheejit)
172
+ * [Ramsha](https://github.com/ramshashaikh)
173
+ * [Rushikesh](https://github.com/shaharao-rushikesh)
174
+
175
+ 🏢 **Ekatra Learning, Inc.**
176
 
177
+ * Website: [Ekatra](www.ekatra.one)
178
+ * Twitter: [@ekatraone](https://twitter.com/ekatraone)
179
+ * LinkedIn: [@ekatraone](https://www.linkedin.com/company/ekatraone/)
__pycache__/operations.cpython-310.pyc CHANGED
Binary files a/__pycache__/operations.cpython-310.pyc and b/__pycache__/operations.cpython-310.pyc differ
 
app.py CHANGED
@@ -3,27 +3,18 @@ import textwrap
3
  # from dotenv import load_dotenv
4
  import streamlit as st
5
  import os
6
- import PyPDF2
7
  import nltk
8
  from nltk.tokenize import sent_tokenize
9
- from sentence_transformers import SentenceTransformer
10
- import numpy as np
11
- from numpy.linalg import norm
12
  import openai
13
  nltk.download('punkt')
14
- # load_dotenv()
15
 
16
 
17
  openai.organization = os.environ['org']
18
  openai.api_key = os.environ['api_key']
19
 
20
 
21
-
22
- url = "https://www.independentschoolparent.com/wp-content/uploads/2018/01/AI.jpg"
23
-
24
  st.title("Ekatra QnA")
25
  st.write("AI Powered Smart Search System")
26
- # st.image(url)
27
 
28
  st.markdown('_Welcome to Question Answering System 🧠 🤖_')
29
 
@@ -32,108 +23,94 @@ top_match_sentences = []
32
 
33
  @st.cache(allow_output_mutation=True)
34
  def process_pdf_data(uploaded_files):
 
 
 
 
 
 
 
 
 
 
 
35
  filt1_list = []
36
  embeddings = []
37
- cosine_lis = []
38
 
39
  text_ext = []
40
  for i in uploaded_files:
41
  if i.type == "application/pdf":
42
- # reader = PyPDF2.PdfReader(i)
43
-
44
  text_ext += op.read_pdf(i)
45
 
 
46
  sent_toks = []
47
  for i in text_ext:
48
  sent_toks.append(sent_tokenize(i))
49
 
50
- # print("len(sent_toks) ", sent_toks)
51
-
52
  concat_list = [j for i in sent_toks for j in i]
53
 
 
54
  for i in concat_list:
55
  a = (i.replace('\n', ' '))
56
  filt1_list.append(a)
57
 
58
- # model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
59
-
60
- embeddings = op.create_content_embeddings(concat_list)
61
  return filt1_list, embeddings
62
 
63
 
64
- # if st.sidebar.radio("SELECT -", ['PDF']) == 'PDF':
65
  uploaded_files = st.file_uploader(
66
  "Upload files - ", accept_multiple_files=True, type=['pdf'])
67
 
68
- # print(len(uploaded_files) == 0)
69
  if st.button("Process!"):
70
  if len(uploaded_files) != 0:
71
- # print(len(uploaded_files))
72
  filt1_list, embeddings = process_pdf_data(uploaded_files)
73
  st.write("Process Completed")
74
 
75
  else:
76
  st.warning("Please upload a PDF file.")
77
 
 
78
  query = st.text_input('Ask me anything!', placeholder='Type.....')
79
- if st.button("Confirm!"):
80
- model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
81
- cached_data = process_pdf_data(uploaded_files)
82
- filt1_list = cached_data[0]
83
- embeddings = cached_data[1]
84
- query_embedding = op.create_query_embeddings(query)
85
- cosine_lis = op.calculate_cosine(
86
- query_embedding, embeddings, filt1_list)
87
- # print("cosine ", cosine_lis)
88
-
89
- indexes_final = op.fetch_top_rank_ans(cosine_lis, 15)
90
-
91
- most_relevant = op.fetch_most_relevant(
92
- indexes_final, filt1_list, cosine_lis, query)
93
-
94
- # print("most_relevant ", most_relevant)
95
-
96
- COMPLETIONS_API_PARAMS = {
97
- "temperature": 0.0,
98
- "max_tokens": 300,
99
- "model": "text-davinci-003",
100
- }
101
-
102
- response = openai.Completion.create(
103
- prompt=most_relevant,
104
- **COMPLETIONS_API_PARAMS
105
- )
106
- print("\n\n", textwrap.fill(
107
- response["choices"][0]["text"].strip(" \n")))
108
-
109
- # prompt = f"Q: {question}\n\nA: Please give an honest answer, only based on given data. If you don't know the answer, simply say 'I don't know'.\n\n"
110
- # # add the sentences to the prompt
111
- # for sentence in top_15_sentences:
112
- # prompt += f"{sentence}\n"
113
-
114
- # header = """Answer the question as truthfully as possible using the provided context, and if the answer is not contained within the text below, say "I don't know."\n\nContext:\n"""
115
- # chosen_sections = "".join(top_15_sentences)
116
- # prompt = header + chosen_sections + "\n\n Q: " + query + "\n A:"
117
-
118
- # # add the top 15 sentences to the prompt
119
- # for sentence in top_15_sentences:
120
- # prompt += f"\n{sentence}"
121
-
122
- # # generate the answer using the OpenAI API
123
- # response = openai.Completion.create(
124
- # engine="davinci", prompt=prompt, max_tokens=300, n=1, stop=None, temperature=0.001
125
- # )
126
- # # answer = response.choices[0].text.strip()
127
-
128
- # COMPLETIONS_API_PARAMS = {
129
- # "temperature": 0.0,
130
- # "max_tokens": 300,
131
- # "model": "text-davinci-003",
132
- # }
133
-
134
- # response = openai.Completion.create(
135
- # prompt=prompt,
136
- # **COMPLETIONS_API_PARAMS
137
- # )
138
-
139
- st.write(textwrap.fill(response["choices"][0]["text"].strip(" \n")))
 
3
  # from dotenv import load_dotenv
4
  import streamlit as st
5
  import os
 
6
  import nltk
7
  from nltk.tokenize import sent_tokenize
 
 
 
8
  import openai
9
  nltk.download('punkt')
 
10
 
11
 
12
  openai.organization = os.environ['org']
13
  openai.api_key = os.environ['api_key']
14
 
15
 
 
 
 
16
  st.title("Ekatra QnA")
17
  st.write("AI Powered Smart Search System")
 
18
 
19
  st.markdown('_Welcome to Question Answering System 🧠 🤖_')
20
 
 
23
 
24
  @st.cache(allow_output_mutation=True)
25
  def process_pdf_data(uploaded_files):
26
+ """
27
+ The function accepts an uploaded PDF file as input and then proceeds to extract, preprocess, and vectorize the text. It ultimately returns a list of filtered sentences and their respective embeddings.
28
+
29
+ Parameters:
30
+ uploaded_files (list): List of uploaded files
31
+
32
+ Returns:
33
+ filt1_list (list): List of filtered sentences
34
+ embeddings (list): List of embeddings of the sentences
35
+
36
+ """
37
  filt1_list = []
38
  embeddings = []
 
39
 
40
  text_ext = []
41
  for i in uploaded_files:
42
  if i.type == "application/pdf":
43
+ # Reading the pdf file and extracting the text
 
44
  text_ext += op.read_pdf(i)
45
 
46
+ # Applying sent_tokenize to the text and storing the result in a list
47
  sent_toks = []
48
  for i in text_ext:
49
  sent_toks.append(sent_tokenize(i))
50
 
 
 
51
  concat_list = [j for i in sent_toks for j in i]
52
 
53
+ # Removing the new line characters from the list
54
  for i in concat_list:
55
  a = (i.replace('\n', ' '))
56
  filt1_list.append(a)
57
 
58
+ # Creating embeddings for the sentences
59
+ embeddings = op.create_content_embeddings(filt1_list)
 
60
  return filt1_list, embeddings
61
 
62
 
63
+ # Streamlit code to upload files
64
  uploaded_files = st.file_uploader(
65
  "Upload files - ", accept_multiple_files=True, type=['pdf'])
66
 
 
67
  if st.button("Process!"):
68
  if len(uploaded_files) != 0:
69
+ # Calling the function process_pdf_data to process the uploaded files
70
  filt1_list, embeddings = process_pdf_data(uploaded_files)
71
  st.write("Process Completed")
72
 
73
  else:
74
  st.warning("Please upload a PDF file.")
75
 
76
+ # Streamlit code to take user input after vectorization of the documents
77
  query = st.text_input('Ask me anything!', placeholder='Type.....')
78
+ try:
79
+ if st.button("Confirm!"):
80
+
81
+ cached_data = process_pdf_data(uploaded_files)
82
+ filt1_list = cached_data[0]
83
+ embeddings = cached_data[1]
84
+
85
+ # Creating embeddings for the query
86
+ query_embedding = op.create_query_embeddings(query)
87
+
88
+ # Calculating cosine similarity between the query and the sentences
89
+ cosine_lis = op.calculate_cosine(
90
+ query_embedding, embeddings, filt1_list)
91
+
92
+ # Fetching the top 15 sentences with the highest cosine similarity
93
+ indexes_final = op.fetch_top_rank_ans(cosine_lis, 15)
94
+
95
+ # Fetching the most relevant sentence from the top 15 sentences, and providing it as the context to the GPT-3 model
96
+ most_relevant = op.fetch_most_relevant(
97
+ indexes_final, filt1_list, cosine_lis, query)
98
+
99
+ # Calling the GPT-3 model to generate the answer
100
+ COMPLETIONS_API_PARAMS = {
101
+ "temperature": 0.0,
102
+ "max_tokens": 300,
103
+ "model": "text-davinci-003",
104
+ }
105
+
106
+ response = openai.Completion.create(
107
+ prompt=most_relevant,
108
+ **COMPLETIONS_API_PARAMS
109
+ )
110
+ # print("\n\n", textwrap.fill(
111
+ # response["choices"][0]["text"].strip(" \n")))
112
+
113
+ # Displaying the answer to the user
114
+ st.write(textwrap.fill(response["choices"][0]["text"].strip(" \n")))
115
+ except:
116
+ st.warning("Something went wrong. Please try again.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
operations.py CHANGED
@@ -3,40 +3,57 @@ import numpy as np
3
  from sentence_transformers import SentenceTransformer
4
  import PyPDF2
5
  from nltk.tokenize import sent_tokenize
6
- import nltk
7
- # nltk.download('punkt')
8
- import sys
9
- # from dotenv import load_dotenv
10
- # load_dotenv('./env')
11
-
12
- sys.setrecursionlimit(5500)
13
 
14
 
15
  def read_pdf(fname):
 
 
 
 
 
 
 
 
 
16
  reader = PyPDF2.PdfReader(fname)
17
  text_ext = []
18
  for i in range(len(reader.pages)):
19
  pageObj = reader.pages[i]
20
  # extracting text from page
21
  text_ext.append(pageObj.extract_text())
22
- # text_ext.append(pageObj.extract_text())
23
- # print("len(text_ext) ", len(text_ext))
24
  return text_ext
25
 
26
 
27
  def sent_tokenize(text_ext):
 
 
 
 
 
 
 
 
 
28
  sent_toks = []
29
 
30
  for i in text_ext:
31
  sent_toks.append(sent_tokenize(i))
32
  print("len(sent_toks) ", len(sent_toks))
33
 
34
- # concat_list = [j for i in sent_toks for j in i]
35
- # print(len(concat_list))
36
  return sent_toks
37
 
38
 
39
  def create_content_embeddings(concat_list):
 
 
 
 
 
 
 
 
 
40
  model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
41
  embeddings = model.encode(concat_list)
42
 
@@ -44,17 +61,33 @@ def create_content_embeddings(concat_list):
44
 
45
 
46
  def create_query_embeddings(query_text):
 
 
 
 
 
 
 
 
 
47
  model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
48
  query_embedding = model.encode(query_text)
49
  return query_embedding
50
 
51
 
52
  def calculate_cosine(query_embedding, embeddings, concat_list):
53
- # cosine = np.dot(
54
- # query_embedding, embeddings[350]) / (norm(query_embedding)*norm(embeddings[350]))
55
 
56
- # print("cosine ", cosine)
57
 
 
 
 
 
 
 
 
 
58
  cosine_lis = []
59
 
60
  for i in range(len(concat_list)):
@@ -67,6 +100,17 @@ def calculate_cosine(query_embedding, embeddings, concat_list):
67
 
68
 
69
  def fetch_top_rank_ans(cosine_lis, N):
 
 
 
 
 
 
 
 
 
 
 
70
  list1 = cosine_lis
71
  indexes_final = sorted(
72
  range(len(list1)), key=lambda i: list1[i], reverse=True)[:N]
@@ -84,14 +128,25 @@ def fetch_top_rank_ans(cosine_lis, N):
84
 
85
 
86
  def fetch_most_relevant(indexes_final, concat_list, list1, query):
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  dicts = {}
88
 
89
  keys = indexes_final
90
  for i in keys:
91
  dicts[i] = concat_list[i]
92
 
93
- # print("[dicts] ", [dicts])
94
-
95
  most_relevant_document_sections = [dicts]
96
 
97
  len(most_relevant_document_sections)
@@ -99,13 +154,10 @@ def fetch_most_relevant(indexes_final, concat_list, list1, query):
99
  chosen_sections = []
100
  chosen_sections_len = 0
101
  chosen_sections_indexes = []
102
- document_section = []
103
 
104
  indices = range(len(list1))
105
  sorted_indices = sorted(indices, key=lambda i: list1[i], reverse=True)
106
- print(len(indexes_final))
107
-
108
- # indexes_final = []
109
 
110
  for section_index in range(len(indexes_final)):
111
 
@@ -117,7 +169,6 @@ def fetch_most_relevant(indexes_final, concat_list, list1, query):
117
 
118
  # Useful diagnostic information
119
  print(f"Selected {len(chosen_sections)} document sections:")
120
- # print("\n".join(chosen_sections_indexes))
121
 
122
  header = """Answer the question as truthfully as possible using the provided context, and if the answer is not contained within the text below, say "I don't know."\n\nContext:\n"""
123
 
 
3
  from sentence_transformers import SentenceTransformer
4
  import PyPDF2
5
  from nltk.tokenize import sent_tokenize
 
 
 
 
 
 
 
6
 
7
 
8
  def read_pdf(fname):
9
+ """
10
+ This function reads the pdf file and extracts the text from it.
11
+
12
+ Parameters:
13
+ fname (str): Name of the pdf file
14
+
15
+ Returns:
16
+ text_ext (list): List of extracted text from the pdf file
17
+ """
18
  reader = PyPDF2.PdfReader(fname)
19
  text_ext = []
20
  for i in range(len(reader.pages)):
21
  pageObj = reader.pages[i]
22
  # extracting text from page
23
  text_ext.append(pageObj.extract_text())
24
+
 
25
  return text_ext
26
 
27
 
28
  def sent_tokenize(text_ext):
29
+ """
30
+ This function apply sent_tokenize to the text and stores the result in a list.
31
+
32
+ Parameters:
33
+ text_ext (list): List of extracted text from the pdf file
34
+
35
+ Returns:
36
+ sent_toks (list): List of tokenized sentences
37
+ """
38
  sent_toks = []
39
 
40
  for i in text_ext:
41
  sent_toks.append(sent_tokenize(i))
42
  print("len(sent_toks) ", len(sent_toks))
43
 
 
 
44
  return sent_toks
45
 
46
 
47
  def create_content_embeddings(concat_list):
48
+ """
49
+ This function creates embeddings for the document sentences.
50
+
51
+ Parameters:
52
+ concat_list (list): List of tokenized sentences
53
+
54
+ Returns:
55
+ embeddings (list): List of embeddings of the sentences
56
+ """
57
  model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
58
  embeddings = model.encode(concat_list)
59
 
 
61
 
62
 
63
  def create_query_embeddings(query_text):
64
+ """
65
+ This function creates embeddings for the query.
66
+ Parameters:
67
+ query_text (str): Query entered by the user
68
+
69
+ Returns:
70
+ query_embedding (list): List of embeddings of the query
71
+ """
72
+
73
  model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
74
  query_embedding = model.encode(query_text)
75
  return query_embedding
76
 
77
 
78
  def calculate_cosine(query_embedding, embeddings, concat_list):
79
+ """
 
80
 
81
+ This function calculates cosine similarity between the query and the sentences.
82
 
83
+ Parameters:
84
+ query_embedding (list): List of embeddings of the query
85
+ embeddings (list): List of embeddings of the sentences
86
+ concat_list (list): List of tokenized sentences
87
+
88
+ Returns:
89
+ cosine_lis (list): List of cosine similarity values
90
+ """
91
  cosine_lis = []
92
 
93
  for i in range(len(concat_list)):
 
100
 
101
 
102
  def fetch_top_rank_ans(cosine_lis, N):
103
+ """
104
+ This function fetches the top N ranked sentences.
105
+
106
+ Parameters:
107
+ cosine_lis (list): List of cosine similarity values
108
+ N (int): Number of sentences to be ranked
109
+
110
+ Returns:
111
+ indexes_final (list): List of top N ranked sentences
112
+ """
113
+
114
  list1 = cosine_lis
115
  indexes_final = sorted(
116
  range(len(list1)), key=lambda i: list1[i], reverse=True)[:N]
 
128
 
129
 
130
  def fetch_most_relevant(indexes_final, concat_list, list1, query):
131
+ """
132
+ This function fetches the most relevant sentences, pass it as a context to GPT-3 prompt along with user's query.
133
+
134
+ Parameters:
135
+ indexes_final (list): List of top N ranked sentences
136
+ concat_list (list): List of tokenized sentences
137
+ list1 (list): List of cosine similarity values
138
+ query (str): Query entered by the user
139
+
140
+ Returns:
141
+ prompt (str): GPT-3 prompt
142
+ """
143
+
144
  dicts = {}
145
 
146
  keys = indexes_final
147
  for i in keys:
148
  dicts[i] = concat_list[i]
149
 
 
 
150
  most_relevant_document_sections = [dicts]
151
 
152
  len(most_relevant_document_sections)
 
154
  chosen_sections = []
155
  chosen_sections_len = 0
156
  chosen_sections_indexes = []
 
157
 
158
  indices = range(len(list1))
159
  sorted_indices = sorted(indices, key=lambda i: list1[i], reverse=True)
160
+ # print(len(indexes_final))
 
 
161
 
162
  for section_index in range(len(indexes_final)):
163
 
 
169
 
170
  # Useful diagnostic information
171
  print(f"Selected {len(chosen_sections)} document sections:")
 
172
 
173
  header = """Answer the question as truthfully as possible using the provided context, and if the answer is not contained within the text below, say "I don't know."\n\nContext:\n"""
174
 
system-architecture.png ADDED