Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
implemented graphbuilder class
PeriniM49c22ae15570
diff --git a/examples/schema_example.py b/examples/schema_example.pynew file mode 100644index 00000000..a29d270d--- /dev/null+++ b/examples/schema_example.py@@ -0,0 +1,25 @@+import os+from dotenv import load_dotenv+from scrapegraphai.builders import GraphBuilder++load_dotenv()+openai_key = os.getenv("OPENAI_APIKEY")+if not openai_key:+ print("Error: OpenAI API key not found in environment variables.")++# Define the configuration for the language model+llm_config = {+ "api_key": openai_key,+ "model_name": "gpt-3.5-turbo",+ "temperature": 0,+ "streaming": True+}++# Example usage of GraphBuilder+user_prompt = "I want to scrape all the links related to the cinema UCI and return me a JSON with the results."+graph_builder = GraphBuilder(user_prompt, llm_config)+graph_json = graph_builder.build_graph()++# Convert the resulting JSON to Graphviz format+graphviz_graph = graph_builder.convert_json_to_graphviz(graph_json)+graphviz_graph.render('custom_graph', view=True)diff --git a/scrapegraphai/builders/__init__.py b/scrapegraphai/builders/__init__.pynew file mode 100644index 00000000..4ab8b612--- /dev/null+++ b/scrapegraphai/builders/__init__.py@@ -0,0 +1,5 @@+"""+ __init__.py file for builders folder+"""++from .graph_builder import GraphBuilder\ No newline at end of filediff --git a/scrapegraphai/builders/graph_builder.py b/scrapegraphai/builders/graph_builder.pynew file mode 100644index 00000000..19e07403--- /dev/null+++ b/scrapegraphai/builders/graph_builder.py@@ -0,0 +1,145 @@+from langchain_core.prompts import ChatPromptTemplate+from langchain.chains import create_extraction_chain+from langchain_openai import ChatOpenAI+from scrapegraphai.utils import nodes_metadata, graph_schema+import graphviz++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, llm_config: dict):+ """+ Initializes the GraphBuilder with a user prompt and language model configuration.+ """+ self.user_prompt = user_prompt+ self.llm_config = llm_config+ self.llm = self._create_llm()+ self.nodes_description = self._generate_nodes_description()+ self.chain = self._create_extraction_chain()++ def _create_llm(self):+ """+ Creates an instance of the ChatOpenAI class with the provided language model configuration.++ Returns:+ ChatOpenAI: An instance of the ChatOpenAI class.++ Raises:+ ValueError: If 'api_key' is not provided in llm_config.+ """+ llm_defaults = {+ "model_name": "gpt-3.5-turbo",+ "temperature": 0,+ "streaming": True+ }+ # Update defaults with any LLM parameters that were provided+ llm_params = {**llm_defaults, **self.llm_config}+ # Ensure the api_key is set, raise an error if it's not+ if "api_key" not in llm_params:+ raise ValueError("LLM configuration must include an 'api_key'.")+ # Create the ChatOpenAI instance with the provided and default parameters+ return ChatOpenAI(**llm_params)++ 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='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.+ """++ 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\ No newline at end of filediff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.pyindex 93c0172d..caaf9f05 100644--- a/scrapegraphai/graphs/smart_scraper_graph.py+++ b/scrapegraphai/graphs/smart_scraper_graph.py@@ -1,10 +1,12 @@-"""-Module for creating the smart scaper-"""from langchain_openai import ChatOpenAIfrom .base_graph import BaseGraph-from ..nodes import FetchHTMLNode, ConditionalNode, GetProbableTagsNode-from ..nodes import GenerateAnswerNode, ParseHTMLNode+from ..nodes import (+ FetchHTMLNode,+ ConditionalNode,+ GetProbableTagsNode,+ GenerateAnswerNode,+ ParseHTMLNode+ )class SmartScraper:@@ -104,5 +106,5 @@ class SmartScraper:"""inputs = {"user_input": self.prompt, "url": self.url}final_state = self.graph.execute(inputs)-+return final_state.get("answer", "No answer found.")diff --git a/scrapegraphai/info/dictionaries.py b/scrapegraphai/info/dictionaries.pydeleted file mode 100644index 60787642..00000000--- a/scrapegraphai/info/dictionaries.py+++ /dev/null@@ -1,40 +0,0 @@-"""-Module for defining dictionaries and token limits-"""--schema_example = {- "properties": {- "person_name": {"type": "string"},- "person_surname": {"type": "string"},- "profession": {"type": "string"},- "hobbies": {"type": "string"},- "projects": {- "type": "array",- "items": {- "type": "object",- "properties": {- "project_name": {"type": "string"},- "project_description": {"type": "string"},- "url": {"type": "string"}- },- "required": ["project_name", "project_description", "url"],- },- },- },- "required": ["person_name", "person_surname", "profession", "hobbies", "projects"],-}--models_tokens = {- "gpt-3.5-turbo-0125": 16385,- "gpt-3.5-turbo": 4096,- "gpt-3.5-turbo-1106": 16385,- "gpt-3.5-turbo-instruct": 4096,- "gpt-4-0125-preview": 128000,- "gpt-4-turbo-preview": 128000,- "gpt-4-1106-preview": 128000,- "gpt-4-vision-preview": 128000,- "gpt-4": 8192,- "gpt-4-0613": 8192,- "gpt-4-32k": 32768,- "gpt-4-32k-0613": 32768,-}diff --git a/scrapegraphai/models/__init__.py b/scrapegraphai/models/__init__.pynew file mode 100644index 00000000..0639abe6--- /dev/null+++ b/scrapegraphai/models/__init__.py@@ -0,0 +1,3 @@+"""+ __init__.py file for models folder+"""diff --git a/scrapegraphai/nodes/fetch_html_node.py b/scrapegraphai/nodes/fetch_html_node.pyindex 77b24179..5aa7b670 100644--- a/scrapegraphai/nodes/fetch_html_node.py+++ b/scrapegraphai/nodes/fetch_html_node.py@@ -3,8 +3,7 @@ Module for fetching the HTML node"""from .base_node import BaseNode-from ..utils.getter import _get_function-+from langchain_community.document_loaders import AsyncHtmlLoaderclass FetchHTMLNode(BaseNode):"""@@ -61,7 +60,8 @@ class FetchHTMLNode(BaseNode):print(f"Error: {e} not found in state.")raise- document = _get_function(url)+ loader = AsyncHtmlLoader(url)+ document = loader.load()state["document"] = documentdiff --git a/scrapegraphai/utils/__init__.py b/scrapegraphai/utils/__init__.pyindex 55afed18..a72f8b13 100644--- a/scrapegraphai/utils/__init__.py+++ b/scrapegraphai/utils/__init__.py@@ -1,4 +1,5 @@"""__init__.py file for utils folder"""-from .nodes_metadata import nodes_metadata\ No newline at end of file+from .nodes_metadata import nodes_metadata+from .schemas import graph_schema\ No newline at end of filediff --git a/scrapegraphai/utils/getter.py b/scrapegraphai/utils/getter.pydeleted file mode 100644index 4962d158..00000000--- a/scrapegraphai/utils/getter.py+++ /dev/null@@ -1,19 +0,0 @@-"""-Module for retrieving content from a URL-"""-from langchain_community.document_loaders import AsyncHtmlLoader---def _get_function(link: str) -> str:- """- It sends a GET request to the specified link with optional headers.-- Args:- link (str): The URL to send the GET request to.-- Returns:- str: The content of the response as a string.- """-- loader = AsyncHtmlLoader(link)- return loader.load()diff --git a/scrapegraphai/utils/nodes_metadata.py b/scrapegraphai/utils/nodes_metadata.pyindex b5b7b1b2..b576a755 100644--- a/scrapegraphai/utils/nodes_metadata.py+++ b/scrapegraphai/utils/nodes_metadata.py@@ -5,6 +5,7 @@ Nodes metadata for the scrapegraphai package.nodes_metadata = {"FetchHTMLNode": {"description": "Fetches HTML content from a given URL.",+ "type": "node","args": {"url": "The URL from which to fetch HTML content."},@@ -12,6 +13,7 @@ nodes_metadata = {},"GetProbableTagsNode": {"description": "Identifies probable HTML tags from a document based on a user's question.",+ "type": "node","args": {"user_input": "User's query or question.","document": "HTML content as a string."@@ -20,6 +22,7 @@ nodes_metadata = {},"ParseHTMLNode": {"description": "Parses HTML content to extract specific data.",+ "type": "node","args": {"document": "HTML content as a string.","tags": "List of HTML tags to focus on during parsing."@@ -28,6 +31,7 @@ nodes_metadata = {},"GenerateAnswerNode": {"description": "Generates an answer based on the user's input and parsed document.",+ "type": "node","args": {"user_input": "User's query or question.","parsed_document": "Data extracted from the HTML document."@@ -36,11 +40,27 @@ nodes_metadata = {},"ConditionalNode": {"description": "Decides the next node to execute based on a condition.",+ "type": "conditional_node","args": {"key_name": "The key in the state to check for a condition.","next_nodes": "A list of two nodes specifying the next node to execute based on the condition's outcome."},"returns": "The name of the next node to execute."+ },+ "ImageToTextNode": {+ "description": "Converts image content to text by extracting visual information and interpreting it.",+ "type": "node",+ "args": {+ "image_data": "Data of the image to be processed."+ },+ "returns": "Updated state with the textual description of the image under 'image_text' key."+ },+ "TextToSpeechNode": {+ "description": "Converts text into spoken words, allowing for auditory representation of the text.",+ "type": "node",+ "args": {+ "text": "The text to be converted into speech."+ },+ "returns": "Updated state with the speech audio file or data under 'speech_audio' key."}- # Add other nodes as necessary...}\ No newline at end of filediff --git a/scrapegraphai/utils/schemas.py b/scrapegraphai/utils/schemas.pynew file mode 100644index 00000000..1624eed6--- /dev/null+++ b/scrapegraphai/utils/schemas.py@@ -0,0 +1,57 @@+graph_schema = {+ "name": "ScrapeGraphAI Graph Configuration",+ "description": "JSON schema for representing graphs in the ScrapeGraphAI library",+ "type": "object",+ "properties": {+ "nodes": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "node_name": {+ "type": "string",+ "description": "The unique identifier for the node."+ },+ "node_type": {+ "type": "string",+ "description": "The type of node, must be 'node' or 'conditional_node'."+ },+ "args": {+ "type": "object",+ "description": "The arguments required for the node's execution."+ },+ "returns": {+ "type": "object",+ "description": "The return values of the node's execution."+ },+ },+ "required": ["node_name", "node_type", "args", "returns"]+ }+ },+ "edges": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "from": {+ "type": "string",+ "description": "The node_name of the starting node of the edge."+ },+ "to": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "An array containing the node_names of the ending nodes of the edge. If the 'from' node is a conditional node, this array must contain exactly two node_names."+ }+ },+ "required": ["from", "to"]+ }+ },+ "entry_point": {+ "type": "string",+ "description": "The node_name of the entry point node."+ }+ },+ "required": ["nodes", "edges", "entry_point"]+}\ No newline at end of filediff --git a/scrapegraphai/utils/token_calculator.py b/scrapegraphai/utils/token_calculator.pyindex eb2f2780..b3b0a6ed 100644--- a/scrapegraphai/utils/token_calculator.py+++ b/scrapegraphai/utils/token_calculator.py@@ -3,8 +3,21 @@ Module for truncatinh in chunks the messages"""from typing import Listimport tiktoken-from .info.dictionaries import models_tokens+models_tokens = {+ "gpt-3.5-turbo-0125": 16385,+ "gpt-3.5-turbo": 4096,+ "gpt-3.5-turbo-1106": 16385,+ "gpt-3.5-turbo-instruct": 4096,+ "gpt-4-0125-preview": 128000,+ "gpt-4-turbo-preview": 128000,+ "gpt-4-1106-preview": 128000,+ "gpt-4-vision-preview": 128000,+ "gpt-4": 8192,+ "gpt-4-0613": 8192,+ "gpt-4-32k": 32768,+ "gpt-4-32k-0613": 32768,+}def truncate_text_tokens(text: str, model: str, encoding_name: str) -> List[str]:"""