File size: 8,493 Bytes
509030b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from os import environ\n",
    "from dotenv import load_dotenv\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain_mistralai import MistralAIEmbeddings\n",
    "from langchain_core.pydantic_v1 import BaseModel, Field\n",
    "from langchain_community.chat_models import ChatAnyscale\n",
    "from langchain.output_parsers import PydanticOutputParser\n",
    "from langchain_experimental.text_splitter import SemanticChunker\n",
    "\n",
    "load_dotenv()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SVOTriple(BaseModel):\n",
    "    \"\"\"\n",
    "    Represents a subject-verb-object triple in a sentence.\n",
    "\n",
    "    Attributes:\n",
    "        subject (str): The subject of the sentence.\n",
    "        verb (str): The verb of the sentence.\n",
    "        object (str): The object of the sentence.\n",
    "    \"\"\"\n",
    "\n",
    "    subject: str = Field(description=\"The subject of the sentence\")\n",
    "    verb: str = Field(description=\"The verb of the sentence\")\n",
    "    object: str = Field(description=\"The object of the sentence\")\n",
    "\n",
    "\n",
    "class SVOTripleList(BaseModel):\n",
    "    \"\"\"\n",
    "    Represents a list of Subject-Verb-Object (SVO) triples.\n",
    "    \"\"\"\n",
    "\n",
    "    triples: list[SVOTriple] = Field(description=\"List of SVO triples\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ChatAnyscale(\n",
    "    anyscale_api_key=environ[\"ANYSCALE_API_KEY\"],\n",
    "    model_name=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
    "    temperature=0,\n",
    "    max_tokens=4096,\n",
    ")\n",
    "\n",
    "embeddings = MistralAIEmbeddings(\n",
    "    mistral_api_key=environ[\"MISTRAL_API_KEY\"],\n",
    ")\n",
    "\n",
    "text_splitter = SemanticChunker(embeddings)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"./patanjali/the-yoga-sutras.md\") as file:\n",
    "    contents = file.read()\n",
    "\n",
    "docs = text_splitter.create_documents([contents])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "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",
    "# Additional Instructions\n",
    "1. Carefully read the provided data, text, or information to understand the context and the dynamics between entities.\n",
    "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",
    "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",
    "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",
    "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",
    "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",
    "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",
    "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",
    "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",
    "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",
    "# Response format\n",
    "{response_format}\n",
    "# Data to extract\n",
    "```\n",
    "{data}\n",
    "```\n",
    "\"\"\"\n",
    "\n",
    "parser = PydanticOutputParser(pydantic_object=SVOTripleList)\n",
    "\n",
    "prompt = PromptTemplate(\n",
    "    template=template,\n",
    "    input_variables=[\"data\"],\n",
    "    partial_variables={\"response_format\": parser.get_format_instructions()},\n",
    ")\n",
    "\n",
    "chain = prompt | model | parser\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = []\n",
    "\n",
    "for doc in docs:\n",
    "    try:\n",
    "        result = chain.invoke({\"data\": data})\n",
    "    except Exception as e:\n",
    "        print(\"Error in processing document:\", e)\n",
    "        print(\"Retrying\")\n",
    "        try:\n",
    "            result = chain.invoke({\"data\": data})\n",
    "        except Exception as e:\n",
    "            print(\"Error in processing document:\", e)\n",
    "            continue\n",
    "    output.append(result)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "\n",
    "with open(\"patanjali_svo.pkl\", \"wb\") as file:\n",
    "    pickle.dump(output, file)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = [triple.dict() for svo_list in output for triple in svo_list.triples]\n",
    "\n",
    "df = pd.DataFrame(data)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.to_csv(\"patanjali_svo.csv\", index=False)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import networkx as nx\n",
    "\n",
    "G = nx.DiGraph()\n",
    "\n",
    "for index, row in df.iterrows():\n",
    "    subject = row[\"subject\"]\n",
    "    verb = row[\"verb\"]\n",
    "    obj = row[\"object\"]\n",
    "\n",
    "    if not G.has_node(subject):\n",
    "        G.add_node(subject)\n",
    "    if not G.has_node(obj):\n",
    "        G.add_node(obj)\n",
    "\n",
    "    G.add_edge(subject, obj, label=verb)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "nx.draw(G, with_labels=True)\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from networkx import write_gexf\n",
    "\n",
    "write_gexf(G, \"patanjali_svo.gexf\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "hermes-toth-Mo6e-kMA-py3.12",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}