Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
dev: refactor dict on graph state
PeriniM20398a3059b5
diff --git a/examples/.env.example b/examples/.env.exampleindex 7e22ba13..42454237 100644--- a/examples/.env.example+++ b/examples/.env.example@@ -1 +1 @@-API_KEY="your openai.com api key"\ No newline at end of file+OPENAI_APIKEY="your openai.com api key"\ No newline at end of filediff --git a/examples/fetch_html_node_example.py b/examples/custom_graph.pysimilarity index 86%rename from examples/fetch_html_node_example.pyrename to examples/custom_graph.pyindex f32da32f..91d865ba 100644--- a/examples/fetch_html_node_example.py+++ b/examples/custom_graph.py@@ -11,7 +11,7 @@ from scrapegraphai.nodes import FetchHTMLNode, ParseHTMLNode, GenerateAnswerNode# load the environment variablesload_dotenv()-openai_key = os.getenv("API_KEY")+openai_key = os.getenv("OPENAI_APIKEY")if not openai_key:print("Error: OpenAI API key not found in environment variables.")@@ -44,9 +44,9 @@ graph = BaseGraph()# execute the graph-inputs = {"keys": {"user_input": "What is the title of the page?", "url": "https://example.com"}}+inputs = {"user_input": "What is the title of the page?", "url": "https://example.com"}result = graph.execute(inputs)# get the answer from the result-answer = result["keys"].get("answer", "No answer found.")+answer = result.get("answer", "No answer found.")print(answer)diff --git a/examples/smart_scraper.py b/examples/smart_scraper.pynew file mode 100644index 00000000..312b79b3--- /dev/null+++ b/examples/smart_scraper.py@@ -0,0 +1,22 @@+"""+Basic example of scraping pipeline using SmartScraper+"""+import os+from dotenv import load_dotenv+from scrapegraphai.graphs import SmartScraper++load_dotenv()++openai_key = os.getenv("OPENAI_APIKEY")+if not openai_key:+ print("Error: OpenAI API key not found in environment variables.")+llm_config = {+ "api_key": openai_key,+ "model_name": "gpt-3.5-turbo",+}++smart_scraper = SmartScraper("List me all the titles and project descriptions",+ "https://perinim.github.io/projects/", llm_config)++answer = smart_scraper.run()+print(answer)diff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.pyindex d04cd8f1..93c0172d 100644--- a/scrapegraphai/graphs/smart_scraper_graph.py+++ b/scrapegraphai/graphs/smart_scraper_graph.py@@ -102,6 +102,7 @@ class SmartScraper:Returns:str: The answer extracted from the web page, corresponding to the given prompt."""- inputs = {"keys": {"user_input": self.prompt, "url": self.url}}+ inputs = {"user_input": self.prompt, "url": self.url}final_state = self.graph.execute(inputs)- return final_state["keys"].get("answer", "No answer found.")++ return final_state.get("answer", "No answer found.")diff --git a/scrapegraphai/nodes/__init__.py b/scrapegraphai/nodes/__init__.pyindex 2bf1efb3..a1adb974 100644--- a/scrapegraphai/nodes/__init__.py+++ b/scrapegraphai/nodes/__init__.py@@ -6,3 +6,5 @@ from .conditional_node import ConditionalNodefrom .get_probable_tags_node import GetProbableTagsNodefrom .generate_answer_node import GenerateAnswerNodefrom .parse_html_node import ParseHTMLNode+from .text_to_speech_node import TextToSpeechNode+from .image_to_text_node import ImageToTextNodediff --git a/scrapegraphai/nodes/conditional_node.py b/scrapegraphai/nodes/conditional_node.pyindex 999d87a5..4ee2da85 100644--- a/scrapegraphai/nodes/conditional_node.py+++ b/scrapegraphai/nodes/conditional_node.py@@ -63,6 +63,6 @@ class ConditionalNode(BaseNode):str: The name of the next node to execute based on the presence of the key."""- if self.key_name in state.get("keys", {}) and len(state["keys"][self.key_name]) > 0:+ if self.key_name in state and len(state[self.key_name]) > 0:return self.next_nodes[0].node_namereturn self.next_nodes[1].node_namediff --git a/scrapegraphai/nodes/fetch_html_node.py b/scrapegraphai/nodes/fetch_html_node.pyindex 6b0df195..77b24179 100644--- a/scrapegraphai/nodes/fetch_html_node.py+++ b/scrapegraphai/nodes/fetch_html_node.py@@ -56,13 +56,13 @@ class FetchHTMLNode(BaseNode):necessary information to perform the operation is missing."""try:- url = state["keys"]["url"]+ url = state["url"]except KeyError as e:print(f"Error: {e} not found in state.")raisedocument = _get_function(url)- state["keys"]["document"] = document+ state["document"] = documentreturn statediff --git a/scrapegraphai/nodes/generate_answer_node.py b/scrapegraphai/nodes/generate_answer_node.pyindex 6e4dbc1c..5c83f54c 100644--- a/scrapegraphai/nodes/generate_answer_node.py+++ b/scrapegraphai/nodes/generate_answer_node.py@@ -59,14 +59,14 @@ class GenerateAnswerNode(BaseNode):print("---GENERATE ANSWER---")try:- user_input = state["keys"]["user_input"]- document = state["keys"]["document"]+ user_input = state["user_input"]+ document = state["document"]except KeyError as e:print(f"Error: {e} not found in state.")raise- parsed_document = state["keys"].get("parsed_document", None)- relevant_chunks = state["keys"].get("relevant_chunks", None)+ parsed_document = state.get("parsed_document", None)+ relevant_chunks = state.get("relevant_chunks", None)if relevant_chunks:context = relevant_chunks@@ -96,5 +96,5 @@ class GenerateAnswerNode(BaseNode):{"context": context, "question": user_input})# Update the state with the generated answer- state["keys"].update({"answer": answer})+ state.update({"answer": answer})return statediff --git a/scrapegraphai/nodes/get_probable_tags_node.py b/scrapegraphai/nodes/get_probable_tags_node.pyindex c73c7c3d..4861a3f9 100644--- a/scrapegraphai/nodes/get_probable_tags_node.py+++ b/scrapegraphai/nodes/get_probable_tags_node.py@@ -56,8 +56,8 @@ class GetProbableTagsNode(BaseNode):print("---GET PROBABLE TAGS---")try:- user_input = state["keys"]["user_input"]- url = state["keys"]["url"]+ user_input = state["user_input"]+ url = state["url"]except KeyError as e:print(f"Error: {e} not found in state.")raise@@ -84,5 +84,5 @@ class GetProbableTagsNode(BaseNode):print("Possible tags: ", *probable_tags)# Update the nested 'keys' dictionary with probable tags- state["keys"].update({"tags": probable_tags})+ state.update({"tags": probable_tags})return statediff --git a/scrapegraphai/nodes/parse_html_node.py b/scrapegraphai/nodes/parse_html_node.pynew file mode 100644index 00000000..e3309837--- /dev/null+++ b/scrapegraphai/nodes/parse_html_node.py@@ -0,0 +1,74 @@+"""+Module for parsing the HTML node+"""+from langchain_community.document_transformers import BeautifulSoupTransformer+from .base_node import BaseNode+++class ParseHTMLNode(BaseNode):+ """+ A node responsible for parsing HTML content from a document using specified tags.+ It uses BeautifulSoupTransformer for parsing, providing flexibility in extracting+ specific parts of an HTML document based on the tags provided in the state.++ This node enhances the scraping workflow by allowing for targeted extraction of+ content, thereby optimizing the processing of large HTML documents.++ Attributes:+ node_name (str): The unique identifier name for the node, defaulting to "ParseHTMLNode".+ node_type (str): The type of the node, set to "node" indicating a standard operational node.++ Args:+ node_name (str, optional): The unique identifier name for the node.+ Defaults to "ParseHTMLNode".++ Methods:+ execute(state): Parses the HTML document contained within the state using+ the specified tags, if provided, and updates the state with the parsed content.+ """++ def __init__(self, node_name="ParseHTMLNode"):+ """+ Initializes the ParseHTMLNode with a node name.+ """+ super().__init__(node_name, "node")++ def execute(self, state):+ """+ Executes the node's logic to parse the HTML document based on specified tags.+ If tags are provided in the state, the document is parsed accordingly; otherwise,+ the document remains unchanged. The method updates the state with either the original+ or parsed document under the 'parsed_document' key.++ Args:+ state (dict): The current state of the graph, expected to contain+ 'document' within 'keys', and optionally 'tags' for targeted parsing.++ Returns:+ dict: The updated state with the 'parsed_document' key containing the parsed content,+ if tags were provided, or the original document otherwise.++ Raises:+ KeyError: If 'document' is not found in the state, indicating that the necessary+ information for parsing is missing.+ """++ print("---PARSE HTML DOCUMENT---")+ try:+ document = state["document"]+ except KeyError as e:+ print(f"Error: {e} not found in state.")+ raise++ tags = state.get("tags", None)++ if not tags:+ print("No specific tags provided; returning document as is.")+ return state++ bs_transformer = BeautifulSoupTransformer()+ parsed_document = bs_transformer.transform_documents(+ document, tags_to_extract=tags)+ print("Document parsed with specified tags.")+ state.update({"parsed_document": parsed_document})+ return statediff --git a/scrapegraphai/nodes/text_to_speach_node.py b/scrapegraphai/nodes/text_to_speech_node.pysimilarity index 98%rename from scrapegraphai/nodes/text_to_speach_node.pyrename to scrapegraphai/nodes/text_to_speech_node.pyindex 1018535f..39209278 100644--- a/scrapegraphai/nodes/text_to_speach_node.py+++ b/scrapegraphai/nodes/text_to_speech_node.py@@ -7,7 +7,7 @@ from openai import OpenAIfrom .base_node import BaseNode-class TextToSpeachNode(BaseNode):+class TextToSpeechNode(BaseNode):"""A node responsible for parsing text content from a document using specified tags and readinfit with the selected voiceq.diff --git a/scrapegraphai/utils/__init__.py b/scrapegraphai/utils/__init__.pynew file mode 100644index 00000000..55afed18--- /dev/null+++ b/scrapegraphai/utils/__init__.py@@ -0,0 +1,4 @@+"""+ __init__.py file for utils folder+"""+from .nodes_metadata import nodes_metadata\ No newline at end of filediff --git a/scrapegraphai/utils/nodes_metadata.py b/scrapegraphai/utils/nodes_metadata.pynew file mode 100644index 00000000..b5b7b1b2--- /dev/null+++ b/scrapegraphai/utils/nodes_metadata.py@@ -0,0 +1,46 @@+"""+Nodes metadata for the scrapegraphai package.+"""++nodes_metadata = {+ "FetchHTMLNode": {+ "description": "Fetches HTML content from a given URL.",+ "args": {+ "url": "The URL from which to fetch HTML content."+ },+ "returns": "Updated state with fetched HTML content under 'document' key."+ },+ "GetProbableTagsNode": {+ "description": "Identifies probable HTML tags from a document based on a user's question.",+ "args": {+ "user_input": "User's query or question.",+ "document": "HTML content as a string."+ },+ "returns": "Updated state with probable HTML tags under 'tags' key."+ },+ "ParseHTMLNode": {+ "description": "Parses HTML content to extract specific data.",+ "args": {+ "document": "HTML content as a string.",+ "tags": "List of HTML tags to focus on during parsing."+ },+ "returns": "Updated state with extracted data under 'parsed_document' key."+ },+ "GenerateAnswerNode": {+ "description": "Generates an answer based on the user's input and parsed document.",+ "args": {+ "user_input": "User's query or question.",+ "parsed_document": "Data extracted from the HTML document."+ },+ "returns": "Updated state with the answer under 'answer' key."+ },+ "ConditionalNode": {+ "description": "Decides the next node to execute based on a condition.",+ "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."+ }+ # Add other nodes as necessary...+}\ No newline at end of file