thrag commited on
Commit
8d8cebe
·
1 Parent(s): 9d1ad6e

First batch of files

Browse files
Files changed (7) hide show
  1. .gitignore +160 -0
  2. README.md +14 -2
  3. app.ipynb +213 -0
  4. app.py +44 -0
  5. housekeeping.ipynb +100 -0
  6. vector-stores-create-1.ipynb +262 -0
  7. vector-stores-query.ipynb +140 -0
.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
README.md CHANGED
@@ -1,7 +1,7 @@
1
  ---
2
  title: Rag Demo 1
3
- emoji: 🌍
4
- colorFrom: green
5
  colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 3.47.1
@@ -10,3 +10,15 @@ pinned: false
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Rag Demo 1
3
+ emoji: 🏆
4
+ colorFrom: purple
5
  colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 3.47.1
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
13
+
14
+ # Books sourced from public domain.
15
+ 1. Literature
16
+ 1. https://www.planetebook.com/
17
+ 1. Finance
18
+ 1. https://assets.openstax.org/oscms-prodcms/media/documents/PrinciplesofFinance-WEB.pdf
19
+ 1. http://www.untag-smd.ac.id/files/Perpustakaan_Digital_1/FINANCE%20Essencial%20finance.pdf
20
+ 1. https://www.drnishikantjha.com/booksCollection/CoreCourseFinancialAccounting%20.pdf
21
+ 1. https://link.springer.com/book/10.1007/978-3-030-74817-3
22
+ 1. https://openbooks.lib.msu.edu/financialmanagement/
23
+ 1. https://press.rebus.community/financialstrategy/
24
+ 1. https://open.umn.edu/opentextbooks/subjects/finance
app.ipynb ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Setup UI"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": 2,
13
+ "metadata": {},
14
+ "outputs": [
15
+ {
16
+ "name": "stdout",
17
+ "output_type": "stream",
18
+ "text": [
19
+ "Loading settings from ../../env/ai.json\n"
20
+ ]
21
+ }
22
+ ],
23
+ "source": [
24
+ "import os\n",
25
+ "import json\n",
26
+ "\n",
27
+ "# If the file does not exist it'll default to the manual setting see below\n",
28
+ "filePathToSettingsFile = '../../env/ai.json'\n",
29
+ "\n",
30
+ "# Is there a settings file? \n",
31
+ "if os.path.exists(filePathToSettingsFile):\n",
32
+ " # Yes there is so load settings from there\n",
33
+ " \n",
34
+ " print(f'Loading settings from {filePathToSettingsFile}')\n",
35
+ " f = open(filePathToSettingsFile)\n",
36
+ " settingsJson = json.load(f)\n",
37
+ " del f\n",
38
+ "\n",
39
+ " for key in settingsJson:\n",
40
+ " os.environ[key] = settingsJson[key]\n",
41
+ " \n",
42
+ " del settingsJson\n",
43
+ "else: \n",
44
+ " # Set variables manually\n",
45
+ " \n",
46
+ " print('Setting variables manually as there is not ai.json settings file')\n",
47
+ "\n",
48
+ " # Update the variables below with your own settings\n",
49
+ " os.environ['REQUESTS_CA_BUNDLE'] = '../../env/ZCert.pem' \n",
50
+ " os.environ['HUGGING_FACE_API_KEY'] = 'Get here: https://huggingface.co/settings/tokens'\n",
51
+ " os.environ['OPENAI_API_KEY'] = 'Get here: https://platform.openai.com/account/api-keys'\n",
52
+ " os.environ[\"SERPAPI_API_KEY\"] = 'serpapi KEY, Get here: https://serpapi.com/manage-api-key' "
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": 3,
58
+ "metadata": {},
59
+ "outputs": [
60
+ {
61
+ "name": "stderr",
62
+ "output_type": "stream",
63
+ "text": [
64
+ "c:\\sc\\ai\\rag-demo-1\\.venv\\lib\\site-packages\\pinecone\\index.py:4: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
65
+ " from tqdm.autonotebook import tqdm\n"
66
+ ]
67
+ }
68
+ ],
69
+ "source": [
70
+ "import os\n",
71
+ "import pinecone\n",
72
+ "from langchain.chains import RetrievalQA\n",
73
+ "from langchain.embeddings import OpenAIEmbeddings\n",
74
+ "from langchain.llms import OpenAI\n",
75
+ "from langchain.vectorstores import Pinecone\n",
76
+ "import gradio as gr"
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "execution_count": 4,
82
+ "metadata": {},
83
+ "outputs": [
84
+ {
85
+ "name": "stderr",
86
+ "output_type": "stream",
87
+ "text": [
88
+ "c:\\sc\\ai\\rag-demo-1\\.venv\\lib\\site-packages\\langchain\\vectorstores\\pinecone.py:59: UserWarning: Passing in `embedding` as a Callable is deprecated. Please pass in an Embeddings object instead.\n",
89
+ " warnings.warn(\n"
90
+ ]
91
+ }
92
+ ],
93
+ "source": [
94
+ "embeddings = OpenAIEmbeddings()\n",
95
+ "\n",
96
+ "course = \"Roman History\"\n",
97
+ "if course == \"Roman History\":\n",
98
+ " pinecone.init(api_key=os.environ[\"PINECONE_API_KEY_2\"], environment=os.environ[\"PINECONE_API_ENV_2\"])\n",
99
+ " index = pinecone.Index(\"rag-demo-1-history-rome\")\n",
100
+ " vector_store = Pinecone(index, embeddings.embed_query, \"text\")\n",
101
+ " "
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "execution_count": 5,
107
+ "metadata": {},
108
+ "outputs": [],
109
+ "source": [
110
+ "llm = OpenAI(temperature=0)\n",
111
+ "qa = RetrievalQA.from_chain_type(llm=llm, chain_type=\"stuff\", retriever=vector_store.as_retriever())\n",
112
+ "\n",
113
+ "query = input(\"Who was ceasar and why whas he noteable?\")\n",
114
+ "answer = qa.run(query)\n",
115
+ "# print(answer)\n",
116
+ "# print(\"\\nWhat else can I help you with:\")\n",
117
+ "\n",
118
+ "# while True:\n",
119
+ "# query = input(\"Who was ceasar and why whas he notable?\")\n",
120
+ "# answer = qa.run(query)\n",
121
+ "# print(answer)\n",
122
+ "# print(\"\\nWhat else can I help you with:\")"
123
+ ]
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "execution_count": null,
128
+ "metadata": {},
129
+ "outputs": [],
130
+ "source": [
131
+ "qa = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), chain_type=\"stuff\", retriever=vector_store.as_retriever())\n",
132
+ "\n",
133
+ "print(\"Connector development help bot. What do you want to know?\")\n",
134
+ "while True:\n",
135
+ " query = input(\"\")\n",
136
+ " answer = qa.run(query)\n",
137
+ " print(answer)\n",
138
+ " print(\"\\nWhat else can I help you with:\")"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": 3,
144
+ "metadata": {},
145
+ "outputs": [
146
+ {
147
+ "name": "stdout",
148
+ "output_type": "stream",
149
+ "text": [
150
+ "Running on local URL: http://127.0.0.1:7860\n",
151
+ "\n",
152
+ "To create a public link, set `share=True` in `launch()`.\n"
153
+ ]
154
+ },
155
+ {
156
+ "data": {
157
+ "text/html": [
158
+ "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
159
+ ],
160
+ "text/plain": [
161
+ "<IPython.core.display.HTML object>"
162
+ ]
163
+ },
164
+ "metadata": {},
165
+ "output_type": "display_data"
166
+ },
167
+ {
168
+ "data": {
169
+ "text/plain": []
170
+ },
171
+ "execution_count": 3,
172
+ "metadata": {},
173
+ "output_type": "execute_result"
174
+ }
175
+ ],
176
+ "source": [
177
+ "def ask_question(openAIKey, prompt, question):\n",
178
+ " return \"Your question is \" + question + \"!!\"\n",
179
+ "\n",
180
+ "iface = gr.Interface(fn=ask_question, \n",
181
+ " inputs=[\n",
182
+ " gr.Textbox(label=\"OpenAI Key\", placeholder=\"Paste your OpenAI key here\"),\n",
183
+ " gr.TextArea(label=\"Prompt\"), \n",
184
+ " gr.TextArea(label=\"Question\", placeholder=\"Type your question here, it will get injected into the prompt at QUESTION\"),\n",
185
+ " ],\n",
186
+ " outputs=\"text\")\n",
187
+ "\n",
188
+ "iface.launch()"
189
+ ]
190
+ }
191
+ ],
192
+ "metadata": {
193
+ "kernelspec": {
194
+ "display_name": ".venv",
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.10.6"
209
+ }
210
+ },
211
+ "nbformat": 4,
212
+ "nbformat_minor": 2
213
+ }
app.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from huggingface_hub import Repository
4
+
5
+ def greet(name):
6
+ # returnValue = "Hello " + name + "!!"
7
+ returnValue = ""
8
+
9
+ textFilename = f'./data/test.txt'
10
+
11
+ try:
12
+
13
+ returnValue = os.listdir(name)
14
+
15
+ except Exception as err:
16
+ returnValue = str(err)
17
+
18
+ return returnValue
19
+
20
+ # try:
21
+
22
+ # with open(textFilename, 'w') as f:
23
+ # f.write(returnValue)
24
+
25
+ # except Exception as err:
26
+ # returnValue = str(err)
27
+ ##################################
28
+ # try:
29
+
30
+ # file = open(textFilename, "r")
31
+ # content = file.read()
32
+ # returnValue = content
33
+ # file.close()
34
+
35
+ # except Exception as err:
36
+ # returnValue = str(err)
37
+
38
+ # return returnValue
39
+
40
+ iface = gr.Interface(fn=greet,
41
+ inputs=gr.TextArea(label="Name"),
42
+ outputs="text")
43
+
44
+ iface.launch()
housekeeping.ipynb ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 3,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stdout",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "Loading settings from ../../env/ai.json\n"
13
+ ]
14
+ }
15
+ ],
16
+ "source": [
17
+ "import os\n",
18
+ "import json\n",
19
+ "\n",
20
+ "# If the file does not exist it'll default to the manual setting see below\n",
21
+ "filePathToSettingsFile = '../../env/ai.json'\n",
22
+ "\n",
23
+ "# Is there a settings file? \n",
24
+ "if os.path.exists(filePathToSettingsFile):\n",
25
+ " # Yes there is so load settings from there\n",
26
+ " \n",
27
+ " print(f'Loading settings from {filePathToSettingsFile}')\n",
28
+ " f = open(filePathToSettingsFile)\n",
29
+ " settingsJson = json.load(f)\n",
30
+ " del f\n",
31
+ "\n",
32
+ " for key in settingsJson:\n",
33
+ " os.environ[key] = settingsJson[key]\n",
34
+ " \n",
35
+ " del settingsJson\n",
36
+ "else: \n",
37
+ " # Set variables manually\n",
38
+ " \n",
39
+ " print('Setting variables manually as there is not ai.json settings file')\n",
40
+ "\n",
41
+ " # Update the variables below with your own settings\n",
42
+ " os.environ['REQUESTS_CA_BUNDLE'] = '../../env/ZCert.pem' \n",
43
+ " os.environ['HUGGING_FACE_API_KEY'] = 'Get here: https://huggingface.co/settings/tokens'\n",
44
+ " os.environ['OPENAI_API_KEY'] = 'Get here: https://platform.openai.com/account/api-keys'\n",
45
+ " os.environ[\"SERPAPI_API_KEY\"] = 'serpapi KEY, Get here: https://serpapi.com/manage-api-key'\n",
46
+ " os.environ[\"PINECONE_API_KEY\"] = 'serpapi KEY, Get here: https://app.pinecone.io/'\n",
47
+ " os.environ[\"PINECONE_API_ENV\"] = 'serpapi KEY, Get here: https://app.pinecone.io/'"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "execution_count": 5,
53
+ "metadata": {},
54
+ "outputs": [],
55
+ "source": [
56
+ "from huggingface_hub import HfFileSystem\n",
57
+ "fs = HfFileSystem()"
58
+ ]
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": 8,
63
+ "metadata": {},
64
+ "outputs": [
65
+ {
66
+ "name": "stdout",
67
+ "output_type": "stream",
68
+ "text": [
69
+ "0\n"
70
+ ]
71
+ }
72
+ ],
73
+ "source": [
74
+ "list = fs.glob(\"thrag/rag-demo-1/*\")\n",
75
+ "print(len(list))"
76
+ ]
77
+ }
78
+ ],
79
+ "metadata": {
80
+ "kernelspec": {
81
+ "display_name": ".venv",
82
+ "language": "python",
83
+ "name": "python3"
84
+ },
85
+ "language_info": {
86
+ "codemirror_mode": {
87
+ "name": "ipython",
88
+ "version": 3
89
+ },
90
+ "file_extension": ".py",
91
+ "mimetype": "text/x-python",
92
+ "name": "python",
93
+ "nbconvert_exporter": "python",
94
+ "pygments_lexer": "ipython3",
95
+ "version": "3.10.6"
96
+ }
97
+ },
98
+ "nbformat": 4,
99
+ "nbformat_minor": 2
100
+ }
vector-stores-create-1.ipynb ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 3,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stdout",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "Loading settings from ../../env/ai.json\n"
13
+ ]
14
+ }
15
+ ],
16
+ "source": [
17
+ "import os\n",
18
+ "import json\n",
19
+ "\n",
20
+ "# If the file does not exist it'll default to the manual setting see below\n",
21
+ "filePathToSettingsFile = '../../env/ai.json'\n",
22
+ "\n",
23
+ "# Is there a settings file? \n",
24
+ "if os.path.exists(filePathToSettingsFile):\n",
25
+ " # Yes there is so load settings from there\n",
26
+ " \n",
27
+ " print(f'Loading settings from {filePathToSettingsFile}')\n",
28
+ " f = open(filePathToSettingsFile)\n",
29
+ " settingsJson = json.load(f)\n",
30
+ " del f\n",
31
+ "\n",
32
+ " for key in settingsJson:\n",
33
+ " os.environ[key] = settingsJson[key]\n",
34
+ " \n",
35
+ " del settingsJson\n",
36
+ "else: \n",
37
+ " # Set variables manually\n",
38
+ " \n",
39
+ " print('Setting variables manually as there is not ai.json settings file')\n",
40
+ "\n",
41
+ " # Update the variables below with your own settings\n",
42
+ " os.environ['REQUESTS_CA_BUNDLE'] = '../../env/ZCert.pem' \n",
43
+ " os.environ['HUGGING_FACE_API_KEY'] = 'Get here: https://huggingface.co/settings/tokens'\n",
44
+ " os.environ['OPENAI_API_KEY'] = 'Get here: https://platform.openai.com/account/api-keys'\n",
45
+ " os.environ[\"SERPAPI_API_KEY\"] = 'serpapi KEY, Get here: https://serpapi.com/manage-api-key' "
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "markdown",
50
+ "metadata": {},
51
+ "source": [
52
+ "# Load data"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": 4,
58
+ "metadata": {},
59
+ "outputs": [],
60
+ "source": [
61
+ "# https://github.com/gkamradt/langchain-tutorials/blob/main/data_generation/Ask%20A%20Book%20Questions.ipynb\n",
62
+ "from langchain.document_loaders import UnstructuredPDFLoader, OnlinePDFLoader, PyPDFLoader\n",
63
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "execution_count": 57,
69
+ "metadata": {},
70
+ "outputs": [],
71
+ "source": [
72
+ "import glob\n",
73
+ "from pdfminer.high_level import extract_text\n",
74
+ "\n",
75
+ "rootFolder = '../rag-demo-1-data/'\n",
76
+ "literatureFolder = 'literature/'\n",
77
+ "historyOfRomeFolder = 'history-roman/'\n",
78
+ "\n",
79
+ "currentFolder = f'{rootFolder}{literatureFolder}'\n"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": 58,
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "for filename in glob.glob(f\"{currentFolder}*.pdf\"):\n",
89
+ "\n",
90
+ " print(f'About to extract {filename}')\n",
91
+ " try:\n",
92
+ " text = extract_text(filename)\n",
93
+ " text = text.encode('ascii', errors='ignore').decode('ascii')\n",
94
+ "\n",
95
+ " textFilename = f'{filename}.txt'\n",
96
+ " print(textFilename)\n",
97
+ " with open(textFilename, 'w') as f:\n",
98
+ " f.write(text)\n",
99
+ " \n",
100
+ " os.rename(filename, f\"{filename}.done\")\n",
101
+ " except Exception as err:\n",
102
+ " print(f\"Error with file {filename} {err}\")"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": 59,
108
+ "metadata": {},
109
+ "outputs": [],
110
+ "source": [
111
+ "from langchain.document_loaders import DirectoryLoader\n",
112
+ "from langchain.document_loaders import TextLoader\n",
113
+ "\n",
114
+ "loader = DirectoryLoader(currentFolder, glob=\"**/*.txt\", loader_cls=TextLoader)\n",
115
+ "docs = loader.load()\n",
116
+ "\n",
117
+ "print(len(docs))\n",
118
+ "print(len(docs[0].page_content))"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "execution_count": 61,
124
+ "metadata": {},
125
+ "outputs": [
126
+ {
127
+ "name": "stdout",
128
+ "output_type": "stream",
129
+ "text": [
130
+ "16596\n"
131
+ ]
132
+ }
133
+ ],
134
+ "source": [
135
+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
136
+ "texts = text_splitter.split_documents(docs)\n",
137
+ "print(len(texts))"
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "execution_count": 62,
143
+ "metadata": {},
144
+ "outputs": [
145
+ {
146
+ "name": "stdout",
147
+ "output_type": "stream",
148
+ "text": [
149
+ "{'source': '..\\\\rag-demo-1-data\\\\literature\\\\moby-dick.pdf.txt'}\n"
150
+ ]
151
+ }
152
+ ],
153
+ "source": [
154
+ "#print(texts[8000].page_content)\n",
155
+ "print(texts[8000].metadata)"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "markdown",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Create embeddings"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": 63,
168
+ "metadata": {},
169
+ "outputs": [],
170
+ "source": [
171
+ "from langchain.vectorstores import Pinecone\n",
172
+ "from langchain.embeddings import OpenAIEmbeddings\n",
173
+ "import pinecone\n",
174
+ "\n",
175
+ "embeddings = OpenAIEmbeddings(openai_api_key=os.environ['OPENAI_API_KEY'])"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "execution_count": 64,
181
+ "metadata": {},
182
+ "outputs": [],
183
+ "source": [
184
+ "index_name = \"\" # put in the name of your pinecone index here\n",
185
+ "pinecone.init(api_key='', environment='gcp-starter')"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 65,
191
+ "metadata": {},
192
+ "outputs": [],
193
+ "source": [
194
+ "docsearch = Pinecone.from_documents(texts, embeddings, index_name=index_name)"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "execution_count": 66,
200
+ "metadata": {},
201
+ "outputs": [],
202
+ "source": [
203
+ "query = \"What is moby dick?\"\n",
204
+ "searchResult = docsearch.similarity_search(query, k=5)"
205
+ ]
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "execution_count": 67,
210
+ "metadata": {},
211
+ "outputs": [
212
+ {
213
+ "name": "stdout",
214
+ "output_type": "stream",
215
+ "text": [
216
+ "..\\rag-demo-1-data\\literature\\moby-dick.pdf.txt\n",
217
+ "Moby Dick By Herman MelvilleDownload free eBooks of classic literature, books and \n",
218
+ "novels at Planet eBook. Subscribe to our free eBooks blog \n",
219
+ "and email newsletter.\fETYMOLOGY.(Supplied by a Late Consumptive Usher to a Grammar \n",
220
+ "School)The pale Usherthreadbare in coat, heart, body, and \n",
221
+ "brain; I see him now. He was ever dusting his old lexicons \n",
222
+ "and grammars, with a queer handkerchief, mockingly em-\n",
223
+ "bellished with all the gay flags of all the known nations of \n",
224
+ "the world. He loved to dust his old grammars; it somehow \n",
225
+ "mildly reminded him of his mortality.While you take in hand to school others, and to teach them \n",
226
+ "by what name a whale-fish is to be called in our tongue \n",
227
+ "leaving out, through ignorance, the letter H, which almost \n",
228
+ "alone maketh the signification of the word, you deliver that \n",
229
+ "which is not true. HACKLUYTWHALE. Sw. and Dan. HVAL. This animal is named from \n",
230
+ "roundness or rolling; for in Dan. HVALT is arched or vaulted.\n"
231
+ ]
232
+ }
233
+ ],
234
+ "source": [
235
+ "\n",
236
+ "print(searchResult[0].metadata['source'])\n",
237
+ "print(searchResult[0].page_content)"
238
+ ]
239
+ }
240
+ ],
241
+ "metadata": {
242
+ "kernelspec": {
243
+ "display_name": "Python 3",
244
+ "language": "python",
245
+ "name": "python3"
246
+ },
247
+ "language_info": {
248
+ "codemirror_mode": {
249
+ "name": "ipython",
250
+ "version": 3
251
+ },
252
+ "file_extension": ".py",
253
+ "mimetype": "text/x-python",
254
+ "name": "python",
255
+ "nbconvert_exporter": "python",
256
+ "pygments_lexer": "ipython3",
257
+ "version": "3.10.6"
258
+ }
259
+ },
260
+ "nbformat": 4,
261
+ "nbformat_minor": 2
262
+ }
vector-stores-query.ipynb ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stdout",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "Loading settings from ../../env/ai.json\n"
13
+ ]
14
+ }
15
+ ],
16
+ "source": [
17
+ "import os\n",
18
+ "import json\n",
19
+ "\n",
20
+ "# If the file does not exist it'll default to the manual setting see below\n",
21
+ "filePathToSettingsFile = '../../env/ai.json'\n",
22
+ "\n",
23
+ "# Is there a settings file? \n",
24
+ "if os.path.exists(filePathToSettingsFile):\n",
25
+ " # Yes there is so load settings from there\n",
26
+ " \n",
27
+ " print(f'Loading settings from {filePathToSettingsFile}')\n",
28
+ " f = open(filePathToSettingsFile)\n",
29
+ " settingsJson = json.load(f)\n",
30
+ " del f\n",
31
+ "\n",
32
+ " for key in settingsJson:\n",
33
+ " os.environ[key] = settingsJson[key]\n",
34
+ " \n",
35
+ " del settingsJson\n",
36
+ "else: \n",
37
+ " # Set variables manually\n",
38
+ " \n",
39
+ " print('Setting variables manually as there is not ai.json settings file')\n",
40
+ "\n",
41
+ " # Update the variables below with your own settings\n",
42
+ " os.environ['REQUESTS_CA_BUNDLE'] = '../../env/ZCert.pem' \n",
43
+ " os.environ['HUGGING_FACE_API_KEY'] = 'Get here: https://huggingface.co/settings/tokens'\n",
44
+ " os.environ['OPENAI_API_KEY'] = 'Get here: https://platform.openai.com/account/api-keys'\n",
45
+ " os.environ[\"SERPAPI_API_KEY\"] = 'serpapi KEY, Get here: https://serpapi.com/manage-api-key' "
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "execution_count": 10,
51
+ "metadata": {},
52
+ "outputs": [],
53
+ "source": [
54
+ "from langchain.vectorstores import Pinecone\n",
55
+ "from langchain.embeddings import OpenAIEmbeddings\n",
56
+ "import pinecone\n",
57
+ "\n",
58
+ "embeddings = OpenAIEmbeddings(openai_api_key=os.environ['OPENAI_API_KEY'])\n"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": 12,
64
+ "metadata": {},
65
+ "outputs": [],
66
+ "source": [
67
+ "index_name = \"rag-demo-1-history-rome\"\n",
68
+ "text_field = \"text\"\n",
69
+ "\n",
70
+ "index = pinecone.Index(index_name)\n",
71
+ "vectorstore = Pinecone(\n",
72
+ " index, embeddings.embed_query, text_field\n",
73
+ ")"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "execution_count": 22,
79
+ "metadata": {},
80
+ "outputs": [],
81
+ "source": [
82
+ "query = \"When was Ceasar born?\"\n",
83
+ "\n",
84
+ "result = vectorstore.similarity_search(\n",
85
+ " query, # our search query\n",
86
+ " k=3 # return 3 most relevant docs\n",
87
+ ")"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": 23,
93
+ "metadata": {},
94
+ "outputs": [
95
+ {
96
+ "name": "stdout",
97
+ "output_type": "stream",
98
+ "text": [
99
+ "3\n",
100
+ "page_content='The situation in Rome. While Pompey was adding to his\\nmilitary reputation in the East he was regarded with jealous\\nand anxious eyes not only by the Senate but also by the other\\nchampions of the popular party, Crassus who found his wealth\\nno match for Pompeys military achievements, and Caius Julius\\nCaesar who was rapidly coming to be one of the leading figures in\\nRoman public life. Caesar was born in 100 B. C., of the patrician [162]\\ngens of the Julii, but since his aunt was the wife of Marius,\\nand he himself had married the daughter of Cinna, his lot was\\ncast with the Populares. As a young man he had distinguished\\nhimself by refusing to divorce his wife at Sullas behest, whereat\\nSulla was with difficulty induced to spare his life, saying that he\\nsaw in him many a Marius. For the time being Caesar judged it\\nprudent to withdraw from Rome to Rhodes. While in the East\\nhe was captured by pirates, and after being ransomed, fulfilled' metadata={'source': '..\\\\rag-demo-1-data\\\\history-roman\\\\3. A History of Rome to 565 A. D. author Arthur Edward Romilly Boak.pdf.txt'}\n",
101
+ "##\n",
102
+ "page_content='13 After the adoption his full name was Caius Julius Caesar Octavianus.\\nAlthough he was known as Caesar by his contemporaries, it is more convenient\\nto refer to him henceforth as Octavian, to distinguish him from his adoptive\\nfather.\\n\\n[187]\\n\\n\\x0c222\\n\\nA History of Rome to 565 A. D.\\n\\nCaesars murder, was about to leave Italy to join Brutus when he\\nheard of the changed situation in Rome and returned to assume\\nthe leadership of the republican party. Antony left Rome for\\nthe Cisalpine province early in December, 44 B. C., and Cicero\\ninduced the Senate to enter into a coalition with Octavian against\\nhim.\\nIn his Philippic Orations he gave full vent to his bitter\\nhatred of Antony and so aroused the latters undying enmity.' metadata={'source': '..\\\\rag-demo-1-data\\\\history-roman\\\\3. A History of Rome to 565 A. D. author Arthur Edward Romilly Boak.pdf.txt'}\n",
103
+ "##\n",
104
+ "page_content='[180]\\n\\nIV. THE DICTATORSHIP OF JULIUS CAESAR: 4644 B. C.\\n\\n213\\n\\n46, when he celebrated his triumph over the Gauls and his other\\nnon-Roman enemies. He assumed it again after Munda in the\\nfollowing year.' metadata={'source': '..\\\\rag-demo-1-data\\\\history-roman\\\\3. A History of Rome to 565 A. D. author Arthur Edward Romilly Boak.pdf.txt'}\n"
105
+ ]
106
+ }
107
+ ],
108
+ "source": [
109
+ "print(len(result))\n",
110
+ "\n",
111
+ "print(result[0])\n",
112
+ "print('##')\n",
113
+ "print(result[1])\n",
114
+ "print('##')\n",
115
+ "print(result[2])"
116
+ ]
117
+ }
118
+ ],
119
+ "metadata": {
120
+ "kernelspec": {
121
+ "display_name": ".venv",
122
+ "language": "python",
123
+ "name": "python3"
124
+ },
125
+ "language_info": {
126
+ "codemirror_mode": {
127
+ "name": "ipython",
128
+ "version": 3
129
+ },
130
+ "file_extension": ".py",
131
+ "mimetype": "text/x-python",
132
+ "name": "python",
133
+ "nbconvert_exporter": "python",
134
+ "pygments_lexer": "ipython3",
135
+ "version": "3.10.6"
136
+ }
137
+ },
138
+ "nbformat": 4,
139
+ "nbformat_minor": 2
140
+ }