umar-100 commited on
Commit
d8cba91
·
verified ·
1 Parent(s): 8e028e6

Upload folder using huggingface_hub

Browse files
.dockerignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ .git/
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ RAG-APP/data/fb.pdf filter=lfs diff=lfs merge=lfs -text
.github/workflows/update_space.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Python script
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Checkout
14
+ uses: actions/checkout@v2
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: '3.9'
20
+
21
+ - name: Install Gradio
22
+ run: python -m pip install gradio
23
+
24
+ - name: Log in to Hugging Face
25
+ run: python -c 'import huggingface_hub; huggingface_hub.login(token="${{ secrets.hf_token }}")'
26
+
27
+ - name: Deploy to Spaces
28
+ run: gradio deploy
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ /home/azureuser/rag-app/RAG-APP/myvenv
2
+ myvenv
3
+ .env
4
+ main.py
5
+ a.txt
Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12.3-slim
2
+
3
+ WORKDIR /RAG-APP
4
+
5
+
6
+ COPY requirements.txt .
7
+
8
+ RUN pip install --no-cache-dir -r requirements.txt
9
+
10
+ COPY . .
11
+
12
+ EXPOSE 80
13
+
14
+ CMD [ "python","app.py" ]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
RAG-APP/data/fb.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eee8b0f39e9fa375a5dcff70b2c87dc6b0284b0603258a6b59afaa95ff573761
3
+ size 3536276
RAG-APP/data/last lesson.pdf ADDED
Binary file (348 kB). View file
 
RAG-APP/data/privacy policy.pdf ADDED
Binary file (145 kB). View file
 
README.md CHANGED
@@ -1,12 +1,45 @@
1
  ---
2
- title: QA Bot
3
- emoji: 📉
4
- colorFrom: gray
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 4.44.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
  ---
2
+ title: QA-bot
3
+ app_file: app.py
 
 
4
  sdk: gradio
5
  sdk_version: 4.44.0
 
 
6
  ---
