From f5cbd80c977f51233ac1978d8450fcf0ec2ff461 Mon Sep 17 00:00:00 2001 From: Marco Vinciguerra Date: Sat, 1 Jun 2024 09:52:21 +0200 Subject: [PATCH] feat: add pdf scraper multi graph --- .../local_models/pdf_scraper_multi_ollama.py | 69 +++++++++++ scrapegraphai/graphs/__init__.py | 1 + scrapegraphai/graphs/pdf_scraper_multi.py | 117 ++++++++++++++++++ .../nodes/generate_answer_csv_node.py | 2 +- .../nodes/generate_answer_pdf_node.py | 2 +- scrapegraphai/nodes/generate_scraper_node.py | 1 - scrapegraphai/nodes/get_probable_tags_node.py | 2 - scrapegraphai/nodes/robots_node.py | 2 +- 8 files changed, 190 insertions(+), 6 deletions(-) create mode 100644 examples/local_models/pdf_scraper_multi_ollama.py create mode 100644 scrapegraphai/graphs/pdf_scraper_multi.py diff --git a/examples/local_models/pdf_scraper_multi_ollama.py b/examples/local_models/pdf_scraper_multi_ollama.py new file mode 100644 index 00000000..c7b439bd --- /dev/null +++ b/examples/local_models/pdf_scraper_multi_ollama.py @@ -0,0 +1,69 @@ +""" +Module for showing how PDFScraper multi works +""" +from scrapegraphai.graphs import PdfScraperMultiGraph + +graph_config = { + "llm": { + "model": "ollama/llama3", + "temperature": 0, + "format": "json", # Ollama needs the format to be specified explicitly + "model_tokens": 4000, + }, + "embeddings": { + "model": "ollama/nomic-embed-text", + "temperature": 0, + }, + "verbose": True, + "headless": False, +} + +# Covert to list +sources = [ + "This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.", + "This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.", + "This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.", + "This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather—the interaction between call center architecture and outdoor weather conditions—in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity – largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking.", +] + +prompt = """ +You are an expert in reviewing academic manuscripts. Please analyze the abstracts provided from an academic journal article to extract and clearly identify the following elements: + +Independent Variable (IV): The variable that is manipulated or considered as the primary cause affecting other variables. +Dependent Variable (DV): The variable that is measured or observed, which is expected to change as a result of variations in the Independent Variable. +Exogenous Shock: Identify any external or unexpected events used in the study that serve as a natural experiment or provide a unique setting for observing the effects on the IV and DV. +Response Format: For each abstract, present your response in the following structured format: + +Independent Variable (IV): +Dependent Variable (DV): +Exogenous Shock: + +Example Queries and Responses: + +Query: This paper provides evidence from a natural experiment on the relationship between positive affect and productivity. We link highly detailed administrative data on the behaviors and performance of all telesales workers at a large telecommunications company with survey reports of employee happiness that we collected on a weekly basis. We use variation in worker mood arising from visual exposure to weather the interaction between call center architecture and outdoor weather conditions in order to provide a quasi-experimental test of the effect of happiness on productivity. We find evidence of a positive impact on sales performance, which is driven by changes in labor productivity largely through workers converting more calls into sales, and to a lesser extent by making more calls per hour and adhering more closely to their schedule. We find no evidence in our setting of effects on measures of high-frequency labor supply such as attendance and break-taking. + +Response: + +Independent Variable (IV): Employee happiness. +Dependent Variable (DV): Overall firm productivity. +Exogenous Shock: Sudden company-wide increase in bonus payments. + +Query: The diffusion of social media coincided with a worsening of mental health conditions among adolescents and young adults in the United States, giving rise to speculation that social media might be detrimental to mental health. In this paper, we provide quasi-experimental estimates of the impact of social media on mental health by leveraging a unique natural experiment: the staggered introduction of Facebook across U.S. colleges. Our analysis couples data on student mental health around the years of Facebook's expansion with a generalized difference-in-differences empirical strategy. We find that the roll-out of Facebook at a college increased symptoms of poor mental health, especially depression. We also find that, among students predicted to be most susceptible to mental illness, the introduction of Facebook led to increased utilization of mental healthcare services. Lastly, we find that, after the introduction of Facebook, students were more likely to report experiencing impairments to academic performance resulting from poor mental health. Additional evidence on mechanisms suggests that the results are due to Facebook fostering unfavorable social comparisons. + +Response: + +Independent Variable (IV): Exposure to social media. +Dependent Variable (DV): Mental health outcomes. +Exogenous Shock: staggered introduction of Facebook across U.S. colleges. +""" +results = [] +for source in sources: + pdf_scraper_graph = PdfScraperMultiGraph( + prompt=prompt, + source=source, + config=graph_config + ) + result = pdf_scraper_graph.run() + results.append(result) + +print(results) diff --git a/scrapegraphai/graphs/__init__.py b/scrapegraphai/graphs/__init__.py index 994b2e3a..b572905e 100644 --- a/scrapegraphai/graphs/__init__.py +++ b/scrapegraphai/graphs/__init__.py @@ -16,3 +16,4 @@ from .pdf_scraper_graph import PDFScraperGraph from .omni_scraper_graph import OmniScraperGraph from .omni_search_graph import OmniSearchGraph from .smart_scraper_multi_graph import SmartScraperMultiGraph +from .pdf_scraper_multi import PdfScraperMultiGraph diff --git a/scrapegraphai/graphs/pdf_scraper_multi.py b/scrapegraphai/graphs/pdf_scraper_multi.py new file mode 100644 index 00000000..125d70a0 --- /dev/null +++ b/scrapegraphai/graphs/pdf_scraper_multi.py @@ -0,0 +1,117 @@ +""" +PdfScraperMultiGraph Module +""" + +from copy import copy, deepcopy +from typing import List, Optional + +from .base_graph import BaseGraph +from .abstract_graph import AbstractGraph +from .pdf_scraper_graph import PDFScraperGraph + +from ..nodes import ( + GraphIteratorNode, + MergeAnswersNode +) + + +class PdfScraperMultiGraph(AbstractGraph): + """ + PdfScraperMultiGraph is a scraping pipeline that scrapes a + list of URLs and generates answers to a given prompt. + It only requires a user prompt and a list of URLs. + + Attributes: + prompt (str): The user prompt to search the internet. + llm_model (dict): The configuration for the language model. + embedder_model (dict): The configuration for the embedder model. + headless (bool): A flag to run the browser in headless mode. + verbose (bool): A flag to display the execution information. + model_token (int): The token limit for the language model. + + Args: + prompt (str): The user prompt to search the internet. + source (List[str]): The source of the graph. + config (dict): Configuration parameters for the graph. + schema (Optional[str]): The schema for the graph output. + + Example: + >>> search_graph = MultipleSearchGraph( + ... "What is Chioggia famous for?", + ... {"llm": {"model": "gpt-3.5-turbo"}} + ... ) + >>> result = search_graph.run() + """ + + def __init__(self, prompt: str, source: List[str], config: dict, schema: Optional[str] = None): + + self.max_results = config.get("max_results", 3) + + if all(isinstance(value, str) for value in config.values()): + self.copy_config = copy(config) + else: + self.copy_config = deepcopy(config) + + super().__init__(prompt, config, source, schema) + + def _create_graph(self) -> BaseGraph: + """ + Creates the graph of nodes representing the workflow for web scraping and searching. + + Returns: + BaseGraph: A graph instance representing the web scraping and searching workflow. + """ + + # ************************************************ + # Create a PDFScraperGraph instance + # ************************************************ + + pdf_scraper_instance = PDFScraperGraph( + prompt="", + source="", + config=self.copy_config, + ) + + # ************************************************ + # Define the graph nodes + # ************************************************ + + graph_iterator_node = GraphIteratorNode( + input="user_prompt & pdfs", + output=["results"], + node_config={ + "graph_instance": pdf_scraper_instance, + } + ) + + merge_answers_node = MergeAnswersNode( + input="user_prompt & results", + output=["answer"], + node_config={ + "llm_model": self.llm_model, + "schema": self.schema + } + ) + + return BaseGraph( + nodes=[ + graph_iterator_node, + merge_answers_node, + ], + edges=[ + (graph_iterator_node, merge_answers_node), + ], + entry_point=graph_iterator_node + ) + + def run(self) -> str: + """ + Executes the web scraping and searching process. + + Returns: + str: The answer to the prompt. + """ + inputs = {"user_prompt": self.prompt, "pdfs": self.source} + self.final_state, self.execution_info = self.graph.execute(inputs) + + return self.final_state.get("answer", "No answer found.") diff --git a/scrapegraphai/nodes/generate_answer_csv_node.py b/scrapegraphai/nodes/generate_answer_csv_node.py index e12c64f9..a7f8f13b 100644 --- a/scrapegraphai/nodes/generate_answer_csv_node.py +++ b/scrapegraphai/nodes/generate_answer_csv_node.py @@ -49,7 +49,7 @@ class GenerateAnswerCSVNode(BaseNode): input: str, output: List[str], node_config: Optional[dict] = None, - node_name: str = "GenerateAnswer", + node_name: str = "GenerateAnswerCSV", ): """ Initializes the GenerateAnswerNodeCsv with a language model client and a node name. diff --git a/scrapegraphai/nodes/generate_answer_pdf_node.py b/scrapegraphai/nodes/generate_answer_pdf_node.py index 1f468a55..475fd4f7 100644 --- a/scrapegraphai/nodes/generate_answer_pdf_node.py +++ b/scrapegraphai/nodes/generate_answer_pdf_node.py @@ -48,7 +48,7 @@ class GenerateAnswerPDFNode(BaseNode): input: str, output: List[str], node_config: Optional[dict] = None, - node_name: str = "GenerateAnswer", + node_name: str = "GenerateAnswerPDF", ): """ Initializes the GenerateAnswerNodePDF with a language model client and a node name. diff --git a/scrapegraphai/nodes/generate_scraper_node.py b/scrapegraphai/nodes/generate_scraper_node.py index 8c272533..a4d74792 100644 --- a/scrapegraphai/nodes/generate_scraper_node.py +++ b/scrapegraphai/nodes/generate_scraper_node.py @@ -10,7 +10,6 @@ from langchain.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnableParallel from tqdm import tqdm - from ..utils.logging import get_logger # Imports from the library diff --git a/scrapegraphai/nodes/get_probable_tags_node.py b/scrapegraphai/nodes/get_probable_tags_node.py index a26ded38..f31633c0 100644 --- a/scrapegraphai/nodes/get_probable_tags_node.py +++ b/scrapegraphai/nodes/get_probable_tags_node.py @@ -3,10 +3,8 @@ GetProbableTagsNode Module """ from typing import List, Optional - from langchain.output_parsers import CommaSeparatedListOutputParser from langchain.prompts import PromptTemplate - from ..utils.logging import get_logger from .base_node import BaseNode diff --git a/scrapegraphai/nodes/robots_node.py b/scrapegraphai/nodes/robots_node.py index 2ed7755f..d77c7a08 100644 --- a/scrapegraphai/nodes/robots_node.py +++ b/scrapegraphai/nodes/robots_node.py @@ -47,7 +47,7 @@ class RobotsNode(BaseNode): input: str, output: List[str], node_config: Optional[dict] = None, - node_name: str = "Robots", + node_name: str = "RobotNode", ): super().__init__(node_name, "node", input, output, 1)