Skip to content

Python scraper based on AI

refactored BaseNode and ParseNode

Perinim20d7b69008e0
diff --git a/examples/graph_examples/custom_graph_example.py b/examples/graph_examples/custom_graph_example.py
index e5c4c4a3..4dfbb92b 100644
--- a/examples/graph_examples/custom_graph_example.py
+++ b/examples/graph_examples/custom_graph_example.py
@@ -20,6 +20,34 @@ llm_config = {
}
model = OpenAI(llm_config)
+# fetch_html_node = FetchNode(
+# input="url | local_dir",
+# output=["doc"],
+# node_name="fetch_html"
+# )
+# parse_document_node = ParseNode(
+# input="doc",
+# output=["parsed_doc"],
+# node_name="parse_document"
+# )
+# split_chunks_node = SplitChunksNode(
+# input="parsed_doc | doc",
+# output=["doc_chunks"],
+# node_name="split_chunks"
+# )
+# rag_node = RAGNode(
+# input="user_prompt & (doc_chunks | parsed_doc | doc)",
+# output=["relevant_doc_chunks"],
+# model=model,
+# node_name="rag"
+# )
+# generate_answer_node = GenerateAnswerNode(
+# input="user_prompt & (relevant_doc_chunks | doc_chunks | parsed_doc | doc)",
+# output=["answer"],
+# model=model,
+# node_name="generate_answer"
+# )
+
# define the nodes for the graph
fetch_html_node = FetchHTMLNode("fetch_html")
parse_document_node = ParseNode(doc_type="html", chunks_size=4000, node_name="parse_document")
diff --git a/scrapegraphai/nodes/base_node.py b/scrapegraphai/nodes/base_node.py
index 2eccbea3..daddb394 100644
--- a/scrapegraphai/nodes/base_node.py
+++ b/scrapegraphai/nodes/base_node.py
@@ -2,7 +2,7 @@
Module for creating the basic node
"""
from abc import ABC, abstractmethod
-from typing import List, Dict
+from typing import Optional, List
import re
class BaseNode(ABC):
@@ -39,7 +39,7 @@ class BaseNode(ABC):
raised to indicate the incorrect usage.
"""
- def __init__(self, node_name: str, node_type: str):
+ def __init__(self, node_name: str, node_type: str, input: str, output: List[str], min_input_len: int = 1, model = None):
"""
Initialize the node with a unique identifier and a specified node type.
@@ -51,6 +51,11 @@ class BaseNode(ABC):
ValueError: If node_type is not "node" or "conditional_node".
"""
self.node_name = node_name
+ self.input = input
+ self.output = output
+ self.min_input_len = min_input_len
+ self.model = model
+
if node_type not in ["node", "conditional_node"]:
raise ValueError(
f"node_type must be 'node' or 'conditional_node', got '{node_type}'")
@@ -66,6 +71,20 @@ class BaseNode(ABC):
"""
pass
+ def get_input_keys(self, state: dict) -> List[str]:
+ # Use the _parse_input_keys method to identify which state keys are needed based on the input attribute
+ try:
+ input_keys = self._parse_input_keys(state, self.input)
+ self._validate_input_keys(input_keys)
+ return input_keys
+ except ValueError as e:
+ raise ValueError(f"Error parsing input keys for {self.node_name}: {str(e)}")
+
+
+ def _validate_input_keys(self, input_keys):
+ if len(input_keys) < self.min_input_len:
+ raise ValueError(f"{self.node_name} requires at least {self.min_input_len} input keys, got {len(input_keys)}.")
+
def _parse_input_keys(self, state: dict, expression: str) -> List[str]:
"""
Parses the input keys expression and identifies the corresponding keys
diff --git a/scrapegraphai/nodes/parse_node.py b/scrapegraphai/nodes/parse_node.py
index 09e14ce8..62082bdc 100644
--- a/scrapegraphai/nodes/parse_node.py
+++ b/scrapegraphai/nodes/parse_node.py
@@ -4,6 +4,7 @@ Module for parsing the HTML node
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_transformers import Html2TextTransformer
from .base_node import BaseNode
+from typing import List
class ParseNode(BaseNode):
@@ -28,7 +29,7 @@ class ParseNode(BaseNode):
the specified tags, if provided, and updates the state with the parsed content.
"""
- def __init__(self, doc_type: str = "html", chunks_size: int = 4000, node_name: str = "ParseHTMLNode"):
+ def __init__(self, input: str, output: List[str], node_name: str = "ParseNode"):
"""
Initializes the ParseHTMLNode with a node name.
Args:
@@ -37,9 +38,7 @@ class ParseNode(BaseNode):
node_name (str): name of the node
node_type (str, optional): type of the node
"""
- super().__init__(node_name, "node")
- self.doc_type = doc_type
- self.chunks_size = chunks_size
+ super().__init__(node_name, "node", input, output, 2)
def execute(self, state):
"""
@@ -61,27 +60,25 @@ class ParseNode(BaseNode):
information for parsing is missing.
"""
- print("---PARSING DOCUMENT---")
- try:
- document = state["document"]
- except KeyError as e:
- print(f"Error: {e} not found in state.")
- raise
+ print(f"--- Executing {self.node_name} Node ---")
+
+ # Interpret input keys based on the provided input expression
+ input_keys = self.get_input_keys(state)
+
+ # Fetching data from the state based on the input keys
+ input_data = [state[key] for key in input_keys]
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
- chunk_size=self.chunks_size,
+ chunk_size=4000,
chunk_overlap=0,
)
- # Parse the document based on the specified doc_type
- if self.doc_type == "html":
- docs_transformed = Html2TextTransformer(
- ).transform_documents(document)[0]
- elif self.doc_type == "text":
- docs_transformed = document
+ # Parse the document
+ docs_transformed = Html2TextTransformer(
+ ).transform_documents(input_data[0])[0]
chunks = text_splitter.split_text(docs_transformed.page_content)
- state.update({"parsed_document": chunks})
+ state.update({self.output[0]: chunks})
return state
diff --git a/scrapegraphai/utils/test_node.py b/scrapegraphai/utils/test_node.py
new file mode 100644
index 00000000..97ab43e1
--- /dev/null
+++ b/scrapegraphai/utils/test_node.py
@@ -0,0 +1,15 @@
+from scrapegraphai.nodes import FetchHTMLNode, ParseNode, RAGNode, GenerateAnswerNode
+
+state = {
+ "user_prompt": None,
+ "url": None,
+ "doc": None,
+}
+
+parse_node = ParseNode(
+ input="doc & url",
+ output=["parsed_doc"],
+ node_name="parse_document"
+ )
+
+parse_node.execute(state)
\ No newline at end of file