alexandreteles commited on
Commit
509030b
1 Parent(s): 28b01d6

information extraction pipeline

Browse files
Files changed (6) hide show
  1. .gitignore +2 -0
  2. .vscode/settings.json +9 -2
  3. information_extraction.ipynb +242 -0
  4. poetry.lock +0 -0
  5. pyproject.toml +39 -0
  6. setup.sh +15 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ env.sh
2
+ .env
.vscode/settings.json CHANGED
@@ -1,3 +1,10 @@
1
  {
2
- "markdownlint.run": "onSave"
3
- }
 
 
 
 
 
 
 
 
1
  {
2
+ "spellright.language": [
3
+ "pt"
4
+ ],
5
+ "spellright.documentTypes": [
6
+ "latex",
7
+ "plaintext"
8
+ ],
9
+ "remote.autoForwardPortsFallback": 0
10
+ }
information_extraction.ipynb ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import pandas as pd\n",
10
+ "from os import environ\n",
11
+ "from dotenv import load_dotenv\n",
12
+ "from langchain.prompts import PromptTemplate\n",
13
+ "from langchain_mistralai import MistralAIEmbeddings\n",
14
+ "from langchain_core.pydantic_v1 import BaseModel, Field\n",
15
+ "from langchain_community.chat_models import ChatAnyscale\n",
16
+ "from langchain.output_parsers import PydanticOutputParser\n",
17
+ "from langchain_experimental.text_splitter import SemanticChunker\n",
18
+ "\n",
19
+ "load_dotenv()\n"
20
+ ]
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "execution_count": null,
25
+ "metadata": {},
26
+ "outputs": [],
27
+ "source": [
28
+ "class SVOTriple(BaseModel):\n",
29
+ " \"\"\"\n",
30
+ " Represents a subject-verb-object triple in a sentence.\n",
31
+ "\n",
32
+ " Attributes:\n",
33
+ " subject (str): The subject of the sentence.\n",
34
+ " verb (str): The verb of the sentence.\n",
35
+ " object (str): The object of the sentence.\n",
36
+ " \"\"\"\n",
37
+ "\n",
38
+ " subject: str = Field(description=\"The subject of the sentence\")\n",
39
+ " verb: str = Field(description=\"The verb of the sentence\")\n",
40
+ " object: str = Field(description=\"The object of the sentence\")\n",
41
+ "\n",
42
+ "\n",
43
+ "class SVOTripleList(BaseModel):\n",
44
+ " \"\"\"\n",
45
+ " Represents a list of Subject-Verb-Object (SVO) triples.\n",
46
+ " \"\"\"\n",
47
+ "\n",
48
+ " triples: list[SVOTriple] = Field(description=\"List of SVO triples\")\n"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "metadata": {},
55
+ "outputs": [],
56
+ "source": [
57
+ "model = ChatAnyscale(\n",
58
+ " anyscale_api_key=environ[\"ANYSCALE_API_KEY\"],\n",
59
+ " model_name=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
60
+ " temperature=0,\n",
61
+ " max_tokens=4096,\n",
62
+ ")\n",
63
+ "\n",
64
+ "embeddings = MistralAIEmbeddings(\n",
65
+ " mistral_api_key=environ[\"MISTRAL_API_KEY\"],\n",
66
+ ")\n",
67
+ "\n",
68
+ "text_splitter = SemanticChunker(embeddings)\n"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "with open(\"./patanjali/the-yoga-sutras.md\") as file:\n",
78
+ " contents = file.read()\n",
79
+ "\n",
80
+ "docs = text_splitter.create_documents([contents])\n"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": null,
86
+ "metadata": {},
87
+ "outputs": [],
88
+ "source": [
89
+ "template = \"\"\"You are an expert entity extractor that always maintains as much semantic meaning as possible. You use inference or deduction whenever necessary to supply missing or omitted data. Examine the provided data, text, or information and generate a list of any entities or objects that match the requested format.\n",
90
+ "# Additional Instructions\n",
91
+ "1. Carefully read the provided data, text, or information to understand the context and the dynamics between entities.\n",
92
+ "2. Identify all subjects, verbs, and objects within the sentences, keeping an eye out for complex sentences that might contain multiple entities or actions.\n",
93
+ "3. Extract all Subject-Verb-Object (SVO) triples from each sentence or statement. Ensure to include all possible combinations in sentences with multiple subjects, verbs, or objects, creating separate triples for each variation.\n",
94
+ "4. When you encounter pronouns (e.g., he, she, they) or other words that do not clearly name an entity but refer to one mentioned in the text, substitute the pronoun or vague term with the correct, specific name of the entity it refers to. Use the context provided in the text to accurately determine to which entity the pronoun or term is referring. For example, if a sentence says \"They offer great value,\" and \"they\" refers to \"The new smartphones launched,\" then replace \"they\" with \"The new smartphones launched\" in your SVO triple.\n",
95
+ "5. If a sentence contains conjunctions like \"and\" or \"or\" that link subjects, verbs, or objects, split these into separate entities for your SVO triples.\n",
96
+ "6. Use your inference skills to complete the triples when the sentence structure is implicit, or some SVO parts are omitted but can be inferred from the context. This includes continuing to utilize specific names for entities rather than pronouns when the subject or object refers back to something previously mentioned.\n",
97
+ "7. In the case of compound verbs or objects where a series of actions or objects are listed for a single subject, create a distinct triple for each action or object linked to the subject. \n",
98
+ "8. Consider indirect objects or prepositional phrases as part of the object in your SVO triples if they add significant meaning to the overall action described.\n",
99
+ "9. For verbs that are part of phrasal verbs or require prepositions to convey the full meaning (e.g., \"look after\"), include these as part of the verb in your SVO triple.\n",
100
+ "10. Double-check your list of triples to ensure comprehensiveness and accuracy, especially in dense or complex paragraphs that may contain multiple actions and entities interacting.\n",
101
+ "# Response format\n",
102
+ "{response_format}\n",
103
+ "# Data to extract\n",
104
+ "```\n",
105
+ "{data}\n",
106
+ "```\n",
107
+ "\"\"\"\n",
108
+ "\n",
109
+ "parser = PydanticOutputParser(pydantic_object=SVOTripleList)\n",
110
+ "\n",
111
+ "prompt = PromptTemplate(\n",
112
+ " template=template,\n",
113
+ " input_variables=[\"data\"],\n",
114
+ " partial_variables={\"response_format\": parser.get_format_instructions()},\n",
115
+ ")\n",
116
+ "\n",
117
+ "chain = prompt | model | parser\n"
118
+ ]
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "execution_count": null,
123
+ "metadata": {},
124
+ "outputs": [],
125
+ "source": [
126
+ "output = []\n",
127
+ "\n",
128
+ "for doc in docs:\n",
129
+ " try:\n",
130
+ " result = chain.invoke({\"data\": data})\n",
131
+ " except Exception as e:\n",
132
+ " print(\"Error in processing document:\", e)\n",
133
+ " print(\"Retrying\")\n",
134
+ " try:\n",
135
+ " result = chain.invoke({\"data\": data})\n",
136
+ " except Exception as e:\n",
137
+ " print(\"Error in processing document:\", e)\n",
138
+ " continue\n",
139
+ " output.append(result)\n"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": null,
145
+ "metadata": {},
146
+ "outputs": [],
147
+ "source": [
148
+ "import pickle\n",
149
+ "\n",
150
+ "with open(\"patanjali_svo.pkl\", \"wb\") as file:\n",
151
+ " pickle.dump(output, file)\n"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "execution_count": null,
157
+ "metadata": {},
158
+ "outputs": [],
159
+ "source": [
160
+ "data = [triple.dict() for svo_list in output for triple in svo_list.triples]\n",
161
+ "\n",
162
+ "df = pd.DataFrame(data)\n"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": null,
168
+ "metadata": {},
169
+ "outputs": [],
170
+ "source": [
171
+ "df.to_csv(\"patanjali_svo.csv\", index=False)\n"
172
+ ]
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "execution_count": null,
177
+ "metadata": {},
178
+ "outputs": [],
179
+ "source": [
180
+ "import networkx as nx\n",
181
+ "\n",
182
+ "G = nx.DiGraph()\n",
183
+ "\n",
184
+ "for index, row in df.iterrows():\n",
185
+ " subject = row[\"subject\"]\n",
186
+ " verb = row[\"verb\"]\n",
187
+ " obj = row[\"object\"]\n",
188
+ "\n",
189
+ " if not G.has_node(subject):\n",
190
+ " G.add_node(subject)\n",
191
+ " if not G.has_node(obj):\n",
192
+ " G.add_node(obj)\n",
193
+ "\n",
194
+ " G.add_edge(subject, obj, label=verb)\n"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "execution_count": null,
200
+ "metadata": {},
201
+ "outputs": [],
202
+ "source": [
203
+ "import matplotlib.pyplot as plt\n",
204
+ "\n",
205
+ "nx.draw(G, with_labels=True)\n",
206
+ "plt.show()\n"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": null,
212
+ "metadata": {},
213
+ "outputs": [],
214
+ "source": [
215
+ "from networkx import write_gexf\n",
216
+ "\n",
217
+ "write_gexf(G, \"patanjali_svo.gexf\")\n"
218
+ ]
219
+ }
220
+ ],
221
+ "metadata": {
222
+ "kernelspec": {
223
+ "display_name": "hermes-toth-Mo6e-kMA-py3.12",
224
+ "language": "python",
225
+ "name": "python3"
226
+ },
227
+ "language_info": {
228
+ "codemirror_mode": {
229
+ "name": "ipython",
230
+ "version": 3
231
+ },
232
+ "file_extension": ".py",
233
+ "mimetype": "text/x-python",
234
+ "name": "python",
235
+ "nbconvert_exporter": "python",
236
+ "pygments_lexer": "ipython3",
237
+ "version": "3.11.9"
238
+ }
239
+ },
240
+ "nbformat": 4,
241
+ "nbformat_minor": 2
242
+ }
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "hermes-toth"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["Alexandre Teles <[email protected]>"]
6
+ readme = "README.md"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = ">=3.11,<3.12"
10
+ jupyterlab = "^4.1.1"
11
+ notebook = "^7.0.8"
12
+ pandas = "^2.2.0"
13
+ pydantic = "^2.6.1"
14
+ numpy = "^1.26.4"
15
+ numba = "^0.59.0"
16
+ setuptools = "^69.1.0"
17
+ langchain = "^0.1.7"
18
+ ipywidgets = "^8.1.2"
19
+ tqdm = "^4.66.2"
20
+ langchain-mistralai = "^0.0.4"
21
+ python-dotenv = "^1.0.1"
22
+ pyarrow = "^15.0.0"
23
+ langchain-openai = "^0.0.6"
24
+ unstructured = "^0.12.4"
25
+ markdown = "^3.5.2"
26
+ transformers = {extras = ["torch"], version = "^4.37.2"}
27
+ langchain-experimental = "^0.0.51"
28
+ networkx = "^3.2.1"
29
+ matplotlib = "^3.8.3"
30
+
31
+
32
+ [[tool.poetry.source]]
33
+ name = "nvidia"
34
+ url = "https://pypi.nvidia.com"
35
+ priority = "supplemental"
36
+
37
+ [build-system]
38
+ requires = ["poetry-core"]
39
+ build-backend = "poetry.core.masonry.api"
setup.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ echo "Setting up the environment..."
3
+ # echo "Installing llama-cpp-python..."
4
+
5
+ # CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python
6
+
7
+ # echo "Installing spacy model..."
8
+
9
+ poetry run python -m spacy download en_core_web_trf
10
+
11
+ echo "Installing nltk data..."
12
+
13
+ poetry run python -m nltk.downloader all
14
+
15
+ echo "Environment setup complete."