Skip to content

Python scraper based on AI

remove asdt

VinciGit007ced0d056423
diff --git a/scrapegraphai/asdt/__init__.py b/scrapegraphai/asdt/__init__.py
deleted file mode 100644
index 539534d6..00000000
--- a/scrapegraphai/asdt/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
- __init__.py file for asdt module.
-"""
-
-from .dom_tree import DOMTree
diff --git a/scrapegraphai/asdt/dom_tree.py b/scrapegraphai/asdt/dom_tree.py
deleted file mode 100644
index 50b2e179..00000000
--- a/scrapegraphai/asdt/dom_tree.py
+++ /dev/null
@@ -1,52 +0,0 @@
-from bs4 import BeautifulSoup, Comment, NavigableString, Tag
-from .tree import Tree
-from .tree_node import TreeNode
-
-class DOMTree(Tree):
- def __init__(self, html_content):
- super().__init__()
- self.root = TreeNode('document')
- self.build_dom_tree(BeautifulSoup(html_content, 'html.parser'), self.root)
-
- def build_dom_tree(self, soup_node, tree_node):
- for child in soup_node.children:
- if isinstance(child, Comment):
- continue # Skip comments
- elif isinstance(child, NavigableString):
- text = child.strip()
- if text:
- new_node = TreeNode(value='text', attributes={'content': text})
- tree_node.add_child(new_node)
- new_node.finalize_node()
- elif isinstance(child, Tag):
- new_node = TreeNode(value=child.name, attributes=child.attrs)
- tree_node.add_child(new_node)
- self.build_dom_tree(child, new_node)
-
- def collect_text_nodes(self, exclude_script=True):
- texts = []
- metadatas = []
-
- def collect(node):
- # If node is a text node, collect its data
- if node.value == 'text':
- texts.append(node.attributes['content'])
- metadatas.append({
- 'root_path': node.root_path,
- 'closest_fork_path': node.closest_fork_path
- })
-
- # Traverse the DOM tree to collect text nodes and their metadata
- def traverse_for_text(node):
- # Skip traversal into script tags, but continue for other nodes
- if exclude_script and node.value == 'script':
- return # Skip script tags
-
- if node.leads_to_text or node.value == 'text':
- collect(node)
- for child in node.children:
- traverse_for_text(child)
-
- traverse_for_text(self.root)
- return texts, metadatas
-
diff --git a/scrapegraphai/asdt/tree.py b/scrapegraphai/asdt/tree.py
deleted file mode 100644
index be95f8e6..00000000
--- a/scrapegraphai/asdt/tree.py
+++ /dev/null
@@ -1,98 +0,0 @@
-from graphviz import Digraph
-
-class Tree:
- def __init__(self, root=None):
- self.root = root
-
- def traverse(self, visit_func):
- def _traverse(node):
- if node:
- visit_func(node)
- for child in node.children:
- _traverse(child)
- _traverse(self.root)
-
- def get_subtrees(self):
- # Retrieves all subtrees rooted at fork nodes
- return self.root.get_subtrees() if self.root else []
-
- def generate_subtree_dicts(self):
- subtree_dicts = []
-
- def aggregate_text_under_fork(fork_node):
- text_aggregate = {
- "content": [],
- "path_to_fork": ""
- }
- for child in fork_node.children:
- if child.value == 'text':
- text_aggregate["content"].append(child.attributes['content'])
- elif child.is_fork:
- continue
- else:
- for sub_child in child.children:
- text_aggregate["content"].append(sub_child.attributes)
-
- text_aggregate["path_to_fork"] = fork_node.closest_fork_path
- return text_aggregate
-
- def process_node(node):
- if node.is_fork:
- texts = aggregate_text_under_fork(node)
- if texts["content"]: # Only add if there's text content
- subtree_dicts.append({
- node.value: {
- "text": texts,
- "path_to_fork": texts["path_to_fork"],
- }
- })
- for child in node.children:
- process_node(child)
-
- process_node(self.root)
- return subtree_dicts
-
- def visualize(self, exclude_tags = ['script']):
- def add_nodes_edges(tree_node, graph):
- if tree_node:
- # Skip excluded tags
- if tree_node.value in exclude_tags:
- return
-
- # Format node label to include attributes
- attr_str = None
- label = f"{tree_node.value}\n[{attr_str}]" if attr_str else tree_node.value
- # Determine color based on node properties
- if tree_node.value == 'text':
- color = 'red' # Text nodes
- elif tree_node.is_fork:
- color = 'green' # Fork nodes
- elif tree_node.leads_to_text:
- color = 'lightblue2' # Nodes leading to text
- else:
- color = 'white' # Nodes that do not lead to text and are not forks
-
- # Customize node appearance
- graph.node(name=str(id(tree_node)), label=label,
- fontsize='12', shape='ellipse', color=color, fontcolor='black')
-
- if tree_node.parent:
- graph.edge(str(id(tree_node.parent)), str(id(tree_node)), fontsize='10')
-
- for child in tree_node.children:
- add_nodes_edges(child, graph)
-
-
- # Initialize Digraph, set graph and node attributes
- graph = Digraph()
- # graph.attr(size='10,10', dpi='300') # Set higher DPI for better image resolution
- graph.attr('node', style='filled', fontname='Helvetica')
- graph.attr('edge', fontname='Helvetica')
-
- add_nodes_edges(self.root, graph)
- graph.render('tree_visualization', view=True, format='svg') # Change format to SVG for vectorized output
-
- return graph
-
- def __repr__(self):
- return f"Tree(root={self.root})"
\ No newline at end of file
diff --git a/scrapegraphai/asdt/tree_node.py b/scrapegraphai/asdt/tree_node.py
deleted file mode 100644
index 636cb5c1..00000000
--- a/scrapegraphai/asdt/tree_node.py
+++ /dev/null
@@ -1,114 +0,0 @@
-from .tree import Tree
-
-class TreeNode:
- def __init__(self, value=None, attributes=None, children=None, parent=None, depth=0):
- self.value = value
- self.attributes = attributes if attributes is not None else {}
- self.children = children if children is not None else []
- self.parent = parent
- self.depth = depth
- # Flag to track if the subtree leads to text
- self.leads_to_text = False
- # Flags to track if the subtree has a direct leaf node
- self.has_direct_leaves = False
- self.root_path = self._compute_root_path()
- self.closest_fork_path = self._compute_fork_path()
- self.structure_hash = None
- self.content_hash = None
-
- def add_child(self, child_node):
- child_node.parent = self
- child_node.depth = self.depth + 1
- self.children.append(child_node)
- child_node.update_paths()
- self.update_leads_to_text()
- self.update_hashes() # Update hashes when the structure changes
-
- def update_hashes(self):
- self.structure_hash = self.hash_subtree_structure(self)
- self.content_hash = self.hash_subtree_content(self)
-
- def update_paths(self):
- self.root_path = self._compute_root_path()
- self.closest_fork_path = self._compute_fork_path()
-
- def update_leads_to_text(self):
- # Check if any child leads to text or is a text node
- if any(child.value == 'text' or child.leads_to_text for child in self.children):
- self.leads_to_text = True
- # Update the flag up the tree
- if self.parent and not self.parent.leads_to_text:
- self.parent.update_leads_to_text()
-
- def _compute_root_path(self):
- path = []
- current = self
- while current.parent:
- path.append(current.value)
- current = current.parent
- path.append('root') # Append 'root' to start of the path
- return '>'.join(reversed(path))
-
- def _compute_fork_path(self):
- path = []
- current = self
- while current.parent and len(current.parent.children) == 1:
- path.append(current.value)
- current = current.parent
- path.append(current.value) # Add the fork or root node
- return '>'.join(reversed(path))
-
- def finalize_node(self):
- if self.is_text and self.is_leaf:
- self.update_direct_leaves_flag()
-
- def update_direct_leaves_flag(self):
- ancestor = self.parent
- while ancestor and len(ancestor.children) == 1:
- ancestor = ancestor.parent
- if ancestor and ancestor.is_fork:
- ancestor.has_direct_leaves = True
-
- def get_subtrees(self, direct_leaves=False):
- # This method finds and returns subtrees rooted at this node and all descendant forks
- # Optionally filters to include only those with direct leaves beneath fork nodes
- subtrees = []
- if self.is_fork and (not direct_leaves or self.has_direct_leaves):
- subtrees.append(Tree(root=self))
- for child in self.children:
- subtrees.extend(child.get_subtrees(direct_leaves=direct_leaves))
- return subtrees
-
- def hash_subtree_structure(self, node):
- """ Recursively generate a hash for the subtree structure. """
- if node.is_leaf:
- return hash((node.value,)) # Simple hash for leaf nodes
- child_hashes = tuple(self.hash_subtree_structure(child) for child in node.children)
- return hash((node.value, child_hashes))
-
- def hash_subtree_content(self, node):
- """ Generate a hash based on the concatenated text of the subtree. """
- text_content = self.get_all_text(node).lower().strip()
- return hash(text_content)
-
- def get_all_text(self, node):
- """ Recursively get all text from a node and its descendants. """
- text = node.attributes.get('content', '') if node.value == 'text' else ''
- for child in node.children:
- text += self.get_all_text(child)
- return text
-
- def __repr__(self):
- return f"TreeNode(value={self.value}, leads_to_text={self.leads_to_text}, is_fork={self.is_fork})"
-
- @property
- def is_fork(self):
- return len(self.children) > 1
-
- @property
- def is_leaf(self):
- return len(self.children) == 0
-
- @property
- def is_text(self):
- return self.value == 'text'
\ No newline at end of file
diff --git a/scrapegraphai/builders/__init__.py b/scrapegraphai/builders/__init__.py
deleted file mode 100644
index 03fd2d1a..00000000
--- a/scrapegraphai/builders/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""
- __init__.py file for builders folder
-"""
-
-from .graph_builder import GraphBuilder
diff --git a/scrapegraphai/builders/graph_builder.py b/scrapegraphai/builders/graph_builder.py
deleted file mode 100644
index 7280c50b..00000000
--- a/scrapegraphai/builders/graph_builder.py
+++ /dev/null
@@ -1,168 +0,0 @@
-"""
-GraphBuilder Module
-"""
-
-from langchain_core.prompts import ChatPromptTemplate
-from langchain.chains import create_extraction_chain
-from ..models import OpenAI, Gemini
-from ..helpers import nodes_metadata, graph_schema
-
-
-class GraphBuilder:
- """
- GraphBuilder is a dynamic tool for constructing web scraping graphs based on user prompts.
- It utilizes a natural language understanding model to interpret user prompts and
- automatically generates a graph configuration for scraping web content.
-
- Attributes:
- prompt (str): The user's natural language prompt for the scraping task.
- llm (ChatOpenAI): An instance of the ChatOpenAI class configured
- with the specified llm_config.
- nodes_description (str): A string description of all available nodes and their arguments.
- chain (LLMChain): The extraction chain responsible for
- processing the prompt and creating the graph.
-
- Methods:
- build_graph(): Executes the graph creation process based on the user prompt
- and returns the graph configuration.
- convert_json_to_graphviz(json_data): Converts a JSON graph configuration
- to a Graphviz object for visualization.
-
- Args:
- prompt (str): The user's natural language prompt describing the desired scraping operation.
- url (str): The target URL from which data is to be scraped.
- llm_config (dict): Configuration parameters for the
- language model, where 'api_key' is mandatory,
- and 'model_name', 'temperature', and 'streaming' can be optionally included.
-
- Raises:
- ValueError: If 'api_key' is not included in llm_config.
- """
-
- def __init__(self, user_prompt: str, config: dict):
- """
- Initializes the GraphBuilder with a user prompt and language model configuration.
- """
- self.user_prompt = user_prompt
- self.config = config
- self.llm = self._create_llm(config["llm"])
- self.nodes_description = self._generate_nodes_description()
- self.chain = self._create_extraction_chain()
-
- def _create_llm(self, llm_config: dict):
- """
- Creates an instance of the OpenAI class with the provided language model configuration.
-
- Returns:
- OpenAI: An instance of the OpenAI class.
-
- Raises:
- ValueError: If 'api_key' is not provided in llm_config.
- """
- llm_defaults = {
- "temperature": 0,
- "streaming": True
- }
- # Update defaults with any LLM parameters that were provided
- llm_params = {**llm_defaults, **llm_config}
- if "api_key" not in llm_params:
- raise ValueError("LLM configuration must include an 'api_key'.")
-
- # select the model based on the model name
- if "gpt-" in llm_params["model"]:
- return OpenAI(llm_params)
- elif "gemini" in llm_params["model"]:
- return Gemini(llm_params)
- raise ValueError("Model not supported")
-
- def _generate_nodes_description(self):
- """
- Generates a string description of all available nodes and their arguments.
-
- Returns:
- str: A string description of all available nodes and their arguments.
- """
-
- return "\n".join([
- f"""- {node}: {data["description"]} (Type: {data["type"]},
- Args: {", ".join(data["args"].keys())})"""
- for node, data in nodes_metadata.items()
- ])
-
- def _create_extraction_chain(self):
- """
- Creates an extraction chain for processing the user prompt and
- generating the graph configuration.
-
- Returns:
- LLMChain: An instance of the LLMChain class.
- """
-
- create_graph_prompt_template = """
- You are an AI that designs direct graphs for web scraping tasks.
- Your goal is to create a web scraping pipeline that is efficient and tailored to the user's requirements.
- You have access to a set of default nodes, each with specific capabilities:
-
- {nodes_description}
-
- Based on the user's input: "{input}", identify the essential nodes required for the task and suggest a graph configuration that outlines the flow between the chosen nodes.
- """.format(nodes_description=self.nodes_description, input="{input}")
- extraction_prompt = ChatPromptTemplate.from_template(
- create_graph_prompt_template)
- return create_extraction_chain(prompt=extraction_prompt, schema=graph_schema, llm=self.llm)
-
- def build_graph(self):
- """
- Executes the graph creation process based on the user prompt and
- returns the graph configuration.
-
- Returns:
- dict: A JSON representation of the graph configuration.
- """
- return self.chain.invoke(self.user_prompt)
-
- @staticmethod
- def convert_json_to_graphviz(json_data, format: str = 'pdf'):
- """
- Converts a JSON graph configuration to a Graphviz object for visualization.
-
- Args:
- json_data (dict): A JSON representation of the graph configuration.
-
- Returns:
- graphviz.Digraph: A Graphviz object representing the graph configuration.
- """
- try:
- import graphviz
- except ImportError:
- raise ImportError("The 'graphviz' library is required for this functionality. "
- "Please install it from 'https://graphviz.org/download/'.")
-
- graph = graphviz.Digraph(comment='ScrapeGraphAI Generated Graph', format=format,
- node_attr={'color': 'lightblue2', 'style': 'filled'})
-
- graph_config = json_data["text"][0]
-
- # Retrieve nodes, edges, and the entry point from the JSON data
- nodes = graph_config.get('nodes', [])
- edges = graph_config.get('edges', [])
- entry_point = graph_config.get('entry_point')
-
- # Add nodes to the graph
- for node in nodes:
- # If this node is the entry point, use a double circle to denote it
- if node['node_name'] == entry_point:
- graph.node(node['node_name'], shape='doublecircle')
- else:
- graph.node(node['node_name'])
-
- # Add edges to the graph
- for edge in edges:
- # An edge could potentially have multiple 'to' nodes if it's from a conditional node
- if isinstance(edge['to'], list):
- for to_node in edge['to']:
- graph.edge(edge['from'], to_node)
- else:
- graph.edge(edge['from'], edge['to'])
-
- return graph
diff --git a/scrapegraphai/docloaders/__init__.py b/scrapegraphai/docloaders/__init__.py
deleted file mode 100644
index a9e45407..00000000
--- a/scrapegraphai/docloaders/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-"""__init__.py file for docloaders folder"""
-
-from .chromium import ChromiumLoader
diff --git a/scrapegraphai/docloaders/chromium.py b/scrapegraphai/docloaders/chromium.py
deleted file mode 100644
index 7d499245..00000000
--- a/scrapegraphai/docloaders/chromium.py
+++ /dev/null
@@ -1,126 +0,0 @@
-import asyncio
-import logging
-from typing import Any, AsyncIterator, Iterator, List, Optional
-
-from langchain_community.document_loaders.base import BaseLoader
-from langchain_core.documents import Document
-
-from ..utils import Proxy, dynamic_import, parse_or_search_proxy
-
-
-logger = logging.getLogger(__name__)
-
-
-class ChromiumLoader(BaseLoader):
- """scrapes HTML pages from URLs using a (headless) instance of the
- Chromium web driver with proxy protection
-
- Attributes:
- backend: The web driver backend library; defaults to 'playwright'.
- browser_config: A dictionary containing additional browser kwargs.
- headless: whether to run browser in headless mode.
- proxy: A dictionary containing proxy settings; None disables protection.
- urls: A list of URLs to scrape content from.
- """
-
- def __init__(
- self,
- urls: List[str],
- *,
- backend: str = "playwright",
- headless: bool = True,
- proxy: Optional[Proxy] = None,
- **kwargs: Any,
- ):
- """Initialize the loader with a list of URL paths.
-
- Args:
- backend: The web driver backend library; defaults to 'playwright'.
- headless: whether to run browser in headless mode.
- proxy: A dictionary containing proxy information; None disables protection.
- urls: A list of URLs to scrape content from.
- kwargs: A dictionary containing additional browser kwargs.
-
- Raises:
- ImportError: If the required backend package is not installed.
- """
- message = (
- f"{backend} is required for ChromiumLoader. "
- f"Please install it with `pip install {backend}`."
- )
-
- dynamic_import(backend, message)
-
- self.backend = backend
- self.browser_config = kwargs
- self.headless = headless
- self.proxy = parse_or_search_proxy(proxy) if proxy else None
- self.urls = urls
-
- async def ascrape_playwright(self, url: str) -> str:
- """
- Asynchronously scrape the content of a given URL using Playwright's async API.
-
- Args:
- url (str): The URL to scrape.
-
- Returns:
- str: The scraped HTML content or an error message if an exception occurs.
-
- """
- from playwright.async_api import async_playwright
-
- logger.info("Starting scraping...")
- results = ""
- async with async_playwright() as p:
- browser = await p.chromium.launch(
- headless=self.headless, proxy=self.proxy, **self.browser_config
- )
- try:
- page = await browser.new_page()
- await page.goto(url)
- results = await page.content() # Simply get the HTML content
- logger.info("Content scraped")
- except Exception as e:
- results = f"Error: {e}"
- await browser.close()
- return results
-
- def lazy_load(self) -> Iterator[Document]:
- """
- Lazily load text content from the provided URLs.
-
- This method yields Documents one at a time as they're scraped,
- instead of waiting to scrape all URLs before returning.
-
- Yields:
- Document: The scraped content encapsulated within a Document object.
-
- """
- scraping_fn = getattr(self, f"ascrape_{self.backend}")
-
- for url in self.urls:
- html_content = asyncio.run(scraping_fn(url))
- metadata = {"source": url}
- yield Document(page_content=html_content, metadata=metadata)
-
- async def alazy_load(self) -> AsyncIterator[Document]:
- """
- Asynchronously load text content from the provided URLs.
-
- This method leverages asyncio to initiate the scraping of all provided URLs
- simultaneously. It improves performance by utilizing concurrent asynchronous
- requests. Each Document is yielded as soon as its content is available,
- encapsulating the scraped content.
-
- Yields:
- Document: A Document object containing the scraped content, along with its
- source URL as metadata.
- """
- scraping_fn = getattr(self, f"ascrape_{self.backend}")
-
- tasks = [scraping_fn(url) for url in self.urls]
- results = await asyncio.gather(*tasks)
- for url, content in zip(self.urls, results):
- metadata = {"source": url}
- yield Document(page_content=content, metadata=metadata)