Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
add refactoring for pylint standards
VinciGit008e5201ee9af0
diff --git a/examples/graph_example.py b/examples/graph_example.pyindex cf56ed9c..b275a1fb 100644--- a/examples/graph_example.py+++ b/examples/graph_example.py@@ -1,17 +1,22 @@+"""+Basic example for creating the node+"""+import os+from dotenv import load_dotenvfrom yosoai.graphs import SmartScraper-OPENAI_API_KEY = ''+load_dotenv()+openai_key = os.getenv("API_KEY")+if not openai_key:+ print("Error: OpenAI API key not found in environment variables.")llm_config = {- "api_key": OPENAI_API_KEY,+ "api_key": openai_key,"model_name": "gpt-3.5-turbo",}-url = "https://perinim.github.io/projects/"-prompt = "List me all the titles and project descriptions"--smart_scraper = SmartScraper(prompt, url, llm_config)+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/examples/html_scraping.py b/examples/html_scraping.pyindex d9d75c64..834e6347 100644--- a/examples/html_scraping.py+++ b/examples/html_scraping.py@@ -1,3 +1,6 @@+"""+Exmaple of scraper using just the HTML code+"""import osfrom dotenv import load_dotenvfrom yosoai import send_request@@ -41,14 +44,13 @@ query_info = '''</article>'''+def main():- # Get OpenAI API key from environment variablesopenai_key = os.getenv("API_KEY")if not openai_key:print("Error: OpenAI API key not found in environment variables.")return- # Example values for the requestrequest_settings = [{"title": "title",@@ -57,15 +59,14 @@ def main():}]- # Choose the desired model and other parametersselected_model = "gpt-3.5-turbo"temperature_value = 0.7- # Invoke send_request function- result = send_request(openai_key, query_info, request_settings, selected_model, temperature_value, 'cl100k_base')+ result = send_request(openai_key, query_info, request_settings,+ selected_model, temperature_value, 'cl100k_base')- # Print or process the result as neededprint("Result:", result)+if __name__ == "__main__":- main()\ No newline at end of file+ main()diff --git a/examples/value_scraping.py b/examples/value_scraping.pyindex 38128322..9ff00a8e 100644--- a/examples/value_scraping.py+++ b/examples/value_scraping.py@@ -1,11 +1,15 @@+"""+Example of scraping using just a link+ """import osfrom dotenv import load_dotenvfrom yosoai import _get_function, send_requestload_dotenv()+def main():- # Get OpenAI API key from environment variables+ """ """openai_key = os.getenv("API_KEY")if not openai_key:print("Error: OpenAI API key not found in environment variables.")@@ -14,24 +18,22 @@ def main():# Example values for the requestrequest_settings = [{- "title": "title_news",- "type": "str",- "description": "Give me the name of the news"+ "title": "title_news",+ "type": "str",+ "description": "Give me the name of the news"}]- # Choose the desired model and other parametersselected_model = "gpt-3.5-turbo"temperature_value = 0.7- # Mockup World URLmockup_world_url = "https://sport.sky.it/nba?gr=www"- # Invoke send_request function- result = send_request(openai_key, _get_function(mockup_world_url), request_settings, selected_model, temperature_value, 'cl100k_base')+ result = send_request(openai_key, _get_function(+ mockup_world_url), request_settings, selected_model, temperature_value, 'cl100k_base')- # Print or process the result as neededprint("Result:", result)+if __name__ == "__main__":- main()\ No newline at end of file+ main()diff --git a/yosoai/__init__.py b/yosoai/__init__.pyindex fefa677a..794b4c65 100644--- a/yosoai/__init__.py+++ b/yosoai/__init__.py@@ -1,5 +1,5 @@"""-init file+ __init__.py file for yosoai folder"""from .class_creator import create_classfrom .class_generator import Generatordiff --git a/yosoai/class_generator.py b/yosoai/class_generator.pyindex 24ea61a2..99e787a1 100644--- a/yosoai/class_generator.py+++ b/yosoai/class_generator.py@@ -58,3 +58,4 @@ class Generator:return result_dictexcept Exception as e:print(f"Error: {e}")+ return Nonediff --git a/yosoai/getter.py b/yosoai/getter.pyindex 4442a667..18287d82 100644--- a/yosoai/getter.py+++ b/yosoai/getter.py@@ -3,6 +3,7 @@ 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.diff --git a/yosoai/graphs/__init__.py b/yosoai/graphs/__init__.pyindex 3f3eca9c..344e6a12 100644--- a/yosoai/graphs/__init__.py+++ b/yosoai/graphs/__init__.py@@ -1,2 +1,5 @@+"""+__init__.py file for graphs folder+"""from .base_graph import BaseGraph-from .smart_scraper_graph import SmartScraper\ No newline at end of file+from .smart_scraper_graph import SmartScraperdiff --git a/yosoai/graphs/base_graph.py b/yosoai/graphs/base_graph.pyindex 636bce78..d513ddbd 100644--- a/yosoai/graphs/base_graph.py+++ b/yosoai/graphs/base_graph.py@@ -1,3 +1,8 @@+"""+Module for creating the base graphs+ """++class BaseGraph:"""BaseGraph manages the execution flow of a graph composed of interconnected nodes.@@ -19,7 +24,7 @@ class BaseGraph:entry_point (BaseNode): The node instance that represents the entry point of the graph."""- def __init__(self, nodes, edges, entry_point):+ def __init__(self, nodes: dict, edges: dict, entry_point: str):"""Initializes the graph with nodes, edges, and the entry point."""@@ -27,7 +32,7 @@ class BaseGraph:self.edges = self._create_edges(edges)self.entry_point = entry_point.node_name- def _create_edges(self, edges):+ def _create_edges(self, edges: dict) -> dict:"""Helper method to create a dictionary of edges from the given iterable of tuples.@@ -42,7 +47,7 @@ class BaseGraph:edge_dict[from_node.node_name] = to_node.node_namereturn edge_dict- def execute(self, initial_state):+ def execute(self, initial_state: dict) -> dict:"""Executes the graph by traversing nodes starting from the entry point. The executionfollows the edges based on the result of each node's execution and continues until@@ -62,13 +67,10 @@ class BaseGraph:result = current_node.execute(state)if current_node.node_type == "conditional_node":- # For ConditionalNode, result is the next node based on the conditioncurrent_node_name = resultelif current_node_name in self.edges:- # For regular nodes, move to the next node based on the defined edgescurrent_node_name = self.edges[current_node_name]else:- # No further edges, end the executioncurrent_node_name = Nonereturn statediff --git a/yosoai/graphs/smart_scraper_graph.py b/yosoai/graphs/smart_scraper_graph.pyindex ab285a66..d04cd8f1 100644--- a/yosoai/graphs/smart_scraper_graph.py+++ b/yosoai/graphs/smart_scraper_graph.py@@ -1,6 +1,11 @@+"""+Module for creating the smart scaper+"""from langchain_openai import ChatOpenAIfrom .base_graph import BaseGraph-from ..nodes import FetchHTMLNode,ConditionalNode, GetProbableTagsNode, GenerateAnswerNode, ParseHTMLNode+from ..nodes import FetchHTMLNode, ConditionalNode, GetProbableTagsNode+from ..nodes import GenerateAnswerNode, ParseHTMLNode+class SmartScraper:"""@@ -10,21 +15,23 @@ class SmartScraper:Attributes:prompt (str): The user's natural language prompt for the information to be extracted.url (str): The URL of the web page to scrape.- llm_config (dict): Configuration parameters for the language model, with 'api_key' being mandatory.+ llm_config (dict): Configuration parameters for the language model, with+ 'api_key' being mandatory.llm (ChatOpenAI): An instance of the ChatOpenAI class configured with llm_config.graph (BaseGraph): An instance of the BaseGraph class representing the scraping workflow.Methods:run(): Executes the web scraping process and returns the answer to the prompt.-+Args:prompt (str): The user's natural language prompt for the information to be extracted.url (str): The URL of the web page to scrape.llm_config (dict): A dictionary containing configuration options for the language model.- Must include 'api_key', may also specify 'model_name', 'temperature', and 'streaming'.+ Must include 'api_key', may also specify 'model_name',+ 'temperature', and 'streaming'."""- def __init__(self, prompt, url, llm_config):+ def __init__(self, prompt: str, url: str, llm_config: dict):"""Initializes the SmartScraper with a prompt, URL, and language model configuration."""@@ -56,7 +63,7 @@ class SmartScraper:raise ValueError("LLM configuration must include an 'api_key'.")# Create the ChatOpenAI instance with the provided and default parametersreturn ChatOpenAI(**llm_params)-+def _create_graph(self):"""Creates the graph of nodes representing the workflow for web scraping.@@ -65,10 +72,12 @@ class SmartScraper:BaseGraph: An instance of the BaseGraph class."""fetch_html_node = FetchHTMLNode("fetch_html")- get_probable_tags_node = GetProbableTagsNode(self.llm, "get_probable_tags")+ get_probable_tags_node = GetProbableTagsNode(+ self.llm, "get_probable_tags")parse_document_node = ParseHTMLNode("parse_document")generate_answer_node = GenerateAnswerNode(self.llm, "generate_answer")- conditional_node = ConditionalNode("conditional", [parse_document_node, generate_answer_node])+ conditional_node = ConditionalNode(+ "conditional", [parse_document_node, generate_answer_node])return BaseGraph(nodes={@@ -86,7 +95,7 @@ class SmartScraper:entry_point=fetch_html_node)- def run(self):+ def run(self) -> str:"""Executes the scraping process by running the graph and returns the extracted information.diff --git a/yosoai/nodes/__init__.py b/yosoai/nodes/__init__.pyindex 89949364..2bf1efb3 100644--- a/yosoai/nodes/__init__.py+++ b/yosoai/nodes/__init__.py@@ -1,5 +1,8 @@+"""+__init__.py file for node folder+"""from .fetch_html_node import FetchHTMLNodefrom .conditional_node import ConditionalNodefrom .get_probable_tags_node import GetProbableTagsNodefrom .generate_answer_node import GenerateAnswerNode-from .parse_html_node import ParseHTMLNode\ No newline at end of file+from .parse_html_node import ParseHTMLNodediff --git a/yosoai/nodes/base_node.py b/yosoai/nodes/base_node.pyindex 5c62b729..27e1ad9e 100644--- a/yosoai/nodes/base_node.py+++ b/yosoai/nodes/base_node.py@@ -1,5 +1,9 @@+"""+Module for creating the basic node+"""from abc import ABC, abstractmethod+class BaseNode(ABC):"""An abstract base class for nodes in a graph-based workflow. Each node is@@ -33,7 +37,7 @@ class BaseNode(ABC):values ("node" or "conditional_node"), a ValueError israised to indicate the incorrect usage."""-+def __init__(self, node_name: str, node_type: str):"""Initialize the node with a unique identifier and a specified node type.@@ -47,15 +51,16 @@ class BaseNode(ABC):"""self.node_name = node_nameif node_type not in ["node", "conditional_node"]:- raise ValueError(f"node_type must be 'node' or 'conditional_node', got '{node_type}'")+ raise ValueError(+ f"node_type must be 'node' or 'conditional_node', got '{node_type}'")self.node_type = node_type-+@abstractmethod- def execute(self, state):+ def execute(self, state: dict):"""Execute the node's logic and return the updated state.-- :param state: The current state of the graph.+ Args:+ state (dict): The current state of the graph.:return: The updated state after executing this node."""- pass\ No newline at end of file+ passdiff --git a/yosoai/nodes/conditional_node.py b/yosoai/nodes/conditional_node.pyindex 84153a6f..999d87a5 100644--- a/yosoai/nodes/conditional_node.py+++ b/yosoai/nodes/conditional_node.py@@ -1,5 +1,9 @@+"""+Module for implementing the conditional node+"""from .base_node import BaseNode+class ConditionalNode(BaseNode):"""A node that determines the next step in the graph's execution flow based on@@ -28,8 +32,8 @@ class ConditionalNode(BaseNode):ValueError: If next_nodes does not contain exactly two elements, indicatinga misconfiguration in specifying the conditional paths."""-- def __init__(self, key_name, next_nodes, node_name="ConditionalNode"):++ def __init__(self, key_name: str, next_nodes: list, node_name="ConditionalNode"):"""Initializes the node with the key to check and the next node names based on the condition.@@ -41,14 +45,14 @@ class ConditionalNode(BaseNode):Raises:ValueError: If next_nodes does not contain exactly two elements."""-+super().__init__(node_name, "conditional_node")self.key_name = key_nameif len(next_nodes) != 2:raise ValueError("next_nodes must contain exactly two elements.")self.next_nodes = next_nodes- def execute(self, state):+ def execute(self, state: dict) -> str:"""Checks if the specified key is present in the state and decides the next node accordingly.@@ -61,5 +65,4 @@ class ConditionalNode(BaseNode):if self.key_name in state.get("keys", {}) and len(state["keys"][self.key_name]) > 0:return self.next_nodes[0].node_name- else:- return self.next_nodes[1].node_name\ No newline at end of file+ return self.next_nodes[1].node_namediff --git a/yosoai/nodes/fetch_html_node.py b/yosoai/nodes/fetch_html_node.pyindex d42d9d48..eddec3b7 100644--- a/yosoai/nodes/fetch_html_node.py+++ b/yosoai/nodes/fetch_html_node.py@@ -1,6 +1,11 @@+"""+Module for fetching the HTML node+"""+from langchain_community.document_loaders import AsyncHtmlLoaderfrom .base_node import BaseNode+class FetchHTMLNode(BaseNode):"""A node responsible for fetching the HTML content of a specified URL and updating@@ -29,13 +34,13 @@ class FetchHTMLNode(BaseNode):to succeed."""- def __init__(self, node_name, node_type="node"):+ def __init__(self, node_name: str, node_type: str = "node"):"""Initializes the FetchHTMLNode with a node name and node type."""super().__init__(node_name, node_type)- def execute(self, state):+ def execute(self, state: dict) -> dict:"""Executes the node's logic to fetch HTML content from a specified URL andupdate the state with this content.diff --git a/yosoai/nodes/generate_answer_node.py b/yosoai/nodes/generate_answer_node.pyindex 8b1de9b1..6e4dbc1c 100644--- a/yosoai/nodes/generate_answer_node.py+++ b/yosoai/nodes/generate_answer_node.py@@ -1,6 +1,10 @@-from .base_node import BaseNode-from langchain.prompts import PromptTemplate+"""+Module for generating the answer node+"""from langchain_core.output_parsers import JsonOutputParser+from langchain.prompts import PromptTemplate+from .base_node import BaseNode+class GenerateAnswerNode(BaseNode):"""@@ -11,26 +15,30 @@ class GenerateAnswerNode(BaseNode):Attributes:llm (ChatOpenAI): An instance of a language model client, configured for generating answers.- node_name (str): The unique identifier name for the node, defaulting to "GenerateAnswerNode".- node_type (str): The type of the node, set to "node" indicating a standard operational node.+ node_name (str): The unique identifier name for the node, defaulting+ to "GenerateAnswerNode".+ node_type (str): The type of the node, set to "node" indicating a+ standard operational node.Args:- llm: An instance of the language model client (e.g., ChatOpenAI) used for generating answers.- node_name (str, optional): The unique identifier name for the node. Defaults to "GenerateAnswerNode".+ llm: An instance of the language model client (e.g., ChatOpenAI) used+ for generating answers.+ node_name (str, optional): The unique identifier name for the node.+ Defaults to "GenerateAnswerNode".Methods:execute(state): Processes the input and document from the state to generate an answer,updating the state with the generated answer under the 'answer' key."""- def __init__(self, llm, node_name="GenerateAnswerNode"):+ def __init__(self, llm, node_name: str = "GenerateAnswerNode"):"""Initializes the GenerateAnswerNode with a language model client and a node name."""super().__init__(node_name, "node")self.llm = llm- def execute(self, state):+ def execute(self, state: dict) -> dict:"""Generates an answer by constructing a prompt from the user's input and the scrapedcontent, querying the language model, and parsing its response.@@ -48,7 +56,7 @@ class GenerateAnswerNode(BaseNode):KeyError: If 'user_input' or 'document' is not found in the state, indicatingthat the necessary information for generating an answer is missing."""-+print("---GENERATE ANSWER---")try:user_input = state["keys"]["user_input"]@@ -60,7 +68,6 @@ class GenerateAnswerNode(BaseNode):parsed_document = state["keys"].get("parsed_document", None)relevant_chunks = state["keys"].get("relevant_chunks", None)- # Use relevant chunks if available, otherwise use the parsed document or the original documentif relevant_chunks:context = relevant_chunkselif parsed_document:@@ -71,10 +78,10 @@ class GenerateAnswerNode(BaseNode):output_parser = JsonOutputParser()format_instructions = output_parser.get_format_instructions()- template = """You are a website scraper and you have just scraped the following content from a website. You are now asked to answer a question about the content you have scraped.\n {format_instructions} \n The content is as follows:- {context}-- Question: {question}+ template = """You are a website scraper and you have just scraped the+ following content from a website.+ You are now asked to answer a question about the content you have scraped.\n {format_instructions} \n The content is as follows: {context}+ Question: {question}"""schema_prompt = PromptTemplate(@@ -85,9 +92,9 @@ class GenerateAnswerNode(BaseNode):# Chainschema_chain = schema_prompt | self.llm | output_parser- answer = schema_chain.invoke({"context": context, "question": user_input})+ answer = schema_chain.invoke(+ {"context": context, "question": user_input})# Update the state with the generated answerstate["keys"].update({"answer": answer})return state-diff --git a/yosoai/nodes/get_probable_tags_node.py b/yosoai/nodes/get_probable_tags_node.pyindex 5ba81af7..c73c7c3d 100644--- a/yosoai/nodes/get_probable_tags_node.py+++ b/yosoai/nodes/get_probable_tags_node.py@@ -1,6 +1,10 @@-from .base_node import BaseNode-from langchain.prompts import PromptTemplate+"""+Module for proobable tags+"""from langchain.output_parsers import CommaSeparatedListOutputParser+from langchain.prompts import PromptTemplate+from .base_node import BaseNode+class GetProbableTagsNode(BaseNode):"""@@ -11,26 +15,28 @@ class GetProbableTagsNode(BaseNode):Attributes:llm: An instance of a language model client, configured for generating tag predictions.- node_name (str): The unique identifier name for the node, defaulting to "GetProbableTagsNode".+ node_name (str): The unique identifier name for the node,+ defaulting to "GetProbableTagsNode".node_type (str): The type of the node, set to "node" indicating a standard operational node.Args:llm: An instance of the language model client (e.g., ChatOpenAI) used for tag predictions.- node_name (str, optional): The unique identifier name for the node. Defaults to "GetProbableTagsNode".+ node_name (str, optional): The unique identifier name for the node.+ Defaults to "GetProbableTagsNode".Methods:execute(state): Processes the user's input and the URL from the state to generate a list ofprobable HTML tags, updating the state with these tags under the 'tags' key."""- def __init__(self, llm, node_name="GetProbableTagsNode"):+ def __init__(self, llm, node_name: str = "GetProbableTagsNode"):"""Initializes the GetProbableTagsNode with a language model client and a node name."""super().__init__(node_name, "node")self.llm = llm- def execute(self, state):+ def execute(self, state: dict):"""Generates a list of probable HTML tags based on the user's input and updates the statewith this list. The method constructs a prompt for the language model, submits it, and@@ -47,9 +53,8 @@ class GetProbableTagsNode(BaseNode):KeyError: If 'user_input' or 'url' is not found in the state, indicating that thenecessary information for generating tag predictions is missing."""-+print("---GET PROBABLE TAGS---")- # Accessing the nested structuretry:user_input = state["keys"]["user_input"]url = state["keys"]["url"]@@ -60,14 +65,16 @@ class GetProbableTagsNode(BaseNode):output_parser = CommaSeparatedListOutputParser()format_instructions = output_parser.get_format_instructions()- template = """You are a website scraper that knows all the types of html tags. You are now asked to list all the html tags where you think you can find the information of the asked question.\n {format_instructions} \n The webpage is: {webpage} \n The asked question is the following:- {question}+ template = """You are a website scraper that knows all the types of html tags.+ You are now asked to list all the html tags where you think you can find the information of the asked question.\n+ {format_instructions} \n The webpage is: {webpage} \n The asked question is the following: {question}"""tag_prompt = PromptTemplate(template=template,input_variables=["question"],- partial_variables={"format_instructions": format_instructions, "webpage": url},+ partial_variables={+ "format_instructions": format_instructions, "webpage": url},)# Execute the chain to get probable tags@@ -78,4 +85,4 @@ class GetProbableTagsNode(BaseNode):# Update the nested 'keys' dictionary with probable tagsstate["keys"].update({"tags": probable_tags})- return state\ No newline at end of file+ return statediff --git a/yosoai/nodes/parse_html_node.py b/yosoai/nodes/parse_html_node.pyindex 5502c5ab..62690e48 100644--- a/yosoai/nodes/parse_html_node.py+++ b/yosoai/nodes/parse_html_node.py@@ -1,5 +1,9 @@-from .base_node import BaseNode+"""+Module for parsing the HTML node+"""from langchain_community.document_transformers import BeautifulSoupTransformer+from .base_node import BaseNode+class ParseHTMLNode(BaseNode):"""@@ -15,11 +19,12 @@ class ParseHTMLNode(BaseNode):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".+ 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.+ 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"):@@ -36,8 +41,8 @@ class ParseHTMLNode(BaseNode):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.+ 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,@@ -47,7 +52,7 @@ class ParseHTMLNode(BaseNode):KeyError: If 'document' is not found in the state, indicating that the necessaryinformation for parsing is missing."""-+print("---PARSE HTML DOCUMENT---")try:document = state["keys"]["document"]@@ -55,20 +60,15 @@ class ParseHTMLNode(BaseNode):print(f"Error: {e} not found in state.")raise- # Check if tags are specified in the statetags = state["keys"].get("tags", None)- if tags:- # Initialize the BeautifulSoupTransformer with any required configurations- bs_transformer = BeautifulSoupTransformer()- # Parse the document with specified tags- parsed_document = bs_transformer.transform_documents(document, tags_to_extract=tags)- print("Document parsed with specified tags.")- else:- # If no tags are specified, return the document as is+ if not tags:print("No specific tags provided; returning document as is.")return state- # Update the state with the parsed document+ bs_transformer = BeautifulSoupTransformer()+ parsed_document = bs_transformer.transform_documents(+ document, tags_to_extract=tags)+ print("Document parsed with specified tags.")state["keys"].update({"parsed_document": parsed_document})- return state\ No newline at end of file+ return state