Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
add superclasse for graphs
VinciGit005e38c2e29817
diff --git a/examples/graph_examples/result.csv b/examples/graph_examples/result.csvindex 97ef817e..aa01441c 100644--- a/examples/graph_examples/result.csv+++ b/examples/graph_examples/result.csv@@ -1,2 +1,2 @@-0,1,2,3-"{'title': 'Rotary Pendulum RL', 'description': 'Open Source project aimed at controlling a real life rotary pendulum using RL algorithms'}","{'title': 'DQN Implementation from scratch', 'description': 'Developed a Deep Q-Network algorithm to train a simple and double pendulum'}","{'title': 'Multi Agents HAED', 'description': 'University project which focuses on simulating a multi-agent system to perform environment mapping. Agents, equipped with sensors, explore and record their surroundings, considering uncertainties in their readings.'}","{'title': 'Wireless ESC for Modular Drones', 'description': 'Modular drone architecture proposal and proof of concept. The project received maximum grade.'}"+news+"[{'title': ""Jeffrey Epstein's Island Visitors Exposed by Data Broker"", 'description': 'A WIRED investigation uncovered coordinates collected by a controversial data broker that reveal sensitive information about visitors to an island once owned by Epstein, the notorious sex offender.'}, {'title': 'Bug Zappers Are Swarming on Amazon', 'description': 'An article discussing the increase in bug zappers being sold on Amazon.'}, {'title': 'FTX Founder Sam Bankman-Fried Sentenced to 25 Years in Prison', 'description': 'FTX founder Sam Bankman-Fried has been sentenced to 25 years in prison.'}, {'title': 'AWOL’s Latest Projector (and Its Price) Are Borderline Blinding', 'description': ""An article about AWOL's latest projector and its price.""}, {'title': 'The Best Umbrellas to Help You Ride Out the Rain', 'description': 'A list of the best umbrellas to use during rainy weather.'}, {'title': 'A First Look at Samsung’s 2024 TV Lineup', 'description': ""An overview of Samsung's 2024 TV lineup.""}, {'title': 'RFK Jr. Has Assembled His Anti-Vax Conspiracy Squad', 'description': 'RFK Jr. has assembled a group to spread anti-vaccination conspiracy theories.'}, {'title': 'Is a Nintendo Switch Worth Buying Right Now?', 'description': ""An article discussing whether it's worth buying a Nintendo Switch at the moment.""}, {'title': 'The White House Puts New Guardrails on Government Use of AI', 'description': ""The White House has implemented new regulations on the government's use of AI.""}, {'title': 'The Baltimore Bridge Collapse Is About to Get Even Messier', 'description': 'An update on the situation surrounding the Baltimore Bridge collapse.'}, {'title': 'Inside the Creation of the World’s Most Powerful Open Source AI Model', 'description': 'An article detailing the creation of a powerful open-source AI model.'}, {'title': 'The 30 Best Shows on Max (aka HBO Max) Right Now', 'description': 'A list of the 30 best shows currently available on HBO Max.'}, {'title': 'Is AI the Future of NPCs?', 'description': 'An exploration of whether AI is the future of NPCs in gaming.'}, {'title': 'The 25 Best Movies on Max (aka HBO Max) Right Now', 'description': 'A list of the 25 best movies currently available on HBO Max.'}, {'title': 'What the Apple Antitrust Suit Means for the Future of Messaging', 'description': 'An analysis of the implications of the Apple antitrust suit on messaging platforms.'}, {'title': 'The 19 Best PS5 Games, From Sci-Fi Horror to Kitty-Cat Adventures', 'description': 'A list of the 19 best games available on the PS5.'}, {'title': 'Our Favorite Garmin Smartwatches Are on Sale', 'description': 'An article highlighting Garmin smartwatches that are currently on sale.'}, {'title': 'Online Conspiracies About the Baltimore Bridge Collapse Are Out of Control', 'description': 'A discussion on the online conspiracies surrounding the Baltimore Bridge collapse.'}, {'title': 'Antiabortion Disinformation Ads Ran Rampant on Facebook', 'description': 'An article addressing the prevalence of antiabortion disinformation ads on Facebook.'}, {'title': 'The Real Reason Some Abortion Pill Patients Go to the ER', 'description': 'An exploration of the reasons why some abortion pill patients end up in the ER.'}, {'title': 'The Earth Will Feast on Dead Cicadas', 'description': 'An article discussing the ecological impact of dead cicadas.'}, {'title': 'Meet the Designer Behind Neuralink’s Surgical Robot', 'description': ""An introduction to the designer behind Neuralink's surgical robot.""}, {'title': 'The Next Generation of Cancer Drugs Will Be Made in Space', 'description': 'An article detailing the future of cancer drug production in space.'}, {'title': '‘Malicious Activity’ Hits the University of Cambridge’s Medical School', 'description': ""An update on the 'malicious activity' affecting the University of Cambridge's Medical School.""}, {'title': 'Judges Block US Extradition of WikiLeaks Founder Julian Assange--for Now', 'description': 'An update on the US extradition case of WikiLeaks founder Julian Assange.'}, {'title': 'Chinese Hackers Charged in Decade-Long Global Spying Rampage', 'description': 'An article discussing the charges against Chinese hackers for global spying.'}]"diff --git a/examples/graph_examples/result.json b/examples/graph_examples/result.jsonindex 8a4e7057..72072475 100644--- a/examples/graph_examples/result.json+++ b/examples/graph_examples/result.json@@ -1 +1 @@-{"projects": [{"title": "Rotary Pendulum RL", "description": "Open Source project aimed at controlling a real life rotary pendulum using RL algorithms"}, {"title": "DQN Implementation from scratch", "description": "Developed a Deep Q-Network algorithm to train a simple and double pendulum"}, {"title": "Multi Agents HAED", "description": "University project which focuses on simulating a multi-agent system to perform environment mapping. Agents, equipped with sensors, explore and record their surroundings, considering uncertainties in their readings."}, {"title": "Wireless ESC for Modular Drones", "description": "Modular drone architecture proposal and proof of concept. The project received maximum grade."}]}\ No newline at end of file+{"merged_content": {"news": [{"title": "Jeffrey Epstein's Island Visitors Exposed by Data Broker", "description": "A WIRED investigation uncovered coordinates collected by a controversial data broker that reveal sensitive information about visitors to an island once owned by Epstein, the notorious sex offender."}, {"title": "Bug Zappers Are Swarming on Amazon", "description": "An article discussing the increase in bug zappers being sold on Amazon."}, {"title": "FTX Founder Sam Bankman-Fried Sentenced to 25 Years in Prison", "description": "FTX founder Sam Bankman-Fried has been sentenced to 25 years in prison."}, {"title": "AWOL\u2019s Latest Projector (and Its Price) Are Borderline Blinding", "description": "An article about AWOL's latest projector and its price."}, {"title": "The Best Umbrellas to Help You Ride Out the Rain", "description": "A list of the best umbrellas to use during rainy weather."}, {"title": "A First Look at Samsung\u2019s 2024 TV Lineup", "description": "An overview of Samsung's 2024 TV lineup."}, {"title": "RFK Jr. Has Assembled His Anti-Vax Conspiracy Squad", "description": "RFK Jr. has assembled a group to spread anti-vaccination conspiracy theories."}, {"title": "Is a Nintendo Switch Worth Buying Right Now?", "description": "An article discussing whether it's worth buying a Nintendo Switch at the moment."}, {"title": "The White House Puts New Guardrails on Government Use of AI", "description": "The White House has implemented new regulations on the government's use of AI."}, {"title": "The Baltimore Bridge Collapse Is About to Get Even Messier", "description": "An update on the situation surrounding the Baltimore Bridge collapse."}, {"title": "Inside the Creation of the World\u2019s Most Powerful Open Source AI Model", "description": "An article detailing the creation of a powerful open-source AI model."}, {"title": "The 30 Best Shows on Max (aka HBO Max) Right Now", "description": "A list of the 30 best shows currently available on HBO Max."}, {"title": "Is AI the Future of NPCs?", "description": "An exploration of whether AI is the future of NPCs in gaming."}, {"title": "The 25 Best Movies on Max (aka HBO Max) Right Now", "description": "A list of the 25 best movies currently available on HBO Max."}, {"title": "What the Apple Antitrust Suit Means for the Future of Messaging", "description": "An analysis of the implications of the Apple antitrust suit on messaging platforms."}, {"title": "The 19 Best PS5 Games, From Sci-Fi Horror to Kitty-Cat Adventures", "description": "A list of the 19 best games available on the PS5."}, {"title": "Our Favorite Garmin Smartwatches Are on Sale", "description": "An article highlighting Garmin smartwatches that are currently on sale."}, {"title": "Online Conspiracies About the Baltimore Bridge Collapse Are Out of Control", "description": "A discussion on the online conspiracies surrounding the Baltimore Bridge collapse."}, {"title": "Antiabortion Disinformation Ads Ran Rampant on Facebook", "description": "An article addressing the prevalence of antiabortion disinformation ads on Facebook."}, {"title": "The Real Reason Some Abortion Pill Patients Go to the ER", "description": "An exploration of the reasons why some abortion pill patients end up in the ER."}, {"title": "The Earth Will Feast on Dead Cicadas", "description": "An article discussing the ecological impact of dead cicadas."}, {"title": "Meet the Designer Behind Neuralink\u2019s Surgical Robot", "description": "An introduction to the designer behind Neuralink's surgical robot."}, {"title": "The Next Generation of Cancer Drugs Will Be Made in Space", "description": "An article detailing the future of cancer drug production in space."}, {"title": "\u2018Malicious Activity\u2019 Hits the University of Cambridge\u2019s Medical School", "description": "An update on the 'malicious activity' affecting the University of Cambridge's Medical School."}, {"title": "Judges Block US Extradition of WikiLeaks Founder Julian Assange--for Now", "description": "An update on the US extradition case of WikiLeaks founder Julian Assange."}, {"title": "Chinese Hackers Charged in Decade-Long Global Spying Rampage", "description": "An article discussing the charges against Chinese hackers for global spying."}]}}\ No newline at end of filediff --git a/scrapegraphai/graphs/__init__.py b/scrapegraphai/graphs/__init__.pyindex 67792b28..a7d2897b 100644--- a/scrapegraphai/graphs/__init__.py+++ b/scrapegraphai/graphs/__init__.py@@ -4,3 +4,4 @@ __init__.py file for graphs folderfrom .base_graph import BaseGraphfrom .smart_scraper_graph import SmartScraperGraphfrom .speech_graph import SpeechGraph+from .search_graph import SearchGraphdiff --git a/scrapegraphai/graphs/abstract_graph.py b/scrapegraphai/graphs/abstract_graph.pynew file mode 100644index 00000000..d5cc9987--- /dev/null+++ b/scrapegraphai/graphs/abstract_graph.py@@ -0,0 +1,43 @@+"""+Module having abstract class for creating all the graphs+"""+from abc import ABC, abstractmethod+++class AbstractGraph(ABC):+ """+ Abstract class representing a generic graph-based tool.+ """++ def __init__(self, prompt: str, file_source: str, config: dict):+ """+ Initializes the AbstractGraph with a prompt, file source, and configuration.+ """+ self.prompt = prompt+ self.file_source = file_source+ self.input_key = "url" if file_source.startswith(+ "http") else "local_dir"+ self.config = config+ self.llm_model = self._create_llm(config["llm"])+ self.graph = self._create_graph()++ @abstractmethod+ def _create_llm(self, llm_config: dict):+ """+ Abstract method to create a language model instance.+ """+ pass++ @abstractmethod+ def _create_graph(self):+ """+ Abstract method to create a graph representation.+ """+ pass++ @abstractmethod+ def run(self) -> str:+ """+ Abstract method to execute the graph and return the result.+ """+ passdiff --git a/scrapegraphai/graphs/search_graph.py b/scrapegraphai/graphs/search_graph.pyindex d346678b..2c568221 100644--- a/scrapegraphai/graphs/search_graph.py+++ b/scrapegraphai/graphs/search_graph.py@@ -1,5 +1,5 @@-"""-Module for creating the search graph+"""+Module for making the search on the intenet"""from ..models import OpenAI, Geminifrom .base_graph import BaseGraph@@ -7,48 +7,28 @@ from ..nodes import (FetchNode,ParseNode,RAGNode,- GenerateAnswerNode+ GenerateAnswerNode,+ SearchInternetNode)-from ..nodes.search_internet_node import SearchInternetNode+from .abstract_graph import AbstractGraph-class SearchGraph:+class SearchGraph(AbstractGraph):"""Module for searching info on the internet"""- def __init__(self, prompt: str, file_source: str, config: dict):- """- Initializes SmartScraper with a prompt, URL, and language model configuration.- """- self.prompt = prompt- self.file_source = file_source- self.input_key = "url" if file_source.startswith(- "http") else "local_dir"- self.config = config- self.llm_model = self._create_llm(config["llm"])- self.graph = self._create_graph()-def _create_llm(self, llm_config: dict):"""- 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.+ Creates an instance of the language model (OpenAI or Gemini) based on configuration."""llm_defaults = {"temperature": 0,"streaming": True}- # Update defaults with any LLM parameters that were providedllm_params = {**llm_defaults, **llm_config}- # Ensure the api_key is set, raise an error if it's notif "api_key" not in llm_params:raise ValueError("LLM configuration must include an 'api_key'.")- # select the model based on the model nameif "gpt-" in llm_params["model"]:return OpenAI(llm_params)elif "gemini" in llm_params["model"]:@@ -58,12 +38,8 @@ class SearchGraph:def _create_graph(self):"""- Creates the graph of nodes representing the workflow for web scraping.-- Returns:- BaseGraph: An instance of the BaseGraph class.+ Creates the graph of nodes representing the workflow for web scraping and searching."""- # define the nodes for the graphsearch_internet_node = SearchInternetNode(input="url | local_dir",output=["doc"],@@ -104,3 +80,12 @@ class SearchGraph:},entry_point=search_internet_node)++ def run(self) -> str:+ """+ Executes the web scraping and searching process.+ """+ inputs = {"user_prompt": self.prompt, self.input_key: self.file_source}+ final_state = self.graph.execute(inputs)++ return final_state.get("answer", "No answer found.")diff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.pyindex 0bfda6fc..9175f549 100644--- a/scrapegraphai/graphs/smart_scraper_graph.py+++ b/scrapegraphai/graphs/smart_scraper_graph.py@@ -9,64 +9,26 @@ from ..nodes import (RAGNode,GenerateAnswerNode)+from .abstract_graph import AbstractGraph-class SmartScraperGraph:+class SmartScraperGraph(AbstractGraph):"""SmartScraper is a comprehensive web scraping tool that automates the process of extractinginformation from web pages using a natural language model to interpret and answer prompts.-- 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 (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'."""- def __init__(self, prompt: str, file_source: str, config: dict):- """- Initializes the SmartScraper with a prompt, URL, and language model configuration.- """- self.prompt = prompt- self.file_source = file_source- self.input_key = "url" if file_source.startswith(- "http") else "local_dir"- self.config = config- self.llm_model = self._create_llm(config["llm"])- self.graph = self._create_graph()-def _create_llm(self, llm_config: dict):"""- 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.+ Creates an instance of the language model (OpenAI or Gemini) based on configuration."""llm_defaults = {"temperature": 0,"streaming": True}- # Update defaults with any LLM parameters that were providedllm_params = {**llm_defaults, **llm_config}- # Ensure the api_key is set, raise an error if it's notif "api_key" not in llm_params:raise ValueError("LLM configuration must include an 'api_key'.")- # select the model based on the model nameif "gpt-" in llm_params["model"]:return OpenAI(llm_params)elif "gemini" in llm_params["model"]:@@ -77,11 +39,7 @@ class SmartScraperGraph:def _create_graph(self):"""Creates the graph of nodes representing the workflow for web scraping.-- Returns:- BaseGraph: An instance of the BaseGraph class."""- # define the nodes for the graphfetch_node = FetchNode(input="url | local_dir",output=["doc"],@@ -118,12 +76,8 @@ class SmartScraperGraph:def run(self) -> str:"""- Executes the scraping process by running the graph and returns the extracted information.-- Returns:- str: The answer extracted from the web page, corresponding to the given prompt.+ Executes the web scraping process and returns the answer to the prompt."""-inputs = {"user_prompt": self.prompt, self.input_key: self.file_source}final_state = self.graph.execute(inputs)diff --git a/scrapegraphai/graphs/speech_graph.py b/scrapegraphai/graphs/speech_graph.pyindex 1e70e01d..da019698 100644--- a/scrapegraphai/graphs/speech_graph.py+++ b/scrapegraphai/graphs/speech_graph.py@@ -1,5 +1,5 @@"""-Module for extracting the summary from the speach+Module for converting text to speach"""from scrapegraphai.utils.save_audio_from_bytes import save_audio_from_bytesfrom ..models import OpenAI, Gemini, OpenAITextToSpeech@@ -11,62 +11,26 @@ from ..nodes import (GenerateAnswerNode,TextToSpeechNode,)+from .abstract_graph import AbstractGraph-class SpeechGraph:+class SpeechGraph(AbstractGraph):"""SpeechSummaryGraph is a tool that automates the process of extracting and summarizinginformation from web pages, then converting that summary into spoken word via an MP3 file.-- Attributes:- url (str): The URL of the web page to scrape and summarize.- llm_config (dict): Configuration parameters for the language model,- with 'api_key' mandatory.- summary_prompt (str): The prompt used to guide the summarization process.- output_path (Path): The path where the generated MP3 file will be saved.-- Methods:- run(): Executes the web scraping, summarization, and text-to-speech process.-- Args:- url (str): The URL of the web page to scrape and summarize.- llm_config (dict): A dictionary containing configuration options for the language model.- summary_prompt (str): The prompt used to guide the summarization process.- output_path (str): The file path where the generated MP3 should be saved."""- def __init__(self, prompt: str, file_source: str, config: dict):- """- Initializes the SmartScraper with a prompt, URL, and language model configuration.- """- self.prompt = prompt- self.file_source = file_source- self.input_key = "url" if "http" in file_source else "local_dir"- self.llm_model = self._create_llm(config["llm"])- self.output_path = config.get("output_path", "output.mp3")- self.text_to_speech_model = OpenAITextToSpeech(config["tts_model"])- self.graph = self._create_graph()-def _create_llm(self, llm_config: dict):"""- 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.+ Creates an instance of the language model (OpenAI or Gemini) based on configuration."""llm_defaults = {"temperature": 0,"streaming": True}- # Update defaults with any LLM parameters that were providedllm_params = {**llm_defaults, **llm_config}- # Ensure the api_key is set, raise an error if it's notif "api_key" not in llm_params:raise ValueError("LLM configuration must include an 'api_key'.")- # select the model based on the model nameif "gpt-" in llm_params["model"]:return OpenAI(llm_params)elif "gemini" in llm_params["model"]:@@ -76,12 +40,8 @@ class SpeechGraph:def _create_graph(self):"""- Creates the graph of nodes representing the workflow for web scraping.-- Returns:- BaseGraph: An instance of the BaseGraph class.+ Creates the graph of nodes representing the workflow for web scraping and summarization."""- # define the nodes for the graphfetch_node = FetchNode(input="url | local_dir",output=["doc"],@@ -103,7 +63,8 @@ class SpeechGraph:text_to_speech_node = TextToSpeechNode(input="answer",output=["audio"],- model_config={"tts_model": self.text_to_speech_model},+ model_config={"tts_model": OpenAITextToSpeech(+ self.config["tts_model"])},)return BaseGraph(@@ -125,10 +86,7 @@ class SpeechGraph:def run(self) -> str:"""- Executes the scraping process by running the graph and returns the extracted information.-- Returns:- str: The answer extracted from the web page, corresponding to the given prompt.+ Executes the web scraping, summarization, and text-to-speech process."""inputs = {"user_prompt": self.prompt, self.input_key: self.file_source}final_state = self.graph.execute(inputs)@@ -136,7 +94,8 @@ class SpeechGraph:audio = final_state.get("audio", None)if not audio:raise ValueError("No audio generated from the text.")- save_audio_from_bytes(audio, self.output_path)- print(f"Audio saved to {self.output_path}")+ save_audio_from_bytes(audio, self.config.get(+ "output_path", "output.mp3"))+ print(f"Audio saved to {self.config.get('output_path', 'output.mp3')}")return final_statediff --git a/scrapegraphai/nodes/__init__.py b/scrapegraphai/nodes/__init__.pyindex 71223add..e66aec9d 100644--- a/scrapegraphai/nodes/__init__.py+++ b/scrapegraphai/nodes/__init__.py@@ -10,3 +10,4 @@ from .parse_node import ParseNodefrom .rag_node import RAGNodefrom .text_to_speech_node import TextToSpeechNodefrom .image_to_text_node import ImageToTextNode+from .search_internet_node import SearchInternetNode