Skip to content

Python scraper based on AI

added execution info of the graph, time, price etc

EURAC\marperini74ec928f9695
diff --git a/.gitignore b/.gitignore
index 46f35144..385fc2d6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,6 +28,6 @@ venv/
*.sqlite
*.google-cookie
examples/graph_examples/ScrapeGraphAI_generated_graph
-examples/*.csv
-examples/*.json
+examples/**/*.csv
+examples/**/*.json
main.py
diff --git a/examples/gemini/custom_graph_gemini.py b/examples/gemini/custom_graph_gemini.py
index 4380bd53..d9a62ca4 100644
--- a/examples/gemini/custom_graph_gemini.py
+++ b/examples/gemini/custom_graph_gemini.py
@@ -74,7 +74,7 @@ graph = BaseGraph(
# Execute the graph
# ************************************************
-result = graph.execute({
+result, execution_info = graph.execute({
"user_prompt": "List me the projects with their description",
"url": "https://perinim.github.io/projects/"
})
diff --git a/examples/local_models/scrape_plain_text_local.py b/examples/local_models/scrape_plain_text_local.py
index 13f766bb..1282ed83 100644
--- a/examples/local_models/scrape_plain_text_local.py
+++ b/examples/local_models/scrape_plain_text_local.py
@@ -40,7 +40,7 @@ graph_config = {
# ************************************************
smart_scraper_graph = SmartScraperGraph(
- prompt="List me all the news with their description.",
+ prompt="List me all the projects with their description.",
source=text,
config=graph_config
)
diff --git a/examples/local_models/smart_scraper_local.py b/examples/local_models/smart_scraper_local.py
index 09a18fac..a1fbbee4 100644
--- a/examples/local_models/smart_scraper_local.py
+++ b/examples/local_models/smart_scraper_local.py
@@ -36,7 +36,7 @@ graph_config = {
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the news with their description.",
# also accepts a string with the already downloaded HTML code
- source="https://perinim.github.io/projects",
+ source="https://www.wired.com/category/science/",
config=graph_config
)
diff --git a/examples/mixed_models/search_graph_mixed.py b/examples/mixed_models/search_graph_mixed.py
index fc0ecfa2..76afe1cc 100644
--- a/examples/mixed_models/search_graph_mixed.py
+++ b/examples/mixed_models/search_graph_mixed.py
@@ -5,7 +5,7 @@ Example of Search Graph
import os
from dotenv import load_dotenv
from scrapegraphai.graphs import SearchGraph
-from scrapegraphai.utils import convert_to_csv, convert_to_json
+from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
load_dotenv()
# ************************************************
@@ -38,6 +38,13 @@ search_graph = SearchGraph(
result = search_graph.run()
print(result)
+# ************************************************
+# Get graph execution info
+# ************************************************
+
+graph_exec_info = search_graph.get_execution_info()
+print(prettify_exec_info(graph_exec_info))
+
# Save to json and csv
convert_to_csv(result, "result")
convert_to_json(result, "result")
diff --git a/examples/openai/custom_graph_openai.py b/examples/openai/custom_graph_openai.py
index 98ebcea3..aa1eea7c 100644
--- a/examples/openai/custom_graph_openai.py
+++ b/examples/openai/custom_graph_openai.py
@@ -74,7 +74,7 @@ graph = BaseGraph(
# Execute the graph
# ************************************************
-result = graph.execute({
+result, execution_info = graph.execute({
"user_prompt": "List me the projects with their description",
"url": "https://perinim.github.io/projects/"
})
diff --git a/examples/openai/scrape_plain_text_openai.py b/examples/openai/scrape_plain_text_openai.py
index a259ed6f..e86876d1 100644
--- a/examples/openai/scrape_plain_text_openai.py
+++ b/examples/openai/scrape_plain_text_openai.py
@@ -5,7 +5,7 @@ Basic example of scraping pipeline using SmartScraper from text
import os
from dotenv import load_dotenv
from scrapegraphai.graphs import SmartScraperGraph
-from scrapegraphai.utils import convert_to_csv, convert_to_json
+from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
load_dotenv()
# ************************************************
@@ -46,6 +46,13 @@ smart_scraper_graph = SmartScraperGraph(
result = smart_scraper_graph.run()
print(result)
+# ************************************************
+# Get graph execution info
+# ************************************************
+
+graph_exec_info = smart_scraper_graph.get_execution_info()
+print(prettify_exec_info(graph_exec_info))
+
# Save to json or csv
convert_to_csv(result, "result")
convert_to_json(result, "result")
diff --git a/examples/openai/scrape_xml_openai.py b/examples/openai/scrape_xml_openai.py
index be25e556..854c5422 100644
--- a/examples/openai/scrape_xml_openai.py
+++ b/examples/openai/scrape_xml_openai.py
@@ -5,7 +5,7 @@ Basic example of scraping pipeline using SmartScraper from XML documents
import os
from dotenv import load_dotenv
from scrapegraphai.graphs import SmartScraperGraph
-from scrapegraphai.utils import convert_to_csv, convert_to_json
+from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
load_dotenv()
# ************************************************
@@ -45,6 +45,13 @@ smart_scraper_graph = SmartScraperGraph(
result = smart_scraper_graph.run()
print(result)
+# ************************************************
+# Get graph execution info
+# ************************************************
+
+graph_exec_info = smart_scraper_graph.get_execution_info()
+print(prettify_exec_info(graph_exec_info))
+
# Save to json or csv
convert_to_csv(result, "result")
convert_to_json(result, "result")
diff --git a/examples/openai/search_graph_openai.py b/examples/openai/search_graph_openai.py
index 63217c7f..0e0ca28d 100644
--- a/examples/openai/search_graph_openai.py
+++ b/examples/openai/search_graph_openai.py
@@ -5,7 +5,7 @@ Example of Search Graph
import os
from dotenv import load_dotenv
from scrapegraphai.graphs import SearchGraph
-from scrapegraphai.utils import convert_to_csv, convert_to_json
+from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
load_dotenv()
# ************************************************
@@ -26,13 +26,20 @@ graph_config = {
# ************************************************
search_graph = SearchGraph(
- prompt="List me all the regions of Italy.",
+ prompt="List me top 5 eyeliner products for a gift.",
config=graph_config
)
result = search_graph.run()
print(result)
+# ************************************************
+# Get graph execution info
+# ************************************************
+
+graph_exec_info = search_graph.get_execution_info()
+print(prettify_exec_info(graph_exec_info))
+
# Save to json and csv
convert_to_csv(result, "result")
convert_to_json(result, "result")
diff --git a/examples/openai/smart_scraper_openai.py b/examples/openai/smart_scraper_openai.py
index 58f3788d..b319ef96 100644
--- a/examples/openai/smart_scraper_openai.py
+++ b/examples/openai/smart_scraper_openai.py
@@ -5,6 +5,7 @@ Basic example of scraping pipeline using SmartScraper
import os
from dotenv import load_dotenv
from scrapegraphai.graphs import SmartScraperGraph
+from scrapegraphai.utils import prettify_exec_info
load_dotenv()
@@ -26,11 +27,18 @@ graph_config = {
# ************************************************
smart_scraper_graph = SmartScraperGraph(
- prompt="List me all the news with their description.",
+ prompt="List me all the projects with their description.",
# also accepts a string with the already downloaded HTML code
- source="https://www.wired.com",
+ source="https://perinim.github.io/projects/",
config=graph_config
)
result = smart_scraper_graph.run()
print(result)
+
+# ************************************************
+# Get graph execution info
+# ************************************************
+
+graph_exec_info = smart_scraper_graph.get_execution_info()
+print(prettify_exec_info(graph_exec_info))
diff --git a/examples/openai/speech_graph_openai.py b/examples/openai/speech_graph_openai.py
index 051b33e6..ccd33de3 100644
--- a/examples/openai/speech_graph_openai.py
+++ b/examples/openai/speech_graph_openai.py
@@ -5,6 +5,7 @@ Basic example of scraping pipeline using SpeechSummaryGraph
import os
from dotenv import load_dotenv
from scrapegraphai.graphs import SpeechGraph
+from scrapegraphai.utils import prettify_exec_info
load_dotenv()
# ************************************************
@@ -25,6 +26,7 @@ graph_config = {
"llm": {
"api_key": openai_key,
"model": "gpt-3.5-turbo",
+ "temperature": 0.7,
},
"tts_model": {
"api_key": openai_key,
@@ -39,10 +41,17 @@ graph_config = {
# ************************************************
speech_graph = SpeechGraph(
- prompt="Create a summary of the website",
- source="https://perinim.github.io/projects/",
+ prompt="Give me a gift idea for a friend.",
+ source="https://www.amazon.it/s?k=profumo&__mk_it_IT=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=17UXSZNCS2NKE&sprefix=profumo%2Caps%2C88&ref=nb_sb_noss_1",
config=graph_config,
)
result = speech_graph.run()
print(result.get("answer", "No answer found"))
+
+# ************************************************
+# Get graph execution info
+# ************************************************
+
+graph_exec_info = speech_graph.get_execution_info()
+print(prettify_exec_info(graph_exec_info))
diff --git a/scrapegraphai/graphs/abstract_graph.py b/scrapegraphai/graphs/abstract_graph.py
index b2117855..5bc79a6d 100644
--- a/scrapegraphai/graphs/abstract_graph.py
+++ b/scrapegraphai/graphs/abstract_graph.py
@@ -6,7 +6,6 @@ from typing import Optional
from ..models import OpenAI, Gemini, Ollama, AzureOpenAI
from ..helpers import models_tokens
-
class AbstractGraph(ABC):
"""
Abstract class representing a generic graph-based tool.
@@ -23,6 +22,9 @@ class AbstractGraph(ABC):
self.embedder_model = None if "embeddings" not in config else self._create_llm(
config["embeddings"])
self.graph = self._create_graph()
+
+ self.final_state = None
+ self.execution_info = None
def _create_llm(self, llm_config: dict):
"""
@@ -30,7 +32,7 @@ class AbstractGraph(ABC):
"""
llm_defaults = {
"temperature": 0,
- "streaming": True
+ "streaming": False
}
llm_params = {**llm_defaults, **llm_config}
@@ -83,6 +85,12 @@ class AbstractGraph(ABC):
else:
raise ValueError("Model not supported")
+ def get_execution_info(self):
+ """
+ Returns the execution information of the graph.
+ """
+ return self.execution_info
+
@abstractmethod
def _create_graph(self):
"""
diff --git a/scrapegraphai/graphs/base_graph.py b/scrapegraphai/graphs/base_graph.py
index d513ddbd..9a04fcb1 100644
--- a/scrapegraphai/graphs/base_graph.py
+++ b/scrapegraphai/graphs/base_graph.py
@@ -1,7 +1,8 @@
"""
Module for creating the base graphs
"""
-
+import time
+from langchain_community.callbacks import get_openai_callback
class BaseGraph:
"""
@@ -62,9 +63,46 @@ class BaseGraph:
current_node_name = self.entry_point
state = initial_state
+ # variables for tracking execution info
+ total_exec_time = 0.0
+ exec_info = {}
+ cb_total = {
+ "total_tokens": 0,
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "successful_requests": 0,
+ "total_cost_USD": 0.0,
+ }
+
while current_node_name is not None:
+
+ curr_time = time.time()
current_node = self.nodes[current_node_name]
- result = current_node.execute(state)
+
+ with get_openai_callback() as cb:
+ result = current_node.execute(state)
+
+ node_exec_time = time.time() - curr_time
+ total_exec_time += node_exec_time
+
+ cb = {
+ "total_tokens": cb.total_tokens,
+ "prompt_tokens": cb.prompt_tokens,
+ "completion_tokens": cb.completion_tokens,
+ "successful_requests": cb.successful_requests,
+ "total_cost_USD": cb.total_cost,
+ }
+
+ exec_info[current_node_name] = {
+ "exec_time": node_exec_time,
+ "model_info": cb
+ }
+
+ cb_total["total_tokens"] += cb["total_tokens"]
+ cb_total["prompt_tokens"] += cb["prompt_tokens"]
+ cb_total["completion_tokens"] += cb["completion_tokens"]
+ cb_total["successful_requests"] += cb["successful_requests"]
+ cb_total["total_cost_USD"] += cb["total_cost_USD"]
if current_node.node_type == "conditional_node":
current_node_name = result
@@ -73,4 +111,10 @@ class BaseGraph:
else:
current_node_name = None
- return state
+ execution_info = {
+ "total_exec_time": total_exec_time,
+ "total_model_info": cb_total,
+ "nodes_info": exec_info
+ }
+
+ return state, execution_info
diff --git a/scrapegraphai/graphs/search_graph.py b/scrapegraphai/graphs/search_graph.py
index 3aac0e1a..ad21e485 100644
--- a/scrapegraphai/graphs/search_graph.py
+++ b/scrapegraphai/graphs/search_graph.py
@@ -11,7 +11,6 @@ from ..nodes import (
)
from .abstract_graph import AbstractGraph
-
class SearchGraph(AbstractGraph):
"""
Module for searching info on the internet
@@ -71,6 +70,6 @@ class SearchGraph(AbstractGraph):
Executes the web scraping and searching process.
"""
inputs = {"user_prompt": self.prompt}
- final_state = self.graph.execute(inputs)
+ self.final_state, self.execution_info = self.graph.execute(inputs)
- return final_state.get("answer", "No answer found.")
+ return self.final_state.get("answer", "No answer found.")
diff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.py
index baa17171..e413727b 100644
--- a/scrapegraphai/graphs/smart_scraper_graph.py
+++ b/scrapegraphai/graphs/smart_scraper_graph.py
@@ -10,7 +10,6 @@ from ..nodes import (
)
from .abstract_graph import AbstractGraph
-
class SmartScraperGraph(AbstractGraph):
"""
SmartScraper is a comprehensive web scraping tool that automates the process of extracting
@@ -71,7 +70,7 @@ class SmartScraperGraph(AbstractGraph):
"""
Executes the web scraping process and returns the answer to the prompt.
"""
- inputs = {"user_prompt": self.prompt, self.input_key: self.source}
- final_state = self.graph.execute(inputs)
+ inputs = {"user_prompt": self.prompt, self.input_key: self.source}
+ self.final_state, self.execution_info = self.graph.execute(inputs)
- return final_state.get("answer", "No answer found.")
+ return self.final_state.get("answer", "No answer found.")
diff --git a/scrapegraphai/graphs/speech_graph.py b/scrapegraphai/graphs/speech_graph.py
index 42633584..f050acb4 100644
--- a/scrapegraphai/graphs/speech_graph.py
+++ b/scrapegraphai/graphs/speech_graph.py
@@ -83,13 +83,13 @@ class SpeechGraph(AbstractGraph):
Executes the web scraping, summarization, and text-to-speech process.
"""
inputs = {"user_prompt": self.prompt, self.input_key: self.source}
- final_state = self.graph.execute(inputs)
+ self.final_state, self.execution_info = self.graph.execute(inputs)
- audio = final_state.get("audio", None)
+ audio = self.final_state.get("audio", None)
if not audio:
raise ValueError("No audio generated from the text.")
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_state
+ return self.final_state
diff --git a/scrapegraphai/nodes/search_internet_node.py b/scrapegraphai/nodes/search_internet_node.py
index 8d5813b2..a403b5cb 100644
--- a/scrapegraphai/nodes/search_internet_node.py
+++ b/scrapegraphai/nodes/search_internet_node.py
@@ -7,7 +7,6 @@ from langchain.prompts import PromptTemplate
from ..utils.research_web import search_on_web
from .base_node import BaseNode
-
class SearchInternetNode(BaseNode):
"""
A node that generates an answer by querying a language model (LLM) based on the user's input
diff --git a/scrapegraphai/utils/__init__.py b/scrapegraphai/utils/__init__.py
index e0bf7d52..2ea30cf1 100644
--- a/scrapegraphai/utils/__init__.py
+++ b/scrapegraphai/utils/__init__.py
@@ -4,3 +4,4 @@
from .save_audio_from_bytes import save_audio_from_bytes
from .convert_to_csv import convert_to_csv
from .convert_to_json import convert_to_json
+from .prettify_exec_info import prettify_exec_info
diff --git a/scrapegraphai/utils/prettify_exec_info.py b/scrapegraphai/utils/prettify_exec_info.py
new file mode 100644
index 00000000..b34a7f8a
--- /dev/null
+++ b/scrapegraphai/utils/prettify_exec_info.py
@@ -0,0 +1,45 @@
+"""
+Prettify the execution information of the graph.
+"""
+
+import pandas as pd
+
+def prettify_exec_info(complete_result: dict) -> pd.DataFrame:
+ """
+ Transform the execution information of the graph into a DataFrame for better visualization.
+
+ Args:
+ - complete_result (dict): The complete execution information of the graph.
+
+ Returns:
+ - pd.DataFrame: The execution information of the graph in a DataFrame.
+ """
+
+ nodes_info = complete_result['nodes_info']
+ total_info = {
+ 'total_exec_time': complete_result['total_exec_time'],
+ 'total_model_info': complete_result['total_model_info']
+ }
+
+ # Convert node-specific information to DataFrame
+ flat_data = []
+ for node_name, node_info in nodes_info.items():
+ flat_data.append({
+ 'Node': node_name,
+ 'Execution Time': node_info['exec_time'],
+ **node_info['model_info'] # Unpack the model_info dict into the row
+ })
+
+ df_nodes = pd.DataFrame(flat_data)
+
+ # Add a row for the total execution time and total model info
+ total_row = {
+ 'Node': 'Total',
+ 'Execution Time': total_info['total_exec_time'],
+ **total_info['total_model_info'] # Unpack the total_model_info dict into the row
+ }
+ df_total = pd.DataFrame([total_row])
+
+ # Combine the nodes DataFrame with the total info DataFrame
+ df_combined_with_total = pd.concat([df_nodes, df_total], ignore_index=True)
+ return df_combined_with_total
\ No newline at end of file