Skip to content

Python scraper based on AI

refactoring of the code

Marco Vinciguerra560f079d4cb2
diff --git a/scrapegraphai/docloaders/browser_base.py b/scrapegraphai/docloaders/browser_base.py
index c9413d68..cc9e7e85 100644
--- a/scrapegraphai/docloaders/browser_base.py
+++ b/scrapegraphai/docloaders/browser_base.py
@@ -13,8 +13,10 @@ def browser_base_fetch(api_key: str, project_id: str, link: List[str], text_cont
- `api_key`: The API key provided by BrowserBase.
- `project_id`: The ID of the project on BrowserBase where you want to fetch data from.
- `link`: The URL or link that you want to fetch data from.
- - `text_content`: A boolean flag to specify whether to return only the text content (True) or the full HTML (False).
- - `async_mode`: A boolean flag that determines whether the function runs asynchronously (True) or synchronously (False, default).
+ - `text_content`: A boolean flag to specify whether to return only the
+ text content (True) or the full HTML (False).
+ - `async_mode`: A boolean flag that determines whether the function runs asynchronously
+ (True) or synchronously (False, default).
It initializes a Browserbase object with the given API key and project ID,
then uses this object to load the specified link.
@@ -37,8 +39,10 @@ def browser_base_fetch(api_key: str, project_id: str, link: List[str], text_cont
api_key (str): The API key provided by BrowserBase.
project_id (str): The ID of the project on BrowserBase where you want to fetch data from.
link (str): The URL or link that you want to fetch data from.
- text_content (bool): Whether to return only the text content (True) or the full HTML (False). Defaults to True.
- async_mode (bool): Whether to run the function asynchronously (True) or synchronously (False). Defaults to False.
+ text_content (bool): Whether to return only the text content
+ (True) or the full HTML (False). Defaults to True.
+ async_mode (bool): Whether to run the function asynchronously
+ (True) or synchronously (False). Defaults to False.
Returns:
object: The result of the loading operation.
@@ -47,7 +51,8 @@ def browser_base_fetch(api_key: str, project_id: str, link: List[str], text_cont
try:
from browserbase import Browserbase
except ImportError:
- raise ImportError("The browserbase module is not installed. Please install it using `pip install browserbase`.")
+ raise ImportError(f"""The browserbase module is not installed.
+ Please install it using `pip install browserbase`.""")
browserbase = Browserbase(api_key=api_key, project_id=project_id)
diff --git a/scrapegraphai/docloaders/scrape_do.py b/scrapegraphai/docloaders/scrape_do.py
index cd9086c3..467ea0a1 100644
--- a/scrapegraphai/docloaders/scrape_do.py
+++ b/scrapegraphai/docloaders/scrape_do.py
@@ -24,17 +24,14 @@ def scrape_do_fetch(token, target_url, use_proxy=False, geoCode=None, super_prox
"""
encoded_url = urllib.parse.quote(target_url)
if use_proxy:
- # Create proxy mode URL
- proxyModeUrl = f"http://{token}:@proxy.scrape.do:8080"
+ proxy_mode_url = f"http://{token}:@proxy.scrape.do:8080"
proxies = {
- "http": proxyModeUrl,
- "https": proxyModeUrl,
+ "http": proxy_mode_url,
+ "https": proxy_mode_url,
}
- # Add optional geoCode and super proxy parameters if provided
params = {"geoCode": geoCode, "super": str(super_proxy).lower()} if geoCode else {}
response = requests.get(target_url, proxies=proxies, verify=False, params=params)
else:
- # API Mode URL
url = f"http://api.scrape.do?token={token}&url={encoded_url}"
response = requests.get(url)
diff --git a/scrapegraphai/graphs/__init__.py b/scrapegraphai/graphs/__init__.py
index ebe914fb..9b3f36c3 100644
--- a/scrapegraphai/graphs/__init__.py
+++ b/scrapegraphai/graphs/__init__.py
@@ -26,4 +26,4 @@ from .markdown_scraper_multi_graph import MDScraperMultiGraph
from .search_link_graph import SearchLinkGraph
from .screenshot_scraper_graph import ScreenshotScraperGraph
from .smart_scraper_multi_concat_graph import SmartScraperMultiConcatGraph
-from .code_generator_graph import CodeGeneratorGraph
\ No newline at end of file
+from .code_generator_graph import CodeGeneratorGraph
diff --git a/scrapegraphai/graphs/abstract_graph.py b/scrapegraphai/graphs/abstract_graph.py
index b546460f..99c13886 100644
--- a/scrapegraphai/graphs/abstract_graph.py
+++ b/scrapegraphai/graphs/abstract_graph.py
@@ -128,7 +128,7 @@ class AbstractGraph(ABC):
if requests_per_second is not None:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
- llm_params["rate_limiter"] = InMemoryRateLimiter(requests_per_second=requests_per_second)
+ llm_params["rate_limiter"] = InMemoryRateLimiter(requests_per_second=requests_per_second)
if max_retries is not None:
llm_params["max_retries"] = max_retries
diff --git a/scrapegraphai/graphs/base_graph.py b/scrapegraphai/graphs/base_graph.py
index 6d160e37..05f9773c 100644
--- a/scrapegraphai/graphs/base_graph.py
+++ b/scrapegraphai/graphs/base_graph.py
@@ -45,7 +45,8 @@ class BaseGraph:
... )
"""
- def __init__(self, nodes: list, edges: list, entry_point: str, use_burr: bool = False, burr_config: dict = None, graph_name: str = "Custom"):
+ def __init__(self, nodes: list, edges: list, entry_point: str,
+ use_burr: bool = False, burr_config: dict = None, graph_name: str = "Custom"):
self.nodes = nodes
self.raw_edges = edges
self.edges = self._create_edges({e for e in edges})
diff --git a/scrapegraphai/graphs/code_generator_graph.py b/scrapegraphai/graphs/code_generator_graph.py
index 9786dc4f..c0c0f52b 100644
--- a/scrapegraphai/graphs/code_generator_graph.py
+++ b/scrapegraphai/graphs/code_generator_graph.py
@@ -51,7 +51,7 @@ class CodeGeneratorGraph(AbstractGraph):
"""
def __init__(self, prompt: str, source: str, config: dict, schema: Optional[BaseModel] = None):
-
+
super().__init__(prompt, config, source, schema)
self.input_key = "url" if source.startswith("http") else "local_dir"
@@ -63,7 +63,7 @@ class CodeGeneratorGraph(AbstractGraph):
Returns:
BaseGraph: A graph instance representing the web scraping workflow.
"""
-
+
if self.schema is None:
raise KeyError("The schema is required for CodeGeneratorGraph")
diff --git a/scrapegraphai/graphs/deep_scraper_graph.py b/scrapegraphai/graphs/deep_scraper_graph.py
index 404fed9f..f3f2ec2d 100644
--- a/scrapegraphai/graphs/deep_scraper_graph.py
+++ b/scrapegraphai/graphs/deep_scraper_graph.py
@@ -134,7 +134,6 @@ class DeepScraperGraph(AbstractGraph):
)
-
def _create_graph(self) -> BaseGraph:
"""
Creates the graph of nodes representing the workflow for web scraping
diff --git a/scrapegraphai/graphs/omni_search_graph.py b/scrapegraphai/graphs/omni_search_graph.py
index 807a5b0a..41d35ab7 100644
--- a/scrapegraphai/graphs/omni_search_graph.py
+++ b/scrapegraphai/graphs/omni_search_graph.py
@@ -14,7 +14,6 @@ from ..nodes import (
)
from ..utils.copy import safe_deepcopy
-
class OmniSearchGraph(AbstractGraph):
"""
OmniSearchGraph is a scraping pipeline that searches the internet for answers to a given prompt.
diff --git a/scrapegraphai/graphs/screenshot_scraper_graph.py b/scrapegraphai/graphs/screenshot_scraper_graph.py
index f3ce608d..174e245a 100644
--- a/scrapegraphai/graphs/screenshot_scraper_graph.py
+++ b/scrapegraphai/graphs/screenshot_scraper_graph.py
@@ -47,6 +47,7 @@ class ScreenshotScraperGraph(AbstractGraph):
"link": self.source
}
)
+
generate_answer_from_image_node = GenerateAnswerFromImageNode(
input="screenshots",
output=["answer"],
diff --git a/scrapegraphai/graphs/script_creator_graph.py b/scrapegraphai/graphs/script_creator_graph.py
index 732fb3cf..f6a884a1 100644
--- a/scrapegraphai/graphs/script_creator_graph.py
+++ b/scrapegraphai/graphs/script_creator_graph.py
@@ -68,6 +68,7 @@ class ScriptCreatorGraph(AbstractGraph):
"script_creator": True
}
)
+
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
@@ -76,6 +77,7 @@ class ScriptCreatorGraph(AbstractGraph):
"llm_model": self.llm_model
}
)
+
generate_scraper_node = GenerateScraperNode(
input="user_prompt & (parsed_doc)",
output=["answer"],
diff --git a/scrapegraphai/graphs/search_graph.py b/scrapegraphai/graphs/search_graph.py
index 7b29e051..8086caa6 100644
--- a/scrapegraphai/graphs/search_graph.py
+++ b/scrapegraphai/graphs/search_graph.py
@@ -4,11 +4,9 @@ SearchGraph Module
from copy import deepcopy
from typing import Optional, List
from pydantic import BaseModel
-
from .base_graph import BaseGraph
from .abstract_graph import AbstractGraph
from .smart_scraper_graph import SmartScraperGraph
-
from ..nodes import (
SearchInternetNode,
GraphIteratorNode,
@@ -77,6 +75,7 @@ class SearchGraph(AbstractGraph):
"search_engine": self.copy_config.get("search_engine")
}
)
+
graph_iterator_node = GraphIteratorNode(
input="user_prompt & urls",
output=["results"],
diff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.py
index 0c025c3a..e2bda63f 100644
--- a/scrapegraphai/graphs/smart_scraper_graph.py
+++ b/scrapegraphai/graphs/smart_scraper_graph.py
@@ -69,6 +69,7 @@ class SmartScraperGraph(AbstractGraph):
"scrape_do": self.config.get("scrape_do")
}
)
+
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
diff --git a/scrapegraphai/graphs/smart_scraper_multi_graph.py b/scrapegraphai/graphs/smart_scraper_multi_graph.py
index 183d8144..5dff3277 100644
--- a/scrapegraphai/graphs/smart_scraper_multi_graph.py
+++ b/scrapegraphai/graphs/smart_scraper_multi_graph.py
@@ -45,9 +45,7 @@ class SmartScraperMultiGraph(AbstractGraph):
config: dict, schema: Optional[BaseModel] = None):
self.max_results = config.get("max_results", 3)
-
self.copy_config = safe_deepcopy(config)
-
self.copy_schema = deepcopy(schema)
super().__init__(prompt, config, source, schema)
diff --git a/scrapegraphai/graphs/speech_graph.py b/scrapegraphai/graphs/speech_graph.py
index 6065bcf4..d491d4bc 100644
--- a/scrapegraphai/graphs/speech_graph.py
+++ b/scrapegraphai/graphs/speech_graph.py
@@ -61,6 +61,7 @@ class SpeechGraph(AbstractGraph):
input="url | local_dir",
output=["doc"]
)
+
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
@@ -69,6 +70,7 @@ class SpeechGraph(AbstractGraph):
"llm_model": self.llm_model
}
)
+
generate_answer_node = GenerateAnswerNode(
input="user_prompt & (relevant_chunks | parsed_doc | doc)",
output=["answer"],
@@ -78,6 +80,7 @@ class SpeechGraph(AbstractGraph):
"schema": self.schema
}
)
+
text_to_speech_node = TextToSpeechNode(
input="answer",
output=["audio"],
diff --git a/scrapegraphai/integrations/burr_bridge.py b/scrapegraphai/integrations/burr_bridge.py
index 76cce914..959634bb 100644
--- a/scrapegraphai/integrations/burr_bridge.py
+++ b/scrapegraphai/integrations/burr_bridge.py
@@ -15,7 +15,8 @@ try:
from burr.core import Application, ApplicationBuilder, State, Action, default, ApplicationContext
from burr.lifecycle import PostRunStepHook, PreRunStepHook
except ImportError:
- raise ImportError("burr package is not installed. Please install it with 'pip install scrapegraphai[burr]'")
+ raise ImportError("""burr package is not installed.
+ Please install it with 'pip install scrapegraphai[burr]'""")
class PrintLnHook(PostRunStepHook, PreRunStepHook):
@@ -32,7 +33,8 @@ class PrintLnHook(PostRunStepHook, PreRunStepHook):
class BurrNodeBridge(Action):
"""Bridge class to convert a base graph node to a Burr action.
- This is nice because we can dynamically declare the inputs/outputs (and not rely on function-parsing).
+ This is nice because we can dynamically declare
+ the inputs/outputs (and not rely on function-parsing).
"""
def __init__(self, node):
@@ -63,7 +65,8 @@ class BurrNodeBridge(Action):
def parse_boolean_expression(expression: str) -> List[str]:
"""
- Parse a boolean expression to extract the keys used in the expression, without boolean operators.
+ Parse a boolean expression to extract the keys
+ used in the expression, without boolean operators.
Args:
expression (str): The boolean expression to parse.
@@ -136,10 +139,9 @@ class BurrBridge:
if application_context is not None:
builder = (
builder
- # if we're using a tracker, we want to copy it/pass in
.with_tracker(
application_context.tracker.copy() if application_context.tracker is not None else None
- ) # remember to do `copy()` here!
+ )
.with_spawning_parent(
application_context.app_id,
application_context.sequence_id,
@@ -157,7 +159,8 @@ class BurrBridge:
Create Burr actions from the base graph nodes.
Returns:
- dict: A dictionary of Burr actions with the node name as keys and the action functions as values.
+ dict: A dictionary of Burr actions with the node name
+ as keys and the action functions as values.
"""
actions = {}
diff --git a/scrapegraphai/integrations/indexify_node.py b/scrapegraphai/integrations/indexify_node.py
index e12adc69..cf15cd0e 100644
--- a/scrapegraphai/integrations/indexify_node.py
+++ b/scrapegraphai/integrations/indexify_node.py
@@ -3,16 +3,9 @@ IndexifyNode Module
"""
from typing import List, Optional
-
from ..utils.logging import get_logger
from ..nodes.base_node import BaseNode
-# try:
-# import indexify
-# except ImportError:
-# raise ImportError("indexify package is not installed. Please install it with 'pip install scrapegraphai[indexify]'")
-
-
class IndexifyNode(BaseNode):
"""
A node responsible for indexing the content present in the state.
@@ -61,7 +54,7 @@ class IndexifyNode(BaseNode):
# Interpret input keys based on the provided input expression
# input_keys length matches the min_input_len parameter in the __init__ method
# e.g. "answer & parsed_doc" or "answer | img_urls"
-
+
input_keys = self.get_input_keys(state)
# Fetching data from the state based on the input keys
diff --git a/scrapegraphai/nodes/base_node.py b/scrapegraphai/nodes/base_node.py
index e4dae794..8ba55452 100644
--- a/scrapegraphai/nodes/base_node.py
+++ b/scrapegraphai/nodes/base_node.py
@@ -192,18 +192,14 @@ class BaseNode(ABC):
"Invalid operator placement: operators cannot be adjacent."
)
- # Check for missing or balanced parentheses
if open_parentheses != close_parentheses:
raise ValueError("Missing or unbalanced parentheses in expression.")
- # Helper function to evaluate an expression without parentheses
def evaluate_simple_expression(exp: str) -> List[str]:
"""Evaluate an expression without parentheses."""
- # Split the expression by the OR operator and process each segment
for or_segment in exp.split("|"):
- # Check if all elements in an AND segment are in state
and_segment = or_segment.split("&")
if all(elem.strip() in state for elem in and_segment):
return [
@@ -211,7 +207,6 @@ class BaseNode(ABC):
]
return []
- # Helper function to evaluate expressions with parentheses
def evaluate_expression(expression: str) -> List[str]:
"""Evaluate an expression with parentheses."""
@@ -220,10 +215,8 @@ class BaseNode(ABC):
end = expression.find(")", start)
sub_exp = expression[start + 1 : end]
- # Replace the evaluated part with a placeholder and then evaluate it
sub_result = evaluate_simple_expression(sub_exp)
- # For simplicity in handling, join sub-results with OR to reprocess them later
expression = (
expression[:start] + "|".join(sub_result) + expression[end + 1 :]
)
@@ -236,7 +229,6 @@ class BaseNode(ABC):
Expression was {expression}.
State contains keys: {', '.join(state.keys())}""")
- # Remove redundant state keys from the result, without changing their order
final_result = []
for key in result:
if key not in final_result:
diff --git a/scrapegraphai/nodes/concat_answers_node.py b/scrapegraphai/nodes/concat_answers_node.py
index d9afc356..438218b5 100644
--- a/scrapegraphai/nodes/concat_answers_node.py
+++ b/scrapegraphai/nodes/concat_answers_node.py
@@ -56,19 +56,15 @@ class ConcatAnswersNode(BaseNode):
self.logger.info(f"--- Executing {self.node_name} Node ---")
- # Interpret input keys based on the provided input expression
input_keys = self.get_input_keys(state)
- # Fetching data from the state based on the input keys
input_data = [state[key] for key in input_keys]
answers = input_data[0]
-
+
if len(answers) > 1:
- # merge the answers in one string
answer = self._merge_dict(answers)
- # Update the state with the generated answer
state.update({self.output[0]: answer})
else:
diff --git a/scrapegraphai/nodes/fetch_node.py b/scrapegraphai/nodes/fetch_node.py
index 053a655b..a548e05b 100644
--- a/scrapegraphai/nodes/fetch_node.py
+++ b/scrapegraphai/nodes/fetch_node.py
@@ -219,7 +219,9 @@ class FetchNode(BaseNode):
parsed_content = source
- if (isinstance(self.llm_model, ChatOpenAI) or isinstance(self.llm_model, AzureChatOpenAI)) and not self.script_creator or self.force and not self.script_creator:
+ if (isinstance(self.llm_model, ChatOpenAI) or \
+ isinstance(self.llm_model, AzureChatOpenAI)) \
+ and not self.script_creator or self.force and not self.script_creator:
parsed_content = convert_to_md(source)
else:
parsed_content = source
diff --git a/scrapegraphai/nodes/generate_answer_csv_node.py b/scrapegraphai/nodes/generate_answer_csv_node.py
index a335381d..0419d891 100644
--- a/scrapegraphai/nodes/generate_answer_csv_node.py
+++ b/scrapegraphai/nodes/generate_answer_csv_node.py
@@ -81,16 +81,13 @@ class GenerateAnswerCSVNode(BaseNode):
self.logger.info(f"--- Executing {self.node_name} Node ---")
- # Interpret input keys based on the provided input expression
input_keys = self.get_input_keys(state)
- # Fetching data from the state based on the input keys
input_data = [state[key] for key in input_keys]
user_prompt = input_data[0]
doc = input_data[1]
- # Initialize the output parser
if self.node_config.get("schema", None) is not None:
if isinstance(self.llm_model, (ChatOpenAI, ChatMistralAI)):
diff --git a/scrapegraphai/nodes/generate_answer_omni_node.py b/scrapegraphai/nodes/generate_answer_omni_node.py
index 2824a573..403240dd 100644
--- a/scrapegraphai/nodes/generate_answer_omni_node.py
+++ b/scrapegraphai/nodes/generate_answer_omni_node.py
@@ -81,7 +81,6 @@ class GenerateAnswerOmniNode(BaseNode):
doc = input_data[1]
imag_desc = input_data[2]
- # Initialize the output parser
if self.node_config.get("schema", None) is not None:
if isinstance(self.llm_model, (ChatOpenAI, ChatMistralAI)):
diff --git a/scrapegraphai/nodes/generate_code_node.py b/scrapegraphai/nodes/generate_code_node.py
index 35de0da0..cc72aaf4 100644
--- a/scrapegraphai/nodes/generate_code_node.py
+++ b/scrapegraphai/nodes/generate_code_node.py
@@ -173,7 +173,9 @@ class GenerateCodeNode(BaseNode):
continue
break
- if state["iteration"] == self.max_iterations["overall"] and (state["errors"]["syntax"] or state["errors"]["execution"] or state["errors"]["validation"] or state["errors"]["semantic"]):
+ if state["iteration"] == self.max_iterations["overall"] and \
+ (state["errors"]["syntax"] or state["errors"]["execution"] \
+ or state["errors"]["validation"] or state["errors"]["semantic"]):
raise RuntimeError("Max iterations reached without obtaining the desired code.")
self.logger.info(f"--- (Code Generated Correctly) ---")
@@ -238,7 +240,8 @@ class GenerateCodeNode(BaseNode):
def semantic_comparison_loop(self, state: dict) -> dict:
for _ in range(self.max_iterations["semantic"]):
- comparison_result = self.semantic_comparison(state["execution_result"], state["reference_answer"])
+ comparison_result = self.semantic_comparison(state["execution_result"],
+ state["reference_answer"])
if comparison_result["are_semantically_equivalent"]:
state["errors"]["semantic"] = []
return state
diff --git a/scrapegraphai/nodes/image_to_text_node.py b/scrapegraphai/nodes/image_to_text_node.py
index 13113aa0..00c71e93 100644
--- a/scrapegraphai/nodes/image_to_text_node.py
+++ b/scrapegraphai/nodes/image_to_text_node.py
@@ -62,10 +62,9 @@ class ImageToTextNode(BaseNode):
elif len(urls) == 0:
return state.update({self.output[0]: []})
- # Skip the image-to-text conversion
if self.max_images < 1:
return state.update({self.output[0]: []})
-
+
img_desc = []
for url in urls[: self.max_images]:
try:
diff --git a/scrapegraphai/nodes/parse_node.py b/scrapegraphai/nodes/parse_node.py
index 46e9c1d1..fd2f3810 100644
--- a/scrapegraphai/nodes/parse_node.py
+++ b/scrapegraphai/nodes/parse_node.py
@@ -118,7 +118,7 @@ class ParseNode(BaseNode):
"""
if not self.parse_urls:
return [], []
-
+
image_extensions = default_filters.filter_dict["img_exts"]
image_extension_seq = '|'.join(image_extensions).replace('.','')
url_pattern = re.compile(r'(https?://[^\s]+|\S+\.(?:' + image_extension_seq + '))')
@@ -130,12 +130,12 @@ class ParseNode(BaseNode):
all_urls = [url for url in all_urls if url.startswith("http")]
else:
all_urls = [urljoin(source, url) for url in all_urls]
-
+
images = [url for url in all_urls if any(url.endswith(ext) for ext in image_extensions)]
links = [url for url in all_urls if url not in images]
return links, images
-
+
def _clean_urls(self, urls: List[str]) -> List[str]:
"""
Cleans the URLs extracted from the text.
@@ -150,7 +150,7 @@ class ParseNode(BaseNode):
for url in urls:
url = re.sub(r'.*?\]\(', '', url)
url = url.rstrip(').')
-
+
cleaned_urls.append(url)
-
- return cleaned_urls
\ No newline at end of file
+
+ return cleaned_urls
diff --git a/scrapegraphai/nodes/search_link_node.py b/scrapegraphai/nodes/search_link_node.py
index 935a64ba..10907850 100644
--- a/scrapegraphai/nodes/search_link_node.py
+++ b/scrapegraphai/nodes/search_link_node.py
@@ -13,7 +13,6 @@ from .base_node import BaseNode
from ..prompts import TEMPLATE_RELEVANT_LINKS
from ..helpers import default_filters
-
class SearchLinkNode(BaseNode):
"""
A node that can filter out the relevant links in the webpage content for the user prompt.
diff --git a/scrapegraphai/prompts/generate_answer_node_csv_prompts.py b/scrapegraphai/prompts/generate_answer_node_csv_prompts.py
index 8df8bde3..b131890e 100644
--- a/scrapegraphai/prompts/generate_answer_node_csv_prompts.py
+++ b/scrapegraphai/prompts/generate_answer_node_csv_prompts.py
@@ -1,6 +1,7 @@
"""
Generate answer csv schema
"""
+
TEMPLATE_CHUKS_CSV = """
You are a scraper and you have just scraped the
following content from a csv.
diff --git a/scrapegraphai/prompts/generate_answer_node_pdf_prompts.py b/scrapegraphai/prompts/generate_answer_node_pdf_prompts.py
index a3ea9bef..04472bfa 100644
--- a/scrapegraphai/prompts/generate_answer_node_pdf_prompts.py
+++ b/scrapegraphai/prompts/generate_answer_node_pdf_prompts.py
@@ -1,6 +1,7 @@
"""
Generate anwer node pdf prompt
"""
+
TEMPLATE_CHUNKS_PDF = """
You are a scraper and you have just scraped the
following content from a PDF.
diff --git a/scrapegraphai/prompts/generate_code_node_prompts.py b/scrapegraphai/prompts/generate_code_node_prompts.py
index eab92ee4..35d4f786 100644
--- a/scrapegraphai/prompts/generate_code_node_prompts.py
+++ b/scrapegraphai/prompts/generate_code_node_prompts.py
@@ -2,7 +2,6 @@
Generate code prompts helper
"""
-
TEMPLATE_INIT_CODE_GENERATION = """
**Task**: Create a Python function named `extract_data(html: str) -> dict()` using BeautifulSoup that extracts relevant information from the given HTML code string and returns it in a dictionary matching the Desired JSON Output Schema.
diff --git a/scrapegraphai/prompts/html_analyzer_node_prompts.py b/scrapegraphai/prompts/html_analyzer_node_prompts.py
index d7e6e342..97961047 100644
--- a/scrapegraphai/prompts/html_analyzer_node_prompts.py
+++ b/scrapegraphai/prompts/html_analyzer_node_prompts.py
@@ -2,7 +2,6 @@
HTML analysis prompts helper
"""
-
TEMPLATE_HTML_ANALYSIS = """
Task: Your job is to analyze the provided HTML code in relation to the initial scraping task analysis and provide all the necessary HTML information useful for implementing a function that extracts data from the given HTML string.
diff --git a/scrapegraphai/telemetry/telemetry.py b/scrapegraphai/telemetry/telemetry.py
index 61af900c..91073e28 100644
--- a/scrapegraphai/telemetry/telemetry.py
+++ b/scrapegraphai/telemetry/telemetry.py
@@ -14,6 +14,7 @@ To disable sending telemetry there are three ways:
or:
export SCRAPEGRAPHAI_TELEMETRY_ENABLED=false
"""
+
import configparser
import functools
import importlib.metadata
diff --git a/scrapegraphai/utils/cleanup_code.py b/scrapegraphai/utils/cleanup_code.py
index 9bf91e62..ad3d437b 100644
--- a/scrapegraphai/utils/cleanup_code.py
+++ b/scrapegraphai/utils/cleanup_code.py
@@ -5,7 +5,7 @@ import re
def extract_code(code: str) -> str:
pattern = r'```(?:python)?\n(.*?)```'
-
+
match = re.search(pattern, code, re.DOTALL)
-
- return match.group(1) if match else code
\ No newline at end of file
+
+ return match.group(1) if match else code
diff --git a/scrapegraphai/utils/cleanup_html.py b/scrapegraphai/utils/cleanup_html.py
index 1521fe01..832f811e 100644
--- a/scrapegraphai/utils/cleanup_html.py
+++ b/scrapegraphai/utils/cleanup_html.py
@@ -57,22 +57,17 @@ def cleanup_html(html_content: str, base_url: str) -> str:
def minify_html(html):
- # Remove comments
+ """
+ minify_html function
+ """
html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)
-
- # Remove whitespace between tags
+
html = re.sub(r'>\s+<', '><', html)
-
- # Remove whitespace at the beginning and end of tags
html = re.sub(r'\s+>', '>', html)
html = re.sub(r'<\s+', '<', html)
-
- # Collapse multiple whitespace characters into a single space
html = re.sub(r'\s+', ' ', html)
-
- # Remove spaces around equals signs in attributes
html = re.sub(r'\s*=\s*', '=', html)
-
+
return html.strip()
def reduce_html(html, reduction):
@@ -84,52 +79,45 @@ def reduce_html(html, reduction):
reduction (int): The level of reduction to apply to the HTML content.
0: minification only,
1: minification and removig unnecessary tags and attributes,
- 2: minification, removig unnecessary tags and attributes, simplifying text content, removing of the head tag
+ 2: minification, removig unnecessary tags and attributes,
+ simplifying text content, removing of the head tag
Returns:
str: The reduced HTML content based on the specified reduction level.
"""
if reduction == 0:
return minify_html(html)
-
+
soup = BeautifulSoup(html, 'html.parser')
-
- # Remove comments
+
for comment in soup.find_all(string=lambda text: isinstance(text, Comment)):
comment.extract()
-
- # Remove script and style tag contents, but keep the tags
+
for tag in soup(['script', 'style']):
tag.string = ""
-
- # Remove unnecessary attributes, but keep class and id
+
attrs_to_keep = ['class', 'id', 'href', 'src']
for tag in soup.find_all(True):
for attr in list(tag.attrs):
if attr not in attrs_to_keep:
del tag[attr]
-
+
if reduction == 1:
return minify_html(str(soup))
-
- # Remove script and style tags completely
+
for tag in soup(['script', 'style']):
tag.decompose()
-
- # Focus only on the body
+
body = soup.body
if not body:
return "No <body> tag found in the HTML"
-
- # Simplify text content
+
for tag in body.find_all(string=True):
if tag.parent.name not in ['script', 'style']:
tag.replace_with(re.sub(r'\s+', ' ', tag.strip())[:20])
-
- # Generate reduced HTML
+
reduced_html = str(body)
-
- # Apply minification
+
reduced_html = minify_html(reduced_html)
-
- return reduced_html
\ No newline at end of file
+
+ return reduced_html
diff --git a/scrapegraphai/utils/code_error_analysis.py b/scrapegraphai/utils/code_error_analysis.py
index fba7e005..ac955502 100644
--- a/scrapegraphai/utils/code_error_analysis.py
+++ b/scrapegraphai/utils/code_error_analysis.py
@@ -45,4 +45,4 @@ def semantic_focused_analysis(state: dict, comparison_result: Dict[str, Any], ll
"generated_code": state["generated_code"],
"differences": json.dumps(comparison_result["differences"], indent=2),
"explanation": comparison_result["explanation"]
- })
\ No newline at end of file
+ })
diff --git a/scrapegraphai/utils/code_error_correction.py b/scrapegraphai/utils/code_error_correction.py
index 276c7a62..52e92e4c 100644
--- a/scrapegraphai/utils/code_error_correction.py
+++ b/scrapegraphai/utils/code_error_correction.py
@@ -1,9 +1,9 @@
"""
This module contains the code generation functions for code correction for different types errors.
"""
+import json
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
-import json
from ..prompts import (
TEMPLATE_SYNTAX_CODE_GENERATION, TEMPLATE_EXECUTION_CODE_GENERATION,
TEMPLATE_VALIDATION_CODE_GENERATION, TEMPLATE_SEMANTIC_CODE_GENERATION
@@ -42,4 +42,4 @@ def semantic_focused_code_generation(state: dict, analysis: str, llm_model) -> s
"generated_code": state["generated_code"],
"generated_result": json.dumps(state["execution_result"], indent=2),
"reference_result": json.dumps(state["reference_answer"], indent=2)
- })
\ No newline at end of file
+ })
diff --git a/scrapegraphai/utils/llm_callback_manager.py b/scrapegraphai/utils/llm_callback_manager.py
index 03bdaf0b..86a4de83 100644
--- a/scrapegraphai/utils/llm_callback_manager.py
+++ b/scrapegraphai/utils/llm_callback_manager.py
@@ -1,6 +1,7 @@
"""
This module provides a custom callback manager for the LLM models.
"""
+
import threading
from contextlib import contextmanager
from langchain_community.callbacks import get_openai_callback
diff --git a/scrapegraphai/utils/output_parser.py b/scrapegraphai/utils/output_parser.py
index 3eabfa8b..c3d81e9c 100644
--- a/scrapegraphai/utils/output_parser.py
+++ b/scrapegraphai/utils/output_parser.py
@@ -22,7 +22,9 @@ def get_structured_output_parser(schema: Union[Dict[str, Any],
return _dict_output_parser
-def get_pydantic_output_parser(schema: Union[Dict[str, Any], Type[BaseModelV1 | BaseModelV2], Type]) -> JsonOutputParser:
+def get_pydantic_output_parser(schema: Union[Dict[str, Any],
+ Type[BaseModelV1 | BaseModelV2], Type])
+-> JsonOutputParser:
"""
Get the correct output parser for the LLM model.
diff --git a/scrapegraphai/utils/prettify_exec_info.py b/scrapegraphai/utils/prettify_exec_info.py
index 07a36e49..7582bac7 100644
--- a/scrapegraphai/utils/prettify_exec_info.py
+++ b/scrapegraphai/utils/prettify_exec_info.py
@@ -3,7 +3,6 @@ Prettify the execution information of the graph.
"""
import pandas as pd
-
def prettify_exec_info(complete_result: list[dict]) -> pd.DataFrame:
"""
Transforms the execution information of a graph into a DataFrame for enhanced visualization.