Skip to content

Python scraper based on AI

refactoring of the code

Marco Vinciguerrafe3aa28fe7f1
diff --git a/scrapegraphai/graphs/abstract_graph.py b/scrapegraphai/graphs/abstract_graph.py
index 357ff94d..02869ab9 100644
--- a/scrapegraphai/graphs/abstract_graph.py
+++ b/scrapegraphai/graphs/abstract_graph.py
@@ -1,7 +1,6 @@
"""
AbstractGraph Module
"""
-
from abc import ABC, abstractmethod
from typing import Optional
import uuid
@@ -122,7 +121,7 @@ class AbstractGraph(ABC):
llm_defaults = {"temperature": 0, "streaming": False}
llm_params = {**llm_defaults, **llm_config}
rate_limit_params = llm_params.pop("rate_limit", {})
-
+
if rate_limit_params:
requests_per_second = rate_limit_params.get("requests_per_second")
max_retries = rate_limit_params.get("max_retries")
@@ -138,7 +137,7 @@ class AbstractGraph(ABC):
self.model_token = llm_params["model_tokens"]
except KeyError as exc:
raise KeyError("model_tokens not specified") from exc
- return llm_params["model_instance"]
+ return llm_params["model_instance"]
known_providers = {"openai", "azure_openai", "google_genai", "google_vertexai",
"ollama", "oneapi", "nvidia", "groq", "anthropic", "bedrock", "mistralai",
@@ -149,16 +148,18 @@ class AbstractGraph(ABC):
llm_params["model"] = split_model_provider[1]
if llm_params["model_provider"] not in known_providers:
- raise ValueError(f"Provider {llm_params['model_provider']} is not supported. If possible, try to use a model instance instead.")
+ raise ValueError(f"""Provider {llm_params['model_provider']} is not supported.
+ If possible, try to use a model instance instead.""")
try:
self.model_token = models_tokens[llm_params["model_provider"]][llm_params["model"]]
except KeyError:
- print(f"Model {llm_params['model_provider']}/{llm_params['model']} not found, using default token size (8192)")
+ print(f"""Model {llm_params['model_provider']}/{llm_params['model']} not found,
+ using default token size (8192)""")
self.model_token = 8192
try:
- if llm_params["model_provider"] not in {"oneapi", "nvidia", "ernie", "deepseek", "togetherai"}:
+ if llm_params["model_provider"] not in {"oneapi","nvidia","ernie","deepseek","togetherai"}:
if llm_params["model_provider"] == "bedrock":
llm_params["model_kwargs"] = { "temperature" : llm_params.pop("temperature") }
with warnings.catch_warnings():
@@ -181,14 +182,16 @@ class AbstractGraph(ABC):
try:
from langchain_together import ChatTogether
except ImportError:
- raise ImportError("The langchain_together module is not installed. Please install it using `pip install scrapegraphai[other-language-models]`.")
+ raise ImportError("""The langchain_together module is not installed.
+ Please install it using `pip install scrapegraphai[other-language-models]`.""")
return ChatTogether(**llm_params)
elif model_provider == "nvidia":
try:
from langchain_nvidia_ai_endpoints import ChatNVIDIA
except ImportError:
- raise ImportError("The langchain_nvidia_ai_endpoints module is not installed. Please install it using `pip install scrapegraphai[other-language-models]`.")
+ raise ImportError("""The langchain_nvidia_ai_endpoints module is not installed.
+ Please install it using `pip install scrapegraphai[other-language-models]`.""")
return ChatNVIDIA(**llm_params)
except Exception as e:
diff --git a/scrapegraphai/graphs/base_graph.py b/scrapegraphai/graphs/base_graph.py
index 17c05032..71e42760 100644
--- a/scrapegraphai/graphs/base_graph.py
+++ b/scrapegraphai/graphs/base_graph.py
@@ -116,28 +116,21 @@ class BaseGraph:
curr_time = time.time()
current_node = next(node for node in self.nodes if node.node_name == current_node_name)
- # check if there is a "source" key in the node config
if current_node.__class__.__name__ == "FetchNode":
- # get the second key name of the state dictionary
source_type = list(state.keys())[1]
if state.get("user_prompt", None):
- # Set 'prompt' if 'user_prompt' is a string, otherwise None
prompt = state["user_prompt"] if isinstance(state["user_prompt"], str) else None
- # Convert 'local_dir' source type to 'html_dir'
if source_type == "local_dir":
source_type = "html_dir"
elif source_type == "url":
- # If the source is a list, add string URLs to 'source'
if isinstance(state[source_type], list):
for url in state[source_type]:
if isinstance(url, str):
source.append(url)
- # If the source is a single string, add it to 'source'
elif isinstance(state[source_type], str):
source.append(state[source_type])
- # check if there is an "llm_model" variable in the class
if hasattr(current_node, "llm_model") and llm_model is None:
llm_model = current_node.llm_model
if hasattr(llm_model, "model_name"):
@@ -145,7 +138,6 @@ class BaseGraph:
elif hasattr(llm_model, "model"):
llm_model = llm_model.model
- # check if there is an "embedder_model" variable in the class
if hasattr(current_node, "embedder_model") and embedder_model is None:
embedder_model = current_node.embedder_model
if hasattr(embedder_model, "model_name"):
@@ -157,7 +149,6 @@ class BaseGraph:
if isinstance(current_node.node_config,dict):
if current_node.node_config.get("schema", None) and schema is None:
if not isinstance(current_node.node_config["schema"], dict):
- # convert to dict
try:
schema = current_node.node_config["schema"].schema()
except Exception as e:
@@ -220,7 +211,6 @@ class BaseGraph:
"exec_time": total_exec_time,
})
- # Log the graph execution telemetry
graph_execution_time = time.time() - start_time
response = state.get("answer", None) if source_type == "url" else None
content = state.get("parsed_doc", None) if response is not None else None
@@ -272,13 +262,10 @@ class BaseGraph:
# if node name already exists in the graph, raise an exception
if node.node_name in {n.node_name for n in self.nodes}:
- raise ValueError(f"Node with name '{node.node_name}' already exists in the graph. You can change it by setting the 'node_name' attribute.")
+ raise ValueError(f"""Node with name '{node.node_name}' already exists in the graph.
+ You can change it by setting the 'node_name' attribute.""")
- # get the last node in the list
last_node = self.nodes[-1]
- # add the edge connecting the last node to the new node
self.raw_edges.append((last_node, node))
- # add the node to the list of nodes
self.nodes.append(node)
- # update the edges connecting the last node to the new node
self.edges = self._create_edges({e for e in self.raw_edges})
diff --git a/scrapegraphai/graphs/csv_scraper_graph.py b/scrapegraphai/graphs/csv_scraper_graph.py
index 48d84c18..eb34383e 100644
--- a/scrapegraphai/graphs/csv_scraper_graph.py
+++ b/scrapegraphai/graphs/csv_scraper_graph.py
@@ -43,7 +43,8 @@ class CSVScraperGraph(AbstractGraph):
the answer to the prompt as a string.
run runs the CSVScraperGraph class to extract information from a CSV file based
on the user's prompt. It requires no additional arguments since all necessary data
- is stored within the class instance. The method fetches the relevant chunks of text or speech,
+ is stored within the class instance.
+ The method fetches the relevant chunks of text or speech,
generates an answer based on these chunks, and returns this answer as a string.
"""
diff --git a/scrapegraphai/graphs/csv_scraper_multi_graph.py b/scrapegraphai/graphs/csv_scraper_multi_graph.py
index 67498475..e7aa0472 100644
--- a/scrapegraphai/graphs/csv_scraper_multi_graph.py
+++ b/scrapegraphai/graphs/csv_scraper_multi_graph.py
@@ -4,8 +4,6 @@ CSVScraperMultiGraph Module
from typing import List, Optional
from pydantic import BaseModel
-
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
from .csv_scraper_graph import CSVScraperGraph
@@ -60,20 +58,12 @@ class CSVScraperMultiGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a CSVScraperGraph instance
- # ************************************************
-
smart_scraper_instance = CSVScraperGraph(
prompt="",
source="",
config=self.copy_config,
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
graph_iterator_node = GraphIteratorNode(
input="user_prompt & jsons",
output=["results"],
diff --git a/scrapegraphai/graphs/deep_scraper_graph.py b/scrapegraphai/graphs/deep_scraper_graph.py
index 10aa61ae..7a75bd08 100644
--- a/scrapegraphai/graphs/deep_scraper_graph.py
+++ b/scrapegraphai/graphs/deep_scraper_graph.py
@@ -1,7 +1,6 @@
"""
DeepScraperGraph Module
"""
-
from typing import Optional
from pydantic import BaseModel
from .base_graph import BaseGraph
@@ -54,7 +53,7 @@ class DeepScraperGraph(AbstractGraph):
"""
def __init__(self, prompt: str, source: str, config: dict, schema: Optional[BaseModel] = None):
-
+
super().__init__(prompt, config, source, schema)
self.input_key = "url" if source.startswith("http") else "local_dir"
@@ -79,7 +78,7 @@ class DeepScraperGraph(AbstractGraph):
"llm_model": self.llm_model
}
)
-
+
generate_answer_node = GenerateAnswerNode(
input="user_prompt & (relevant_chunks | parsed_doc | doc)",
output=["answer"],
@@ -89,6 +88,7 @@ class DeepScraperGraph(AbstractGraph):
"schema": self.schema
}
)
+
search_node = SearchLinkNode(
input="user_prompt & relevant_chunks",
output=["relevant_links"],
@@ -96,6 +96,7 @@ class DeepScraperGraph(AbstractGraph):
"llm_model": self.llm_model,
}
)
+
graph_iterator_node = GraphIteratorNode(
input="user_prompt & relevant_links",
output=["results"],
@@ -104,6 +105,7 @@ class DeepScraperGraph(AbstractGraph):
"batchsize": 1
}
)
+
merge_answers_node = MergeAnswersNode(
input="user_prompt & results",
output=["answer"],
@@ -143,8 +145,8 @@ class DeepScraperGraph(AbstractGraph):
"""
base_graph = self._create_repeated_graph()
- graph_iterator_node = list(filter(lambda x: x.node_name == "GraphIterator", base_graph.nodes))[0]
- # Graph iterator will repeat the same graph for multiple hyperlinks found within input webpage
+ graph_iterator_node = list(filter(lambda x: x.node_name == "GraphIterator",
+ base_graph.nodes))[0]
graph_iterator_node.node_config["graph_instance"] = self
return base_graph
diff --git a/scrapegraphai/graphs/json_scraper_graph.py b/scrapegraphai/graphs/json_scraper_graph.py
index 2137a023..dfc3a0bc 100644
--- a/scrapegraphai/graphs/json_scraper_graph.py
+++ b/scrapegraphai/graphs/json_scraper_graph.py
@@ -1,7 +1,6 @@
"""
JSONScraperGraph Module
"""
-
from typing import Optional
from pydantic import BaseModel
from .base_graph import BaseGraph
diff --git a/scrapegraphai/graphs/json_scraper_multi_graph.py b/scrapegraphai/graphs/json_scraper_multi_graph.py
index c72d8afd..d4fc8f99 100644
--- a/scrapegraphai/graphs/json_scraper_multi_graph.py
+++ b/scrapegraphai/graphs/json_scraper_multi_graph.py
@@ -5,7 +5,6 @@ JSONScraperMultiGraph Module
from copy import deepcopy
from typing import List, Optional
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
from .json_scraper_graph import JSONScraperGraph
@@ -43,7 +42,8 @@ class JSONScraperMultiGraph(AbstractGraph):
>>> result = search_graph.run()
"""
- def __init__(self, prompt: str, source: List[str], config: dict, schema: Optional[BaseModel] = None):
+ def __init__(self, prompt: str, source: List[str],
+ config: dict, schema: Optional[BaseModel] = None):
self.max_results = config.get("max_results", 3)
@@ -61,10 +61,6 @@ class JSONScraperMultiGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a JSONScraperGraph instance
- # ************************************************
-
smart_scraper_instance = JSONScraperGraph(
prompt="",
source="",
@@ -72,10 +68,6 @@ class JSONScraperMultiGraph(AbstractGraph):
schema=self.copy_schema
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
graph_iterator_node = GraphIteratorNode(
input="user_prompt & jsons",
output=["results"],
diff --git a/scrapegraphai/graphs/markdown_scraper_graph.py b/scrapegraphai/graphs/markdown_scraper_graph.py
index 82bd8a75..7f31fa69 100644
--- a/scrapegraphai/graphs/markdown_scraper_graph.py
+++ b/scrapegraphai/graphs/markdown_scraper_graph.py
@@ -1,3 +1,6 @@
+"""
+md_scraper module
+"""
from typing import Optional
import logging
from pydantic import BaseModel
@@ -17,7 +20,8 @@ class MDScraperGraph(AbstractGraph):
config (dict): Configuration parameters for the graph.
schema (BaseModel): The schema for the graph output.
llm_model: An instance of a language model client, configured for generating answers.
- embedder_model: An instance of an embedding model client, configured for generating embeddings.
+ embedder_model: An instance of an embedding model client,
+ configured for generating embeddings.
verbose (bool): A flag indicating whether to show print statements during execution.
headless (bool): A flag indicating whether to run the graph in headless mode.
diff --git a/scrapegraphai/graphs/markdown_scraper_multi_graph.py b/scrapegraphai/graphs/markdown_scraper_multi_graph.py
index 772eebe6..e6fa35fc 100644
--- a/scrapegraphai/graphs/markdown_scraper_multi_graph.py
+++ b/scrapegraphai/graphs/markdown_scraper_multi_graph.py
@@ -1,7 +1,6 @@
"""
MDScraperMultiGraph Module
"""
-
from copy import copy, deepcopy
from typing import List, Optional
from pydantic import BaseModel
@@ -42,7 +41,8 @@ class MDScraperMultiGraph(AbstractGraph):
>>> result = search_graph.run()
"""
- def __init__(self, prompt: str, source: List[str], config: dict, schema: Optional[BaseModel] = None):
+ def __init__(self, prompt: str, source: List[str],
+ config: dict, schema: Optional[BaseModel] = None):
self.copy_config = safe_deepcopy(config)
self.copy_schema = deepcopy(schema)
diff --git a/scrapegraphai/graphs/omni_search_graph.py b/scrapegraphai/graphs/omni_search_graph.py
index 860685bd..bfb8dcbc 100644
--- a/scrapegraphai/graphs/omni_search_graph.py
+++ b/scrapegraphai/graphs/omni_search_graph.py
@@ -5,11 +5,9 @@ OmniSearchGraph Module
from copy import deepcopy
from typing import Optional
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
from .omni_scraper_graph import OmniScraperGraph
-
from ..nodes import (
SearchInternetNode,
GraphIteratorNode,
@@ -63,10 +61,6 @@ class OmniSearchGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a OmniScraperGraph instance
- # ************************************************
-
omni_scraper_instance = OmniScraperGraph(
prompt="",
source="",
@@ -74,10 +68,6 @@ class OmniSearchGraph(AbstractGraph):
schema=self.copy_schema
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
search_internet_node = SearchInternetNode(
input="user_prompt",
output=["urls"],
diff --git a/scrapegraphai/graphs/pdf_scraper_graph.py b/scrapegraphai/graphs/pdf_scraper_graph.py
index 9b54136c..2e9165df 100644
--- a/scrapegraphai/graphs/pdf_scraper_graph.py
+++ b/scrapegraphai/graphs/pdf_scraper_graph.py
@@ -2,7 +2,6 @@
"""
PDFScraperGraph Module
"""
-
from typing import Optional
from pydantic import BaseModel
from .base_graph import BaseGraph
diff --git a/scrapegraphai/graphs/pdf_scraper_multi_graph.py b/scrapegraphai/graphs/pdf_scraper_multi_graph.py
index 06da6944..55c2fd75 100644
--- a/scrapegraphai/graphs/pdf_scraper_multi_graph.py
+++ b/scrapegraphai/graphs/pdf_scraper_multi_graph.py
@@ -59,10 +59,6 @@ class PdfScraperMultiGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a PDFScraperGraph instance
- # ************************************************
-
pdf_scraper_instance = PDFScraperGraph(
prompt="",
source="",
@@ -70,10 +66,6 @@ class PdfScraperMultiGraph(AbstractGraph):
schema=self.copy_schema
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
graph_iterator_node = GraphIteratorNode(
input="user_prompt & pdfs",
output=["results"],
diff --git a/scrapegraphai/graphs/script_creator_graph.py b/scrapegraphai/graphs/script_creator_graph.py
index 2f080764..4692d8dd 100644
--- a/scrapegraphai/graphs/script_creator_graph.py
+++ b/scrapegraphai/graphs/script_creator_graph.py
@@ -1,7 +1,6 @@
"""
ScriptCreatorGraph Module
"""
-
from typing import Optional
from pydantic import BaseModel
from .base_graph import BaseGraph
diff --git a/scrapegraphai/graphs/script_creator_multi_graph.py b/scrapegraphai/graphs/script_creator_multi_graph.py
index b2ea8465..f807986b 100644
--- a/scrapegraphai/graphs/script_creator_multi_graph.py
+++ b/scrapegraphai/graphs/script_creator_multi_graph.py
@@ -3,13 +3,10 @@ ScriptCreatorMultiGraph Module
"""
from typing import List, Optional
-
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
from .script_creator_graph import ScriptCreatorGraph
-
from ..nodes import (
GraphIteratorNode,
MergeGeneratedScriptsNode
@@ -43,7 +40,8 @@ class ScriptCreatorMultiGraph(AbstractGraph):
>>> result = script_graph.run()
"""
- def __init__(self, prompt: str, source: List[str], config: dict, schema: Optional[BaseModel] = None):
+ def __init__(self, prompt: str, source: List[str],
+ config: dict, schema: Optional[BaseModel] = None):
self.max_results = config.get("max_results", 3)
@@ -58,10 +56,6 @@ class ScriptCreatorMultiGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a ScriptCreatorGraph instance
- # ************************************************
-
script_generator_instance = ScriptCreatorGraph(
prompt="",
source="",
@@ -69,10 +63,6 @@ class ScriptCreatorMultiGraph(AbstractGraph):
schema=self.schema
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
graph_iterator_node = GraphIteratorNode(
input="user_prompt & urls",
output=["scripts"],
diff --git a/scrapegraphai/graphs/search_graph.py b/scrapegraphai/graphs/search_graph.py
index e34469be..a2ef6fc3 100644
--- a/scrapegraphai/graphs/search_graph.py
+++ b/scrapegraphai/graphs/search_graph.py
@@ -62,7 +62,6 @@ class SearchGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # Create a SmartScraperGraph instance
smart_scraper_instance = SmartScraperGraph(
prompt="",
source="",
@@ -70,7 +69,6 @@ class SearchGraph(AbstractGraph):
schema=self.copy_schema
)
- # Define the graph nodes
search_internet_node = SearchInternetNode(
input="user_prompt",
output=["urls"],
diff --git a/scrapegraphai/graphs/search_link_graph.py b/scrapegraphai/graphs/search_link_graph.py
index b373f4e0..54fd663c 100644
--- a/scrapegraphai/graphs/search_link_graph.py
+++ b/scrapegraphai/graphs/search_link_graph.py
@@ -1,4 +1,6 @@
-""" SearchLinkGraph Module """
+"""
+SearchLinkGraph Module
+"""
from typing import Optional
import logging
from pydantic import BaseModel
diff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.py
index 045f31ac..a4e04281 100644
--- a/scrapegraphai/graphs/smart_scraper_graph.py
+++ b/scrapegraphai/graphs/smart_scraper_graph.py
@@ -1,13 +1,11 @@
"""
SmartScraperGraph Module
"""
-
from typing import Optional
import logging
from pydantic import BaseModel
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
-
from ..nodes import (
FetchNode,
ParseNode,
diff --git a/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py b/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py
index a85eb5bb..d9773cb9 100644
--- a/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py
+++ b/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py
@@ -18,7 +18,8 @@ from ..nodes import (
class SmartScraperMultiConcatGraph(AbstractGraph):
"""
- SmartScraperMultiGraph is a scraping pipeline that scrapes a list of URLs and generates answers to a given prompt.
+ SmartScraperMultiGraph is a scraping pipeline that scrapes a
+ list of URLs and generates answers to a given prompt.
It only requires a user prompt and a list of URLs.
Attributes:
@@ -43,13 +44,14 @@ class SmartScraperMultiConcatGraph(AbstractGraph):
>>> result = search_graph.run()
"""
- def __init__(self, prompt: str, source: List[str], config: dict, schema: Optional[BaseModel] = None):
+ def __init__(self, prompt: str, source: List[str],
+ config: dict, schema: Optional[BaseModel] = None):
if all(isinstance(value, str) for value in config.values()):
self.copy_config = copy(config)
else:
self.copy_config = deepcopy(config)
-
+
self.copy_schema = deepcopy(schema)
super().__init__(prompt, config, source, schema)
@@ -62,10 +64,6 @@ class SmartScraperMultiConcatGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a SmartScraperGraph instance
- # ************************************************
-
smart_scraper_instance = SmartScraperGraph(
prompt="",
source="",
@@ -73,10 +71,6 @@ class SmartScraperMultiConcatGraph(AbstractGraph):
schema=self.copy_schema
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
graph_iterator_node = GraphIteratorNode(
input="user_prompt & urls",
output=["results"],
diff --git a/scrapegraphai/graphs/smart_scraper_multi_graph.py b/scrapegraphai/graphs/smart_scraper_multi_graph.py
index 82585cf0..2fc11dda 100644
--- a/scrapegraphai/graphs/smart_scraper_multi_graph.py
+++ b/scrapegraphai/graphs/smart_scraper_multi_graph.py
@@ -5,11 +5,9 @@ SmartScraperMultiGraph Module
from copy import deepcopy
from typing import List, Optional
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
from .smart_scraper_graph import SmartScraperGraph
-
from ..nodes import (
GraphIteratorNode,
MergeAnswersNode
@@ -63,10 +61,6 @@ class SmartScraperMultiGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a SmartScraperGraph instance
- # ************************************************
-
smart_scraper_instance = SmartScraperGraph(
prompt="",
source="",
@@ -74,10 +68,6 @@ class SmartScraperMultiGraph(AbstractGraph):
schema=self.copy_schema
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
graph_iterator_node = GraphIteratorNode(
input="user_prompt & urls",
output=["results"],
diff --git a/scrapegraphai/graphs/speech_graph.py b/scrapegraphai/graphs/speech_graph.py
index 4388bf66..3febd2a1 100644
--- a/scrapegraphai/graphs/speech_graph.py
+++ b/scrapegraphai/graphs/speech_graph.py
@@ -1,20 +1,16 @@
"""
SpeechGraph Module
"""
-
from typing import Optional
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
-
from ..nodes import (
FetchNode,
ParseNode,
GenerateAnswerNode,
TextToSpeechNode,
)
-
from ..utils.save_audio_from_bytes import save_audio_from_bytes
from ..models import OpenAITextToSpeech
@@ -29,7 +25,8 @@ class SpeechGraph(AbstractGraph):
config (dict): Configuration parameters for the graph.
schema (BaseModel): The schema for the graph output.
llm_model: An instance of a language model client, configured for generating answers.
- embedder_model: An instance of an embedding model client, configured for generating embeddings.
+ embedder_model: An instance of an embedding model clienta
+ configured for generating embeddings.
verbose (bool): A flag indicating whether to show print statements during execution.
headless (bool): A flag indicating whether to run the graph in headless mode.
model_token (int): The token limit for the language model.
diff --git a/scrapegraphai/graphs/xml_scraper_graph.py b/scrapegraphai/graphs/xml_scraper_graph.py
index 29184f28..9bc91b6f 100644
--- a/scrapegraphai/graphs/xml_scraper_graph.py
+++ b/scrapegraphai/graphs/xml_scraper_graph.py
@@ -4,10 +4,8 @@ XMLScraperGraph Module
from typing import Optional
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
-
from ..nodes import (
FetchNode,
GenerateAnswerNode
diff --git a/scrapegraphai/graphs/xml_scraper_multi_graph.py b/scrapegraphai/graphs/xml_scraper_multi_graph.py
index 493d12ca..c76cf11a 100644
--- a/scrapegraphai/graphs/xml_scraper_multi_graph.py
+++ b/scrapegraphai/graphs/xml_scraper_multi_graph.py
@@ -5,11 +5,9 @@ XMLScraperMultiGraph Module
from copy import deepcopy
from typing import List, Optional
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
from .xml_scraper_graph import XMLScraperGraph
-
from ..nodes import (
GraphIteratorNode,
MergeAnswersNode
@@ -61,10 +59,6 @@ class XMLScraperMultiGraph(AbstractGraph):
BaseGraph: A graph instance representing the web scraping and searching workflow.
"""
- # ************************************************
- # Create a XMLScraperGraph instance
- # ************************************************
-
smart_scraper_instance = XMLScraperGraph(
prompt="",
source="",
@@ -72,10 +66,6 @@ class XMLScraperMultiGraph(AbstractGraph):
schema=self.copy_schema
)
- # ************************************************
- # Define the graph nodes
- # ************************************************
-
graph_iterator_node = GraphIteratorNode(
input="user_prompt & jsons",
output=["results"],
diff --git a/scrapegraphai/helpers/default_filters.py b/scrapegraphai/helpers/default_filters.py
index a997736d..c3846f86 100644
--- a/scrapegraphai/helpers/default_filters.py
+++ b/scrapegraphai/helpers/default_filters.py
@@ -10,4 +10,4 @@ filter_dict = {
'/login', '/signup', '/register', '/contact', 'facebook.com', 'twitter.com',
'linkedin.com', 'instagram.com', '.js', '.css',
]
-}
\ No newline at end of file
+}
diff --git a/scrapegraphai/integrations/burr_bridge.py b/scrapegraphai/integrations/burr_bridge.py
index e5eb3c6a..76cce914 100644
--- a/scrapegraphai/integrations/burr_bridge.py
+++ b/scrapegraphai/integrations/burr_bridge.py
@@ -18,8 +18,6 @@ except ImportError:
raise ImportError("burr package is not installed. Please install it with 'pip install scrapegraphai[burr]'")
-
-
class PrintLnHook(PostRunStepHook, PreRunStepHook):
"""
Hook to print the action name before and after it is executed.
diff --git a/scrapegraphai/models/deepseek.py b/scrapegraphai/models/deepseek.py
index 31b2bd5d..1901269e 100644
--- a/scrapegraphai/models/deepseek.py
+++ b/scrapegraphai/models/deepseek.py
@@ -18,5 +18,5 @@ class DeepSeek(ChatOpenAI):
if 'api_key' in llm_config:
llm_config['openai_api_key'] = llm_config.pop('api_key')
llm_config['openai_api_base'] = 'https://api.deepseek.com/v1'
-
+
super().__init__(**llm_config)
diff --git a/scrapegraphai/nodes/base_node.py b/scrapegraphai/nodes/base_node.py
index 206b0547..90dbea51 100644
--- a/scrapegraphai/nodes/base_node.py
+++ b/scrapegraphai/nodes/base_node.py
@@ -27,7 +27,8 @@ class BaseNode(ABC):
input (str): Expression defining the input keys needed from the state.
output (List[str]): List of output keys to be updated in the state.
min_input_len (int, optional): Minimum required number of input keys; defaults to 1.
- node_config (Optional[dict], optional): Additional configuration for the node; defaults to None.
+ node_config (Optional[dict], optional): Additional configuration
+ for the node; defaults to None.
Raises:
ValueError: If `node_type` is not one of the allowed types.
@@ -233,7 +234,9 @@ class BaseNode(ABC):
result = evaluate_expression(expression)
if not result:
- raise ValueError(f"No state keys matched the expression. Expression was {expression}. State contains keys: {', '.join(state.keys())}")
+ raise ValueError(f"""No state keys matched the expression.
+ Expression was {expression}.
+ State contains keys: {', '.join(state.keys())}""")
# Remove redundant state keys from the result, without changing their order
final_result = []
diff --git a/scrapegraphai/nodes/concat_answers_node.py b/scrapegraphai/nodes/concat_answers_node.py
index 8360e18c..add8c9f6 100644
--- a/scrapegraphai/nodes/concat_answers_node.py
+++ b/scrapegraphai/nodes/concat_answers_node.py
@@ -34,7 +34,7 @@ class ConcatAnswersNode(BaseNode):
)
def _merge_dict(self, items):
-
+
return {"products": {f"item_{i+1}": item for i, item in enumerate(items)}}
def execute(self, state: dict) -> dict:
diff --git a/scrapegraphai/nodes/fetch_node.py b/scrapegraphai/nodes/fetch_node.py
index dd18e7e1..19d59004 100644
--- a/scrapegraphai/nodes/fetch_node.py
+++ b/scrapegraphai/nodes/fetch_node.py
@@ -285,7 +285,9 @@ class FetchNode(BaseNode):
metadata={"source": source}) for content in data]
elif self.scrape_do is not None:
from ..docloaders.scrape_do import scrape_do_fetch
- if self.scrape_do.get("use_proxy") is None or self.scrape_do.get("geoCode") is None or self.scrape_do.get("super_proxy") is None:
+ if (self.scrape_do.get("use_proxy") is None) or \
+ self.scrape_do.get("geoCode") is None or \
+ self.scrape_do.get("super_proxy") is None:
data = scrape_do_fetch(self.scrape_do.get("api_key"),
source)
else:
@@ -305,7 +307,10 @@ class FetchNode(BaseNode):
the document fetched by ChromiumLoader.""")
parsed_content = document[0].page_content
- if (isinstance(self.llm_model, ChatOpenAI) or isinstance(self.llm_model, AzureChatOpenAI)) and not self.script_creator or self.force and not self.script_creator and not self.openai_md_enabled:
+ if (isinstance(self.llm_model, ChatOpenAI) \
+ or isinstance(self.llm_model, AzureChatOpenAI)) \
+ and not self.script_creator or self.force \
+ and not self.script_creator and not self.openai_md_enabled:
parsed_content = convert_to_md(document[0].page_content, parsed_content)
compressed_document = [
diff --git a/scrapegraphai/nodes/generate_answer_node.py b/scrapegraphai/nodes/generate_answer_node.py
index f5b6b5c8..42586b60 100644
--- a/scrapegraphai/nodes/generate_answer_node.py
+++ b/scrapegraphai/nodes/generate_answer_node.py
@@ -105,7 +105,11 @@ class GenerateAnswerNode(BaseNode):
output_parser = JsonOutputParser()
format_instructions = output_parser.get_format_instructions()
- if isinstance(self.llm_model, (ChatOpenAI, AzureChatOpenAI)) and not self.script_creator or self.force and not self.script_creator or self.is_md_scraper:
+ if isinstance(self.llm_model, (ChatOpenAI, AzureChatOpenAI)) \
+ and not self.script_creator \
+ or self.force \
+ and not self.script_creator or self.is_md_scraper:
+
template_no_chunks_prompt = TEMPLATE_NO_CHUNKS_MD
template_chunks_prompt = TEMPLATE_CHUNKS_MD
template_merge_prompt = TEMPLATE_MERGE_MD
diff --git a/scrapegraphai/nodes/generate_answer_pdf_node.py b/scrapegraphai/nodes/generate_answer_pdf_node.py
index 5e1e2687..2a25cc20 100644
--- a/scrapegraphai/nodes/generate_answer_pdf_node.py
+++ b/scrapegraphai/nodes/generate_answer_pdf_node.py
@@ -85,24 +85,20 @@ class GenerateAnswerPDFNode(BaseNode):
self.logger.info(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]
user_prompt = input_data[0]
doc = input_data[1]
- # Initialize the output parser
if self.node_config.get("schema", None) is not None:
if isinstance(self.llm_model, (ChatOpenAI, ChatMistralAI)):
self.llm_model = self.llm_model.with_structured_output(
schema = self.node_config["schema"],
method="function_calling") # json schema works only on specific models
-
- # default parser to empty lambda function
+
output_parser = lambda x: x
if is_basemodel_subclass(self.node_config["schema"]):
output_parser = dict
@@ -139,9 +135,9 @@ class GenerateAnswerPDFNode(BaseNode):
state.update({self.output[0]: answer})
return state
-
+
chains_dict = {}
-
+
for i, chunk in enumerate(
tqdm(doc, desc="Processing chunks", disable=not self.verbose)):
prompt = PromptTemplate(
diff --git a/scrapegraphai/nodes/generate_scraper_node.py b/scrapegraphai/nodes/generate_scraper_node.py
index ce6259df..93ad9cf3 100644
--- a/scrapegraphai/nodes/generate_scraper_node.py
+++ b/scrapegraphai/nodes/generate_scraper_node.py
@@ -111,8 +111,9 @@ class GenerateScraperNode(BaseNode):
#raise NotImplementedError(
# "Currently GenerateScraperNode cannot handle more than 1 context chunks"
#)
- self.logger.warn(f"Warning: {self.node_name} Node provided with {len(doc)} chunks but can only "
- "support 1, ignoring remaining chunks")
+ self.logger.warn(f"""Warning: {self.node_name}
+ Node provided with {len(doc)} chunks but can only "
+ "support 1, ignoring remaining chunks""")
doc = [doc[0]]
template = TEMPLATE_NO_CHUNKS
else:
diff --git a/scrapegraphai/nodes/graph_iterator_node.py b/scrapegraphai/nodes/graph_iterator_node.py
index a765da28..fe355d51 100644
--- a/scrapegraphai/nodes/graph_iterator_node.py
+++ b/scrapegraphai/nodes/graph_iterator_node.py
@@ -89,10 +89,8 @@ class GraphIteratorNode(BaseNode):
KeyError: If the input keys are not found in the state.
"""
- # interprets input keys based on the provided input expression
input_keys = self.get_input_keys(state)
- # fetches data from the state based on the input keys
input_data = [state[key] for key in input_keys]
user_prompt = input_data[0]
diff --git a/scrapegraphai/nodes/merge_generated_scripts.py b/scrapegraphai/nodes/merge_generated_scripts.py
index ffc2b2fd..e3a138a8 100644
--- a/scrapegraphai/nodes/merge_generated_scripts.py
+++ b/scrapegraphai/nodes/merge_generated_scripts.py
@@ -60,7 +60,6 @@ class MergeGeneratedScriptsNode(BaseNode):
user_prompt = input_data[0]
scripts = input_data[1]
- # merge the scripts in one string
scripts_str = ""
for i, script in enumerate(scripts):
scripts_str += "-----------------------------------\n"
@@ -68,16 +67,6 @@ class MergeGeneratedScriptsNode(BaseNode):
scripts_str += "-----------------------------------\n"
scripts_str += script
- # TODO: should we pass the schema to the output parser even if the scripts already have it implemented?
-
- # schema to be used for output parsing
- # if self.node_config.get("schema", None) is not None:
- # output_schema = JsonOutputParser(pydantic_object=self.node_config["schema"])
- # else:
- # output_schema = JsonOutputParser()
-
- # format_instructions = output_schema.get_format_instructions()
-
TEMPLATE_MERGE = """
You are a python expert in web scraping and you have just generated multiple scripts to scrape different URLs.\n
The scripts are generated based on a user question and the content of the websites.\n
@@ -103,4 +92,4 @@ class MergeGeneratedScriptsNode(BaseNode):
# Update the state with the generated answer
state.update({self.output[0]: answer})
- return state
\ No newline at end of file
+ return state
diff --git a/scrapegraphai/nodes/robots_node.py b/scrapegraphai/nodes/robots_node.py
index 6f9bc352..2bb47e74 100644
--- a/scrapegraphai/nodes/robots_node.py
+++ b/scrapegraphai/nodes/robots_node.py
@@ -119,7 +119,8 @@ class RobotsNode(BaseNode):
raise ValueError("The website you selected is not scrapable")
else:
self.logger.warning(
- "\033[33m(WARNING: Scraping this website is not allowed but you decided to force it)\033[0m"
+ """\033[33m(WARNING: Scraping this website is
+ not allowed but you decided to force it)\033[0m"""
)
else:
self.logger.warning("\033[32m(Scraping this website is allowed)\033[0m")
diff --git a/scrapegraphai/nodes/search_link_node.py b/scrapegraphai/nodes/search_link_node.py
index 60c3e1aa..034599ea 100644
--- a/scrapegraphai/nodes/search_link_node.py
+++ b/scrapegraphai/nodes/search_link_node.py
@@ -42,9 +42,7 @@ class SearchLinkNode(BaseNode):
self.llm_model = node_config["llm_model"]
- # Apply filters if filter_links is True or if filter_config is provided
if node_config.get("filter_links", False) or "filter_config" in node_config:
- # Merge provided filter config with default filter config for partial configuration
provided_filter_config = node_config.get("filter_config", {})
self.filter_config = {**default_filters.filter_dict, **provided_filter_config}
self.filter_links = True
@@ -79,7 +77,7 @@ class SearchLinkNode(BaseNode):
return any(indicator in parsed_url.path.lower() or indicator in query_params for indicator in lang_indicators)
def _is_potentially_irrelevant(self, url):
if not self.filter_links:
- return False # Skip irrelevant URL filtering if filtering is not enabled
+ return False
irrelevant_keywords = self.filter_config.get("irrelevant_keywords", [])
return any(keyword in url.lower() for keyword in irrelevant_keywords)
@@ -118,7 +116,6 @@ class SearchLinkNode(BaseNode):
):
try:
- # Primary approach: Regular expression to extract links
links = re.findall(r'https?://[^\s"<>\]]+', str(chunk.page_content))
if not self.filter_links:
@@ -140,7 +137,6 @@ class SearchLinkNode(BaseNode):
self.seen_links.update(relevant_links)
except Exception as e:
- # Fallback approach: Using the LLM to extract links
self.logger.error(f"Error extracting links: {e}. Falling back to LLM.")
merge_prompt = PromptTemplate(
diff --git a/scrapegraphai/utils/copy.py b/scrapegraphai/utils/copy.py
index 2defbfa3..d6bb839a 100644
--- a/scrapegraphai/utils/copy.py
+++ b/scrapegraphai/utils/copy.py
@@ -1,3 +1,6 @@
+"""
+copy module
+"""
import copy
from typing import Any, Dict, Optional
from pydantic.v1 import BaseModel
@@ -24,52 +27,36 @@ def safe_deepcopy(obj: Any) -> Any:
"""
try:
-
- # Try to use copy.deepcopy first
return copy.deepcopy(obj)
except (TypeError, AttributeError) as e:
- # If deepcopy fails, handle specific types manually
-
- # Handle dictionaries
if isinstance(obj, dict):
new_obj = {}
-
for k, v in obj.items():
new_obj[k] = safe_deepcopy(v)
return new_obj
- # Handle lists
elif isinstance(obj, list):
new_obj = []
-
for v in obj:
new_obj.append(safe_deepcopy(v))
return new_obj
- # Handle tuples (immutable, but might contain mutable objects)
elif isinstance(obj, tuple):
new_obj = tuple(safe_deepcopy(v) for v in obj)
-
return new_obj
- # Handle frozensets (immutable, but might contain mutable objects)
elif isinstance(obj, frozenset):
new_obj = frozenset(safe_deepcopy(v) for v in obj)
return new_obj
- # Handle objects with attributes
elif hasattr(obj, "__dict__"):
- # If an object cannot be deep copied, then the sub-properties of \
- # the object will not be analyzed and shallow copy will be used directly.
try:
return copy.copy(obj)
except (TypeError, AttributeError):
raise DeepCopyError(f"Cannot deep copy the object of type {type(obj)}") from e
- # Attempt shallow copy as a fallback
try:
return copy.copy(obj)
except (TypeError, AttributeError):
raise DeepCopyError(f"Cannot deep copy the object of type {type(obj)}") from e
-
diff --git a/scrapegraphai/utils/parse_state_keys.py b/scrapegraphai/utils/parse_state_keys.py
index f4bd2ea5..79de329c 100644
--- a/scrapegraphai/utils/parse_state_keys.py
+++ b/scrapegraphai/utils/parse_state_keys.py
@@ -3,7 +3,6 @@ Parse_state_key module
"""
import re
-
def parse_expression(expression, state: dict) -> list:
"""
Parses a complex boolean expression involving state keys.
@@ -22,7 +21,8 @@ def parse_expression(expression, state: dict) -> list:
Example:
>>> parse_expression("user_input & (relevant_chunks | parsed_document | document)",
- {"user_input": None, "document": None, "parsed_document": None, "relevant_chunks": None})
+ {"user_input": None, "document": None,
+ "parsed_document": None, "relevant_chunks": None})
['user_input', 'relevant_chunks', 'parsed_document', 'document']
This function evaluates the expression to determine the
@@ -69,7 +69,6 @@ def parse_expression(expression, state: dict) -> list:
return [elem.strip() for elem in and_segment if elem.strip() in state]
return []
- # Helper function to evaluate expressions with parentheses
def evaluate_expression(expression):
while '(' in expression:
start = expression.rfind('(')
diff --git a/scrapegraphai/utils/prettify_exec_info.py b/scrapegraphai/utils/prettify_exec_info.py
index 8cfef81a..07a36e49 100644
--- a/scrapegraphai/utils/prettify_exec_info.py
+++ b/scrapegraphai/utils/prettify_exec_info.py
@@ -12,10 +12,12 @@ def prettify_exec_info(complete_result: list[dict]) -> pd.DataFrame:
complete_result (list[dict]): The complete execution information of the graph.
Returns:
- pd.DataFrame: A DataFrame that organizes the execution information for better readability and analysis.
+ pd.DataFrame: A DataFrame that organizes the execution information
+ for better readability and analysis.
Example:
- >>> prettify_exec_info([{'node': 'A', 'status': 'success'}, {'node': 'B', 'status': 'failure'}])
+ >>> prettify_exec_info([{'node': 'A', 'status': 'success'},
+ {'node': 'B', 'status': 'failure'}])
DataFrame with columns 'node' and 'status' showing execution results for each node.
"""
diff --git a/scrapegraphai/utils/research_web.py b/scrapegraphai/utils/research_web.py
index fe7902d3..0a10c8f2 100644
--- a/scrapegraphai/utils/research_web.py
+++ b/scrapegraphai/utils/research_web.py
@@ -62,13 +62,12 @@ def search_on_web(query: str, search_engine: str = "Google",
url = f"http://localhost:{port}"
params = {"q": query, "format": "json"}
- # Send the GET request to the server
response = requests.get(url, params=params)
- # Parse the response and limit to the specified max_results
data = response.json()
limited_results = data["results"][:max_results]
return limited_results
else:
- raise ValueError("The only search engines available are DuckDuckGo, Google, Bing, or SearXNG")
+ raise ValueError("""The only search engines available are
+ DuckDuckGo, Google, Bing, or SearXNG""")
diff --git a/scrapegraphai/utils/sys_dynamic_import.py b/scrapegraphai/utils/sys_dynamic_import.py
index 14910b3f..aa45a9b1 100644
--- a/scrapegraphai/utils/sys_dynamic_import.py
+++ b/scrapegraphai/utils/sys_dynamic_import.py
@@ -3,11 +3,9 @@ high-level module for dynamic importing of python modules at runtime
source code inspired by https://gist.github.com/DiTo97/46f4b733396b8d7a8f1d4d22db902cfc
"""
-
import sys
import typing
import importlib.util
-
if typing.TYPE_CHECKING:
import types