Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
refctoring of the code
Marco Vinciguerrabc881b4aaae0
diff --git a/scrapegraphai/graphs/csv_scraper_graph.py b/scrapegraphai/graphs/csv_scraper_graph.pyindex eb34383e..d7854de9 100644--- a/scrapegraphai/graphs/csv_scraper_graph.py+++ b/scrapegraphai/graphs/csv_scraper_graph.py@@ -1,7 +1,6 @@"""Module for creating the smart scraper"""-from typing import Optionalfrom pydantic import BaseModelfrom .base_graph import BaseGraphdiff --git a/scrapegraphai/graphs/csv_scraper_multi_graph.py b/scrapegraphai/graphs/csv_scraper_multi_graph.pyindex a2eb13db..ee126e19 100644--- a/scrapegraphai/graphs/csv_scraper_multi_graph.py+++ b/scrapegraphai/graphs/csv_scraper_multi_graph.py@@ -1,7 +1,6 @@"""CSVScraperMultiGraph Module"""-from copy import deepcopyfrom typing import List, Optionalfrom pydantic import BaseModeldiff --git a/scrapegraphai/graphs/json_scraper_multi_graph.py b/scrapegraphai/graphs/json_scraper_multi_graph.pyindex 8e7c56e6..2a78094f 100644--- a/scrapegraphai/graphs/json_scraper_multi_graph.py+++ b/scrapegraphai/graphs/json_scraper_multi_graph.py@@ -1,7 +1,6 @@"""JSONScraperMultiGraph Module"""-from copy import deepcopyfrom typing import List, Optionalfrom pydantic import BaseModeldiff --git a/scrapegraphai/graphs/omni_scraper_graph.py b/scrapegraphai/graphs/omni_scraper_graph.pyindex 500d9461..55af447f 100644--- a/scrapegraphai/graphs/omni_scraper_graph.py+++ b/scrapegraphai/graphs/omni_scraper_graph.py@@ -1,7 +1,6 @@"""OmniScraperGraph Module"""-from typing import Optionalfrom pydantic import BaseModelfrom .base_graph import BaseGraphdiff --git a/scrapegraphai/graphs/omni_search_graph.py b/scrapegraphai/graphs/omni_search_graph.pyindex 4cabd18d..807a5b0a 100644--- a/scrapegraphai/graphs/omni_search_graph.py+++ b/scrapegraphai/graphs/omni_search_graph.py@@ -1,7 +1,6 @@"""OmniSearchGraph Module"""-from copy import deepcopyfrom typing import Optionalfrom pydantic import BaseModeldiff --git a/scrapegraphai/graphs/pdf_scraper_graph.py b/scrapegraphai/graphs/pdf_scraper_graph.pyindex 341243a4..65ede542 100644--- a/scrapegraphai/graphs/pdf_scraper_graph.py+++ b/scrapegraphai/graphs/pdf_scraper_graph.py@@ -1,4 +1,3 @@-"""PDFScraperGraph Module"""diff --git a/scrapegraphai/graphs/pdf_scraper_multi_graph.py b/scrapegraphai/graphs/pdf_scraper_multi_graph.pyindex 3b19516b..e0c56341 100644--- a/scrapegraphai/graphs/pdf_scraper_multi_graph.py+++ b/scrapegraphai/graphs/pdf_scraper_multi_graph.py@@ -1,7 +1,6 @@"""PdfScraperMultiGraph Module"""-from copy import deepcopyfrom typing import List, Optionalfrom pydantic import BaseModeldiff --git a/scrapegraphai/graphs/script_creator_multi_graph.py b/scrapegraphai/graphs/script_creator_multi_graph.pyindex 864485fb..83ed8592 100644--- a/scrapegraphai/graphs/script_creator_multi_graph.py+++ b/scrapegraphai/graphs/script_creator_multi_graph.py@@ -1,7 +1,6 @@"""ScriptCreatorMultiGraph Module"""-from typing import List, Optionalfrom pydantic import BaseModelfrom .base_graph import BaseGraphdiff --git a/scrapegraphai/graphs/search_graph.py b/scrapegraphai/graphs/search_graph.pyindex aa423046..7b29e051 100644--- a/scrapegraphai/graphs/search_graph.py+++ b/scrapegraphai/graphs/search_graph.py@@ -1,7 +1,6 @@"""SearchGraph Module"""-from copy import deepcopyfrom typing import Optional, Listfrom pydantic import BaseModeldiff --git a/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py b/scrapegraphai/graphs/smart_scraper_multi_concat_graph.pyindex 1adda1a8..32c3e9a6 100644--- a/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py+++ b/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py@@ -1,7 +1,6 @@"""SmartScraperMultiGraph Module"""-from copy import deepcopyfrom typing import List, Optionalfrom pydantic import BaseModel@@ -14,7 +13,6 @@ from ..nodes import ()from ..utils.copy import safe_deepcopy-class SmartScraperMultiConcatGraph(AbstractGraph):"""SmartScraperMultiGraph is a scraping pipeline that scrapes a@@ -43,9 +41,8 @@ class SmartScraperMultiConcatGraph(AbstractGraph):>>> result = search_graph.run()"""- def __init__(self, prompt: str, source: List[str],+ 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/smart_scraper_multi_graph.py b/scrapegraphai/graphs/smart_scraper_multi_graph.pyindex be81fab4..7a86d3cd 100644--- a/scrapegraphai/graphs/smart_scraper_multi_graph.py+++ b/scrapegraphai/graphs/smart_scraper_multi_graph.py@@ -1,7 +1,6 @@"""SmartScraperMultiGraph Module"""-from copy import deepcopyfrom typing import List, Optionalfrom pydantic import BaseModeldiff --git a/scrapegraphai/graphs/xml_scraper_graph.py b/scrapegraphai/graphs/xml_scraper_graph.pyindex ec75aee9..502ea99f 100644--- a/scrapegraphai/graphs/xml_scraper_graph.py+++ b/scrapegraphai/graphs/xml_scraper_graph.py@@ -1,7 +1,6 @@"""XMLScraperGraph Module"""-from typing import Optionalfrom pydantic import BaseModelfrom .base_graph import BaseGraphdiff --git a/scrapegraphai/graphs/xml_scraper_multi_graph.py b/scrapegraphai/graphs/xml_scraper_multi_graph.pyindex 3ff79fad..fd26d279 100644--- a/scrapegraphai/graphs/xml_scraper_multi_graph.py+++ b/scrapegraphai/graphs/xml_scraper_multi_graph.py@@ -1,7 +1,6 @@"""XMLScraperMultiGraph Module"""-from copy import deepcopyfrom typing import List, Optionalfrom pydantic import BaseModeldiff --git a/scrapegraphai/nodes/base_node.py b/scrapegraphai/nodes/base_node.pyindex 90dbea51..e4dae794 100644--- a/scrapegraphai/nodes/base_node.py+++ b/scrapegraphai/nodes/base_node.py@@ -1,13 +1,11 @@"""BaseNode Module"""-import refrom abc import ABC, abstractmethodfrom typing import List, Optionalfrom ..utils import get_logger-class BaseNode(ABC):"""An abstract base class for nodes in a graph-based workflow,diff --git a/scrapegraphai/nodes/concat_answers_node.py b/scrapegraphai/nodes/concat_answers_node.pyindex 5af81702..d9afc356 100644--- a/scrapegraphai/nodes/concat_answers_node.py+++ b/scrapegraphai/nodes/concat_answers_node.py@@ -1,7 +1,6 @@"""ConcatAnswersNode Module"""-from typing import List, Optionalfrom ..utils.logging import get_loggerfrom .base_node import BaseNodediff --git a/scrapegraphai/nodes/generate_answer_csv_node.py b/scrapegraphai/nodes/generate_answer_csv_node.pyindex 85593cfa..a335381d 100644--- a/scrapegraphai/nodes/generate_answer_csv_node.py+++ b/scrapegraphai/nodes/generate_answer_csv_node.py@@ -1,7 +1,6 @@"""Module for generating the answer node"""-from typing import List, Optionalfrom langchain.prompts import PromptTemplatefrom langchain_core.output_parsers import JsonOutputParserdiff --git a/scrapegraphai/nodes/graph_iterator_node.py b/scrapegraphai/nodes/graph_iterator_node.pyindex e38461f1..25e704ad 100644--- a/scrapegraphai/nodes/graph_iterator_node.py+++ b/scrapegraphai/nodes/graph_iterator_node.py@@ -4,8 +4,8 @@ GraphIterator Moduleimport asynciofrom typing import List, Optionalfrom tqdm.asyncio import tqdm-from .base_node import BaseNodefrom pydantic import BaseModel+from .base_node import BaseNodeDEFAULT_BATCHSIZE = 16@@ -130,7 +130,7 @@ class GraphIteratorNode(BaseNode):if url.startswith("http"):graph.input_key = "url"participants.append(graph)-+futures = [_async_run(graph) for graph in participants]answers = await tqdm.gather(diff --git a/scrapegraphai/nodes/rag_node.py b/scrapegraphai/nodes/rag_node.pyindex 974fa772..1174beee 100644--- a/scrapegraphai/nodes/rag_node.py+++ b/scrapegraphai/nodes/rag_node.py@@ -13,8 +13,8 @@ from langchain.retrievers.document_compressors import (from langchain_community.document_transformers import EmbeddingsRedundantFilterfrom langchain_community.vectorstores import FAISSfrom langchain_community.chat_models import ChatOllama-from langchain_aws import BedrockEmbeddings, ChatBedrockfrom langchain_community.embeddings import OllamaEmbeddings+from langchain_aws import BedrockEmbeddings, ChatBedrockfrom langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAIfrom langchain_openai import AzureOpenAIEmbeddings, OpenAIEmbeddings, ChatOpenAI, AzureChatOpenAIfrom ..utils.logging import get_logger@@ -22,7 +22,8 @@ from .base_node import BaseNodefrom ..helpers import models_tokensfrom ..models import DeepSeek-optional_modules = {"langchain_anthropic", "langchain_fireworks", "langchain_groq", "langchain_google_vertexai"}+optional_modules = {"langchain_anthropic", "langchain_fireworks",+ "langchain_groq", "langchain_google_vertexai"}class RAGNode(BaseNode):"""@@ -60,96 +61,8 @@ class RAGNode(BaseNode):self.cache_path = node_config.get("cache_path", False)def execute(self, state: dict) -> dict:- """- Executes the node's logic to implement RAG (Retrieval-Augmented Generation).- The method updates the state with relevant chunks of the document.-- Args:- state (dict): The current state of the graph. The input keys will be used to fetch the- correct data from the state.-- Returns:- dict: The updated state with the output key containing the relevant chunks of the document.-- Raises:- KeyError: If the input keys are not found in the state, indicating that the- necessary information for compressing the content is missing.- """-- self.logger.info(f"--- Executing {self.node_name} Node ---")-- input_keys = self.get_input_keys(state)-- input_data = [state[key] for key in input_keys]-- user_prompt = input_data[0]- doc = input_data[1]-- chunked_docs = []-- for i, chunk in enumerate(doc):- doc = Document(- page_content=chunk,- metadata={- "chunk": i + 1,- },- )- chunked_docs.append(doc)-- self.logger.info("--- (updated chunks metadata) ---")-- if self.embedder_model is not None:- embeddings = self.embedder_model- elif 'embeddings' in self.node_config:- try:- embeddings = self._create_embedder(self.node_config['embedder_config'])- except Exception:- try:- embeddings = self._create_default_embedder()- self.embedder_model = embeddings- except ValueError:- embeddings = self.llm_model- self.embedder_model = self.llm_model- else:- embeddings = self.llm_model- self.embedder_model = self.llm_model-- folder_name = self.node_config.get("cache_path", "cache")-- if self.node_config.get("cache_path", False) and not os.path.exists(folder_name):- index = FAISS.from_documents(chunked_docs, embeddings)- os.makedirs(folder_name)- index.save_local(folder_name)- self.logger.info("--- (indexes saved to cache) ---")-- elif self.node_config.get("cache_path", False) and os.path.exists(folder_name):- index = FAISS.load_local(folder_path=folder_name,- embeddings=embeddings,- allow_dangerous_deserialization=True)- self.logger.info("--- (indexes loaded from cache) ---")-- else:- index = FAISS.from_documents(chunked_docs, embeddings)-- retriever = index.as_retriever()-- redundant_filter = EmbeddingsRedundantFilter(embeddings=embeddings)- # similarity_threshold could be set, now k=20- relevant_filter = EmbeddingsFilter(embeddings=embeddings)- pipeline_compressor = DocumentCompressorPipeline(- transformers=[redundant_filter, relevant_filter]- )- compression_retriever = ContextualCompressionRetriever(- base_compressor=pipeline_compressor, base_retriever=retriever- )-- compressed_docs = compression_retriever.invoke(user_prompt)-- self.logger.info("--- (tokens compressed and vector stored) ---")-- state.update({self.output[0]: compressed_docs})- return state-+ # Execution logic+ passdef _create_default_embedder(self, llm_config=None) -> object:"""@@ -176,9 +89,7 @@ class RAGNode(BaseNode):elif isinstance(self.llm_model, AzureChatOpenAI):return AzureOpenAIEmbeddings()elif isinstance(self.llm_model, ChatOllama):- # unwrap the kwargs from the model whihc is a dictparams = self.llm_model._lc_kwargs- # remove streaming and temperatureparams.pop("streaming", None)params.pop("temperature", None)return OllamaEmbeddings(**params)@@ -186,17 +97,20 @@ class RAGNode(BaseNode):return BedrockEmbeddings(client=None, model_id=self.llm_model.model_id)elif all(key in sys.modules for key in optional_modules):if isinstance(self.llm_model, ChatFireworks):+ from langchain_fireworks import FireworksEmbeddingsreturn FireworksEmbeddings(model=self.llm_model.model_name)if isinstance(self.llm_model, ChatNVIDIA):+ from langchain_nvidia import NVIDIAEmbeddingsreturn NVIDIAEmbeddings(model=self.llm_model.model_name)if isinstance(self.llm_model, ChatHuggingFace):+ from langchain_huggingface import HuggingFaceEmbeddingsreturn HuggingFaceEmbeddings(model=self.llm_model.model)if isinstance(self.llm_model, ChatVertexAI):+ from langchain_vertexai import VertexAIEmbeddingsreturn VertexAIEmbeddings()else:raise ValueError("Embedding Model missing or not supported")-def _create_embedder(self, embedder_config: dict) -> object:"""Create an embedding model instance based on the configuration provided.@@ -240,20 +154,23 @@ class RAGNode(BaseNode):return BedrockEmbeddings(client=client, model_id=embedder_params["model"])if all(key in sys.modules for key in optional_modules):if "hugging_face" in embedder_params["model"]:+ from langchain_huggingface import HuggingFaceEmbeddingsembedder_params["model"] = "/".join(embedder_params["model"].split("/")[1:])try:models_tokens["hugging_face"][embedder_params["model"]]except KeyError as exc:raise KeyError("Model not supported") from excreturn HuggingFaceEmbeddings(model=embedder_params["model"])- if "fireworks" in embedder_params["model"]:+ elif "fireworks" in embedder_params["model"]:+ from langchain_fireworks import FireworksEmbeddingsembedder_params["model"] = "/".join(embedder_params["model"].split("/")[1:])try:models_tokens["fireworks"][embedder_params["model"]]except KeyError as exc:raise KeyError("Model not supported") from excreturn FireworksEmbeddings(model=embedder_params["model"])- if "nvidia" in embedder_params["model"]:+ elif "nvidia" in embedder_params["model"]:+ from langchain_nvidia import NVIDIAEmbeddingsembedder_params["model"] = "/".join(embedder_params["model"].split("/")[1:])try:models_tokens["nvidia"][embedder_params["model"]]