{ "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 }