Skip to content

Python scraper based on AI

removed fetch_html and fetch_text (merged)

Perinimf27e0b4c5ffc
diff --git a/scrapegraphai/nodes/__init__.py b/scrapegraphai/nodes/__init__.py
index 24817b94..cbcd488e 100644
--- a/scrapegraphai/nodes/__init__.py
+++ b/scrapegraphai/nodes/__init__.py
@@ -1,7 +1,7 @@
"""
__init__.py file for node folder
"""
-from .fetch_html_node import FetchHTMLNode
+
from .fetch_node import FetchNode
from .conditional_node import ConditionalNode
from .get_probable_tags_node import GetProbableTagsNode
@@ -9,5 +9,4 @@ from .generate_answer_node import GenerateAnswerNode
from .parse_node import ParseNode
from .rag_node import RAGNode
from .text_to_speech_node import TextToSpeechNode
-from .image_to_text_node import ImageToTextNode
-from .fetch_text_node import FetchTextNode
\ No newline at end of file
+from .image_to_text_node import ImageToTextNode
\ No newline at end of file
diff --git a/scrapegraphai/nodes/fetch_html_node.py b/scrapegraphai/nodes/fetch_html_node.py
deleted file mode 100644
index 14d8fa1a..00000000
--- a/scrapegraphai/nodes/fetch_html_node.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""
-Module for fetching the HTML node
-"""
-from typing import Any
-from langchain_community.document_loaders import AsyncHtmlLoader
-from langchain_core.documents import Document
-from .base_node import BaseNode
-from ..utils.remover import remover
-
-
-def _build_metadata(soup: Any, url: str) -> dict:
- """Build metadata from BeautifulSoup output."""
- metadata = {"source": url}
- if title := soup.find("title"):
- metadata["title"] = title.get_text()
- if description := soup.find("meta", attrs={"name": "description"}):
- metadata["description"] = description.get(
- "content", "No description found.")
- if html := soup.find("html"):
- metadata["language"] = html.get("lang", "No language found.")
- return metadata
-
-
-class FetchHTMLNode(BaseNode):
- """
- A node responsible for fetching the HTML content of a specified URL and updating
- the graph's state with this content. It uses the AsyncHtmlLoader for asynchronous
- document loading.
-
- This node acts as a starting point in many scraping workflows, preparing the state
- with the necessary HTML content for further processing by subsequent nodes in the graph.
-
- Attributes:
- node_name (str): The unique identifier name for the node.
- node_type (str): The type of the node, defaulting to "node". This categorization
- helps in determining the node's role and behavior within the graph.
- The "node" type is used for standard operational nodes.
-
- Args:
- node_name (str): The unique identifier name for the node. This name is used to
- reference the node within the graph.
- node_type (str, optional): The type of the node, limited to "node" or
- "conditional_node". Defaults to "node".
-
- Methods:
- execute(state): Fetches the HTML content for the URL specified in the state and
- updates the state with this content under the 'document' key.
- The 'url' key must be present in the state for the operation
- to succeed.
- """
-
- def __init__(self, node_name: str):
- """
- Initializes the FetchHTMLNode with a node name and node type.
- Arguments:
- node_name (str): name of the node
- """
- super().__init__(node_name, "node")
-
- def execute(self, state: dict) -> dict:
- """
- Executes the node's logic to fetch HTML content from a specified URL and
- update the state with this content.
-
- Args:
- state (dict): The current state of the graph, expected to contain a 'url' key.
-
- Returns:
- dict: The updated state with a new 'document' key containing the fetched HTML content.
-
- Raises:
- KeyError: If the 'url' key is not found in the state, indicating that the
- necessary information to perform the operation is missing.
- """
- print("---FETCHING HTML CODE---")
- try:
- url = state["url"]
- except KeyError as e:
- print(f"Error: {e} not found in state.")
- raise
-
- loader = AsyncHtmlLoader(url)
- document = loader.load()
- # metadata = document[0].metadata
- # document = remover(str(document[0]))
-
- # state["document"] = [
- # Document(page_content=document, metadata=metadata)]
- state["document"] = document
-
- return state
diff --git a/scrapegraphai/nodes/fetch_text_node.py b/scrapegraphai/nodes/fetch_text_node.py
deleted file mode 100644
index 3942eb0a..00000000
--- a/scrapegraphai/nodes/fetch_text_node.py
+++ /dev/null
@@ -1,58 +0,0 @@
-""" 
-Module for FetchTextNode
-"""
-from langchain_core.documents import Document
-from .base_node import BaseNode
-
-
-class FetchTextNode(BaseNode):
- """
- A node for loading raw text into the state.
-
- Primarily used in scraping workflows, this node prepares the state by directly
- loading raw text content from a specified source, making it available for
- further processing by subsequent nodes in the graph.
-
- Attributes:
- node_name (str): The unique identifier for the node.
- node_type (str): The type of the node ("node" in this case).
-
- Args:
- node_name (str): The unique identifier for the node.
-
- Methods:
- execute(state): Directly loads text content into the state and stores it
- under the 'document' key. Requires the 'url' key to be present in
- the state, representing the location of the text content.
- """
-
- def __init__(self, node_name: str):
- """
- Initializes the FetchTextNode with a node name.
-
- Args:
- node_name (str): The unique name for the node.
- """
- super().__init__(node_name, "node")
-
- def execute(self, state: dict) -> dict:
- """
- Loads raw text content into the state.
-
- Args:
- state (dict): The current state, expected to contain a 'text' key
- indicating the source of the text.
-
- Returns:
- dict: The updated state with the text content stored under the 'document' key.
-
- Raises:
- KeyError: If the 'url' key is missing from the state.
- """
- print("---LOADING TEXT CODE---")
-
- if 'text' not in state:
- raise KeyError("The 'url' key is required to load the text.")
-
- state["document"] = Document(page_content=state["text"])
- return state
diff --git a/scrapegraphai/nodes/text_to_speech_node.py b/scrapegraphai/nodes/text_to_speech_node.py
index ddc770af..9ab79e9e 100644
--- a/scrapegraphai/nodes/text_to_speech_node.py
+++ b/scrapegraphai/nodes/text_to_speech_node.py
@@ -4,7 +4,7 @@ Module for parsing the text to voice
"""
from .base_node import BaseNode
-
+from typing import List
class TextToSpeechNode(BaseNode):
"""
@@ -17,14 +17,14 @@ class TextToSpeechNode(BaseNode):
execute(state, text): Execute the node's logic and return the updated state.
"""
- def __init__(self, llm, node_name: str = "TextToSpeechNode"):
+ def __init__(self, input: str, output: List[str], model_config: dict, node_name: str = "TextToSpeechNode"):
"""
Initializes an instance of the TextToSpeechNode class.
"""
- super().__init__(node_name, "node")
- self.llm = llm
+ super().__init__(node_name, "node", input, output, 1, model_config)
+ self.text2speech_model = model_config["text2speech_model"]
- def execute(self, state: dict) -> dict:
+ def execute(self, state):
"""
Execute the node's logic and return the updated state.
Args:
@@ -34,11 +34,21 @@ class TextToSpeechNode(BaseNode):
:return: The updated state after executing this node.
"""
- text2translate = state.get("answer", None)
- if not text2translate:
+ 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]
+
+ text2translate = input_data[0]
+
+ # if not a string, raise an error
+ if not isinstance(text2translate, str):
raise ValueError("No text to translate to speech.")
print("---TRANSLATING TEXT TO SPEECH---")
- audio = self.llm.run(text2translate["summary"])
+ audio = self.text2speech_model.run(text2translate["summary"])
- state.update({"audio": audio})
+ state.update({self.output[0]: audio})
return state