7
+ # PDF Question-Answering App using LangChain, Pinecone, and Mistral
8
+
9
+ This project is a RAG app designed to perform question-answering (QA) on PDF documents. It uses the `LangChain` framework for embedding, `Pinecone` for vector storage, and the `mistral` language model for generating responses to user queries.
10
+
11
+ ## Features
12
+ - **PDF Handling**: Load and split PDF files into manageable chunks for processing.
13
+ - **Embeddings**: I am using the `SentenceTransformerEmbeddings` to create embeddings for document chunks.
14
+ - **Vector Storage**: Pinecone is used to store document embeddings and efficiently retrieve relevant chunks based on user questions.
15
+ - **LLM Integration**: I tried using LLMs locally using `Ollama`but due to lack of compute resources I used `mistral` for faster and better responses.
16
+ - **Environment Variables**: Secrets like API keys are securely managed using `.env` files.
17
+
18
+ ## Requirements
19
+ - Python 3.12
20
+ - Run `pip install -r requirements.txt`
21
+ - The following teck stack is used:
22
+ - `langchain`
23
+ - `pinecone` Make sure to sign up and create Pinecone API key
24
+ - `Mistral API`
25
+
26
+
27
+ ## Setup
28
+
29
+ ### 1. Clone the Repository
30
+ ```bash
31
+ git clone https://github.com/m-umar-j/RAG-APP
32
+ cd RAG-APP
33
+ ```
34
+ ### 2. install the requirements using
35
+ ```bash
36
+ pip install -r requirements.txt`
37
+ ```
38
+ ### 3. create .env file in your root directory and add pinecone API key
39
+
40
+ ``` makefile
41
+ PINECONE_API_KEY=your-pinecone-api-key
42
+ ```
43
+ ### 4. modify paths
44
 
45
+ `file_path = "/path/to/data.pdf"`
__pycache__/gradio.cpython-312.pyc ADDED
Binary file (488 Bytes). View file
 
__pycache__/utilis.cpython-312.pyc ADDED
Binary file (2.71 kB). View file
 
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from langchain_community.embeddings import SentenceTransformerEmbeddings
3
+ from langchain_community.vectorstores import Pinecone as LangchainPinecone
4
+ from utilis import load_split_file, create_index, final_response
5
+ from langchain_mistralai.chat_models import ChatMistralAI
6
+
7
+ import os
8
+ import shutil
9
+ from dotenv import load_dotenv
10
+
11
+
12
+ load_dotenv()
13
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
14
+ MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
15
+
16
+
17
+
18
+ embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
19
+
20
+ model = ChatMistralAI(mistral_api_key=MISTRAL_API_KEY)
21
+ pinecone_index = "index"
22
+ index_name = create_index(pinecone_index, PINECONE_API_KEY)
23
+
24
+ def save_file(fileobj):
25
+
26
+ upload_dir = "RAG-APP/data/"
27
+ if not os.path.exists(upload_dir):
28
+ os.makedirs(upload_dir)
29
+
30
+ # Save the file to the disk
31
+ file_path = os.path.join(upload_dir, os.path.basename(fileobj.name))
32
+ shutil.copyfile(fileobj.name, file_path)
33
+
34
+ return file_path
35
+
36
+ def process_pdf(fileobj):
37
+ file_path = save_file(fileobj)
38
+ docs = load_split_file(file_path)
39
+
40
+
41
+ index = LangchainPinecone.from_documents(docs, embeddings, index_name=index_name)
42
+
43
+ return index, "File Uploaded Successfully"
44
+
45
+
46
+
47
+ with gr.Blocks() as Iface:
48
+ file_input = gr.File(label="Upload PDF") # This will give you the uploaded file's tempfile object
49
+
50
+ upload_file = gr.Button("Upload File")
51
+ index_state = gr.State()
52
+
53
+ message = gr.Textbox("Please wait while the file is processed!")
54
+ upload_file.click(fn = lambda file:
55
+ process_pdf(file),
56
+ inputs = file_input,
57
+ outputs = [index_state, message])
58
+
59
+
60
+ question_input = gr.Textbox(label="Ask any question about your document")
61
+
62
+ submit_button = gr.Button("Get Answer")
63
+
64
+ with gr.Row():
65
+ answer_output = gr.Textbox(label="Answer", scale=3)
66
+ matching_results = gr.Textbox(label="Reference", scale=1)
67
+
68
+
69
+ submit_button.click(
70
+ fn=lambda index, q: final_response(index, q, model),
71
+ inputs=[index_state, question_input],
72
+ outputs=[answer_output, matching_results]
73
+ )
74
+
75
+ Iface.launch(share=True)
notebook.ipynb ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# PDF QA RAG App"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "markdown",
12
+ "metadata": {},
13
+ "source": [
14
+ "## Importing necessary libraries "
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "execution_count": 1,
20
+ "metadata": {},
21
+ "outputs": [],
22
+ "source": [
23
+ "from langchain_community.document_loaders import PyPDFLoader\n",
24
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
25
+ "\n",
26
+ "from langchain.prompts import PromptTemplate \n",
27
+ "from langchain_core.output_parsers import StrOutputParser \n",
28
+ "from operator import itemgetter\n",
29
+ "\n",
30
+ "from pinecone import Pinecone, ServerlessSpec"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "markdown",
35
+ "metadata": {},
36
+ "source": [
37
+ "## Defining helper functions"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": 2,
43
+ "metadata": {},
44
+ "outputs": [],
45
+ "source": [
46
+ "def load_split_file(file_path):\n",
47
+ " loader = PyPDFLoader(file_path)\n",
48
+ " pages = loader.load_and_split()\n",
49
+ "\n",
50
+ " \n",
51
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=10)\n",
52
+ " docs = text_splitter.split_documents(pages)\n",
53
+ "\n",
54
+ " return docs\n",
55
+ "\n"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "execution_count": 3,
61
+ "metadata": {},
62
+ "outputs": [],
63
+ "source": [
64
+ "def create_index(index_name, PINECONE_API_KEY):\n",
65
+ " \n",
66
+ " pc = Pinecone(api_key=PINECONE_API_KEY)\n",
67
+ "\n",
68
+ " if index_name in pc.list_indexes().names():\n",
69
+ " pc.delete_index(index_name) # To avoid any conflicts in retrieval\n",
70
+ " pc.create_index(\n",
71
+ " name=index_name, \n",
72
+ " dimension=384, \n",
73
+ " metric='cosine',\n",
74
+ " spec=ServerlessSpec(\n",
75
+ " cloud=\"aws\",\n",
76
+ " region=\"us-east-1\"\n",
77
+ " )\n",
78
+ " )\n",
79
+ "\n",
80
+ " return index_name\n",
81
+ "\n"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "execution_count": 4,
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "def final_response(index, question, model):\n",
91
+ " retriever = index.as_retriever()\n",
92
+ "\n",
93
+ " parser = StrOutputParser()\n",
94
+ "\n",
95
+ " chain = model | parser \n",
96
+ "\n",
97
+ " template = \"\"\"\n",
98
+ " You must provide an answer based strictly on the context below. The answer is highly likely to be found within the given context, so analyze it thoroughly before responding. Only if there is absolutely no relevant information, respond with \"I don't know\".\n",
99
+ "\n",
100
+ " Context: {context}\n",
101
+ "\n",
102
+ " Question: {question}\n",
103
+ " \"\"\"\n",
104
+ "\n",
105
+ "\n",
106
+ " prompt = PromptTemplate.from_template(template)\n",
107
+ " prompt.format(context=\"Here is some context\", question=\"Here is a question\")\n",
108
+ "\n",
109
+ " chain = (\n",
110
+ " {\n",
111
+ " \"context\": itemgetter(\"question\") | retriever,\n",
112
+ " \"question\": itemgetter(\"question\"),\n",
113
+ " }\n",
114
+ " | prompt\n",
115
+ " | model\n",
116
+ " | parser\n",
117
+ " )\n",
118
+ " matching_results=index.similarity_search(question,k=2)\n",
119
+ "\n",
120
+ " return f\"Answer: {chain.invoke({'question': question})}\", matching_results\n",
121
+ "\n"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "metadata": {},
128
+ "outputs": [],
129
+ "source": [
130
+ "import gradio as gr\n",
131
+ "from langchain_community.embeddings import SentenceTransformerEmbeddings\n",
132
+ "from langchain_community.vectorstores import Pinecone as LangchainPinecone\n",
133
+ "from utilis import load_split_file, create_index, final_response\n",
134
+ "from langchain_mistralai.chat_models import ChatMistralAI\n",
135
+ "\n",
136
+ "import os\n",
137
+ "import shutil\n",
138
+ "from dotenv import load_dotenv"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": 6,
144
+ "metadata": {},
145
+ "outputs": [],
146
+ "source": [
147
+ "load_dotenv()\n",
148
+ "PINECONE_API_KEY = os.getenv(\"PINECONE_API_KEY\")\n",
149
+ "MISTRAL_API_KEY = os.getenv(\"MISTRAL_API_KEY\")\n",
150
+ "SAVE_DIR = \"/RAG-APP/data.pdf\"\n"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "execution_count": null,
156
+ "metadata": {},
157
+ "outputs": [],
158
+ "source": [
159
+ "embeddings = SentenceTransformerEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
160
+ "\n",
161
+ "model = ChatMistralAI(mistral_api_key=MISTRAL_API_KEY)\n",
162
+ "pinecone_index = \"index\"\n",
163
+ "index_name = create_index(pinecone_index, PINECONE_API_KEY)"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "metadata": {},
170
+ "outputs": [],
171
+ "source": [
172
+ "file_path = \"data/last lesson.pdf\"\n",
173
+ "docs = load_split_file(file_path)"
174
+ ]
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "execution_count": null,
179
+ "metadata": {},
180
+ "outputs": [],
181
+ "source": [
182
+ "index = LangchainPinecone.from_documents(docs, embeddings, index_name=index_name)\n",
183
+ "question = \"What data does google collects?\"\n",
184
+ "matching_results=index.similarity_search(question,k=2)\n",
185
+ "\n",
186
+ "answer = final_response(index, question, model)\n",
187
+ "\n",
188
+ "print(f\"{answer}\\n\\n{matching_results}\")"
189
+ ]
190
+ }
191
+ ],
192
+ "metadata": {
193
+ "kernelspec": {
194
+ "display_name": "myvenv",
195
+ "language": "python",
196
+ "name": "python3"
197
+ },
198
+ "language_info": {
199
+ "codemirror_mode": {
200
+ "name": "ipython",
201
+ "version": 3
202
+ },
203
+ "file_extension": ".py",
204
+ "mimetype": "text/x-python",
205
+ "name": "python",
206
+ "nbconvert_exporter": "python",
207
+ "pygments_lexer": "ipython3",
208
+ "version": "3.12.3"
209
+ }
210
+ },
211
+ "nbformat": 4,
212
+ "nbformat_minor": 2
213
+ }
requirements.txt ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ aiohappyeyeballs==2.4.0
3
+ aiohttp==3.10.5
4
+ aiohttp-cors==0.7.0
5
+ aiosignal==1.3.1
6
+ altair==5.4.1
7
+ annotated-types==0.7.0
8
+ anyio==4.4.0
9
+ appdirs==1.4.4
10
+ asttokens==2.4.1
11
+ async-lru==2.0.4
12
+ attrs==24.2.0
13
+ beartype==0.15.0
14
+ bleach==6.1.0
15
+ blinker==1.8.2
16
+ bokeh==3.5.2
17
+ boto3==1.35.20
18
+ botocore==1.35.20
19
+ cachetools==5.5.0
20
+ certifi==2024.8.30
21
+ charset-normalizer==3.3.2
22
+ click==8.1.7
23
+ cohere==5.9.4
24
+ comm==0.2.2
25
+ contourpy==1.3.0
26
+ cycler==0.12.1
27
+ dataclasses-json==0.6.7
28
+ debugpy==1.8.5
29
+ decorator==5.1.1
30
+ Deprecated==1.2.14
31
+ diskcache==5.6.3
32
+ distro==1.9.0
33
+ docarray==0.40.0
34
+ executing==2.1.0
35
+ fastapi==0.115.0
36
+ fastavro==1.9.7
37
+ ffmpy==0.4.0
38
+ filelock==3.16.0
39
+ fonttools==4.53.1
40
+ frozenlist==1.4.1
41
+ fs==2.4.16
42
+ fsspec==2024.9.0
43
+ geographiclib==2.0
44
+ geopy==2.4.1
45
+ gitdb==4.0.11
46
+ GitPython==3.1.43
47
+ google-ai-generativelanguage==0.6.9
48
+ google-api-core==2.19.2
49
+ google-api-python-client==2.145.0
50
+ google-auth==2.34.0
51
+ google-auth-httplib2==0.2.0
52
+ google-cloud-bigquery==3.25.0
53
+ google-cloud-core==2.4.1
54
+ google-cloud-pubsub==2.23.1
55
+ google-crc32c==1.6.0
56
+ google-generativeai==0.8.1
57
+ google-resumable-media==2.7.2
58
+ googleapis-common-protos==1.65.0
59
+ gradio==4.44.0
60
+ gradio_client==1.3.0
61
+ greenlet==3.1.0
62
+ grpc-google-iam-v1==0.13.1
63
+ grpcio==1.66.1
64
+ grpcio-status==1.62.3
65
+ h11==0.14.0
66
+ h3==3.7.7
67
+ httpcore==1.0.5
68
+ httplib2==0.22.0
69
+ httpx==0.27.2
70
+ httpx-sse==0.4.0
71
+ huggingface-hub==0.24.7
72
+ idna==3.10
73
+ importlib_metadata==8.4.0
74
+ importlib_resources==6.4.5
75
+ ipykernel==6.29.5
76
+ ipython==8.27.0
77
+ ipywidgets==8.1.5
78
+ jedi==0.19.1
79
+ Jinja2==3.1.4
80
+ jiter==0.5.0
81
+ jmespath==1.0.1
82
+ joblib==1.4.2
83
+ jsonpatch==1.33
84
+ jsonpointer==3.0.0
85
+ jsonschema==4.23.0
86
+ jsonschema-specifications==2023.12.1
87
+ jupyter_bokeh==4.0.5
88
+ jupyter_client==8.6.3
89
+ jupyter_core==5.7.2
90
+ jupyterlab_widgets==3.0.13
91
+ kiwisolver==1.4.7
92
+ langchain==0.3.0
93
+ langchain-community==0.3.0
94
+ langchain-core==0.3.0
95
+ langchain-mistralai==0.2.0
96
+ langchain-text-splitters==0.3.0
97
+ langsmith==0.1.121
98
+ linkify-it-py==2.0.3
99
+ litellm==1.46.1
100
+ Markdown==3.7
101
+ markdown-it-py==3.0.0
102
+ MarkupSafe==2.1.5
103
+ marshmallow==3.22.0
104
+ matplotlib==3.9.2
105
+ matplotlib-inline==0.1.7
106
+ mdit-py-plugins==0.4.2
107
+ mdurl==0.1.2
108
+ mpmath==1.3.0
109
+ multidict==6.1.0
110
+ mypy-extensions==1.0.0
111
+ narwhals==1.8.1
112
+ nest-asyncio==1.6.0
113
+ networkx==3.3
114
+ numpy==1.26.4
115
+ nvidia-cublas-cu12==12.1.3.1
116
+ nvidia-cuda-cupti-cu12==12.1.105
117
+ nvidia-cuda-nvrtc-cu12==12.1.105
118
+ nvidia-cuda-runtime-cu12==12.1.105
119
+ nvidia-cudnn-cu12==9.1.0.70
120
+ nvidia-cufft-cu12==11.0.2.54
121
+ nvidia-curand-cu12==10.3.2.106
122
+ nvidia-cusolver-cu12==11.4.5.107
123
+ nvidia-cusparse-cu12==12.1.0.106
124
+ nvidia-nccl-cu12==2.20.5
125
+ nvidia-nvjitlink-cu12==12.6.68
126
+ nvidia-nvtx-cu12==12.1.105
127
+ openai==1.45.1
128
+ opentelemetry-api==1.27.0
129
+ opentelemetry-exporter-otlp-proto-common==1.27.0
130
+ opentelemetry-exporter-otlp-proto-grpc==1.27.0
131
+ opentelemetry-proto==1.27.0
132
+ opentelemetry-sdk==1.27.0
133
+ opentelemetry-semantic-conventions==0.48b0
134
+ orjson==3.10.7
135
+ packaging==24.1
136
+ pandas==2.2.2
137
+ panel==1.5.0
138
+ param==2.1.1
139
+ parameterized==0.9.0
140
+ parso==0.8.4
141
+ pexpect==4.9.0
142
+ pillow==10.4.0
143
+ pinecone==5.3.0
144
+ pinecone-plugin-inference==1.1.0
145
+ pinecone-plugin-interface==0.0.7
146
+ platformdirs==4.3.3
147
+ prompt_toolkit==3.0.47
148
+ proto-plus==1.24.0
149
+ protobuf==4.25.4
150
+ psutil==6.0.0
151
+ ptyprocess==0.7.0
152
+ pure_eval==0.2.3
153
+ pyarrow==17.0.0
154
+ pyasn1==0.6.1
155
+ pyasn1_modules==0.4.1
156
+ pydantic==2.7.4
157
+ pydantic-settings==2.5.2
158
+ pydantic_core==2.18.4
159
+ pydeck==0.9.1
160
+ pydub==0.25.1
161
+ Pygments==2.18.0
162
+ pyparsing==3.1.4
163
+ pypdf==4.3.1
164
+ python-dateutil==2.9.0.post0
165
+ python-dotenv==1.0.1
166
+ python-multipart==0.0.9
167
+ python-sat==1.8.dev13
168
+ pytz==2024.2
169
+ pyviz_comms==3.0.3
170
+ PyYAML==6.0.2
171
+ pyzmq==26.2.0
172
+ referencing==0.35.1
173
+ regex==2024.9.11
174
+ requests==2.32.3
175
+ rich==13.8.1
176
+ rpds-py==0.20.0
177
+ rsa==4.9
178
+ ruff==0.6.6
179
+ s3transfer==0.10.2
180
+ safetensors==0.4.5
181
+ scikit-learn==1.5.2
182
+ scipy==1.14.1
183
+ semantic-version==2.10.0
184
+ sentence-transformers==3.1.0
185
+ setuptools==75.1.0
186
+ shapely==2.0.6
187
+ shellingham==1.5.4
188
+ six==1.16.0
189
+ smmap==5.0.1
190
+ sniffio==1.3.1
191
+ SQLAlchemy==2.0.35
192
+ sqlglot==10.6.1
193
+ stack-data==0.6.3
194
+ starlette==0.38.5
195
+ sympy==1.13.2
196
+ tenacity==8.5.0
197
+ threadpoolctl==3.5.0
198
+ tiktoken==0.7.0
199
+ tokenizers==0.19.1
200
+ toml==0.10.2
201
+ tomlkit==0.12.0
202
+ torch==2.4.1
203
+ tornado==6.4.1
204
+ tqdm==4.66.5
205
+ traitlets==5.14.3
206
+ transformers==4.44.2
207
+ triton==3.0.0
208
+ typer==0.12.5
209
+ types-requests==2.32.0.20240914
210
+ typing-inspect==0.9.0
211
+ typing_extensions==4.12.2
212
+ tzdata==2024.1
213
+ uc-micro-py==1.0.3
214
+ uritemplate==4.1.1
215
+ urllib3==2.2.3
216
+ uvicorn==0.30.6
217
+ watchdog==4.0.2
218
+ wcwidth==0.2.13
219
+ webencodings==0.5.1
220
+ websockets==12.0
221
+ widgetsnbextension==4.0.13
222
+ wrapt==1.16.0
223
+ xyzservices==2024.9.0
224
+ yarl==1.11.1
225
+ zipp==3.20.2
utilis.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.document_loaders import PyPDFLoader
2
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
3
+
4
+ from langchain.prompts import PromptTemplate
5
+ from langchain_core.output_parsers import StrOutputParser
6
+ from operator import itemgetter
7
+
8
+ from pinecone import Pinecone, ServerlessSpec
9
+
10
+
11
+
12
+ def load_split_file(file_path):
13
+ loader = PyPDFLoader(file_path)
14
+ pages = loader.load_and_split()
15
+
16
+
17
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=10)
18
+ docs = text_splitter.split_documents(pages)
19
+
20
+ return docs
21
+
22
+
23
+ def create_index(index_name, PINECONE_API_KEY):
24
+
25
+ pc = Pinecone(api_key=PINECONE_API_KEY)
26
+
27
+ if index_name in pc.list_indexes().names():
28
+ pc.delete_index(index_name) # To avoid any conflicts in retrieval
29
+ pc.create_index(
30
+ name=index_name,
31
+ dimension=384,
32
+ metric='cosine',
33
+ spec=ServerlessSpec(
34
+ cloud="aws",
35
+ region="us-east-1"
36
+ )
37
+ )
38
+
39
+ return index_name
40
+
41
+
42
+ def final_response(index, question, model):
43
+ retriever = index.as_retriever()
44
+
45
+ parser = StrOutputParser()
46
+
47
+ chain = model | parser
48
+
49
+ template = """
50
+ You must provide an answer based strictly on the context below.
51
+ The answer is highly likely to be found within the given context, so analyze it thoroughly before responding.
52
+ Only if there is absolutely no relevant information, respond with "I don't know".
53
+ Do not make things up.
54
+
55
+ Context: {context}
56
+
57
+ Question: {question}
58
+ """
59
+
60
+
61
+ prompt = PromptTemplate.from_template(template)
62
+ prompt.format(context="Here is some context", question="Here is a question")
63
+
64
+ chain = (
65
+ {
66
+ "context": itemgetter("question") | retriever,
67
+ "question": itemgetter("question"),
68
+ }
69
+ | prompt
70
+ | model
71
+ | parser
72
+ )
73
+ matching_results=index.similarity_search(question,k=2)
74
+
75
+ return f"Answer: {chain.invoke({'question': question})}", matching_results
76
+