Skip to content

Python scraper based on AI

Code generator updated version

Matteo Vedovati34590664f158
diff --git a/examples/code_generation/simple_with_schema.py b/examples/code_generation/simple_with_schema.py
index c4803c62..58e12e0e 100644
--- a/examples/code_generation/simple_with_schema.py
+++ b/examples/code_generation/simple_with_schema.py
@@ -30,12 +30,18 @@ openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
"llm": {
"api_key":openai_key,
- "model": "openai/gpt-4o",\
+ "model": "openai/gpt-4o-mini",\
},
- "library": "beautifulsoup",
"verbose": True,
"headless": False,
"reduction": 2,
+ "max_iterations": {
+ "overall": 10,
+ "syntax": 3,
+ "execution": 3,
+ "validation": 3,
+ "semantic": 3
+ },
}
# ************************************************
diff --git a/scrapegraphai/graphs/code_generator_graph.py b/scrapegraphai/graphs/code_generator_graph.py
index 6dc769b0..6eaa05af 100644
--- a/scrapegraphai/graphs/code_generator_graph.py
+++ b/scrapegraphai/graphs/code_generator_graph.py
@@ -49,8 +49,6 @@ class CodeGeneratorGraph(AbstractGraph):
def __init__(self, prompt: str, source: str, config: dict, schema: Optional[BaseModel] = None):
- self.library = config['library']
-
super().__init__(prompt, config, source, schema)
self.input_key = "url" if source.startswith("http") else "local_dir"
@@ -119,10 +117,16 @@ class CodeGeneratorGraph(AbstractGraph):
input="user_prompt & refined_prompt & html_info & reduced_html & answer",
output=["generated_code"],
node_config={
- "library": self.library,
"llm_model": self.llm_model,
"additional_info": self.config.get("additional_info"),
- "schema": self.schema
+ "schema": self.schema,
+ "max_iterations": self.config.get("max_iterations", {
+ "overall": 10,
+ "syntax": 3,
+ "execution": 3,
+ "validation": 3,
+ "semantic": 3
+ }),
}
)
diff --git a/scrapegraphai/nodes/generate_code_node.py b/scrapegraphai/nodes/generate_code_node.py
index 77fc6378..1fef3c5c 100644
--- a/scrapegraphai/nodes/generate_code_node.py
+++ b/scrapegraphai/nodes/generate_code_node.py
@@ -1,8 +1,9 @@
"""
GenerateCodeNode Module
"""
-from typing import List, Optional
+from typing import Any, Dict, List, Optional, Tuple
from langchain.prompts import PromptTemplate
+from langchain.output_parsers import ResponseSchema, StructuredOutputParser
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableParallel
from langchain_core.utils.pydantic import is_basemodel_subclass
@@ -19,6 +20,8 @@ from .base_node import BaseNode
from pydantic import ValidationError
from ..utils import transform_schema
from jsonschema import validate, ValidationError
+import json
+import string
class GenerateCodeNode(BaseNode):
@@ -69,10 +72,11 @@ class GenerateCodeNode(BaseNode):
"overall": 10,
"syntax": 3,
"execution": 3,
- "validation": 3
+ "validation": 3,
+ "semantic": 3
})
- self.output_schema = node_config.get("schema").schema() # get JSON output schema
+ self.output_schema = node_config.get("schema") # get JSON output schema
def execute(self, state: dict) -> dict:
"""
@@ -104,7 +108,7 @@ class GenerateCodeNode(BaseNode):
self.raw_html = state['original_html'][0].page_content
- simplefied_schema = str(transform_schema(self.output_schema)) # get JSON output schema
+ simplefied_schema = str(transform_schema(self.output_schema.schema())) # get JSON output schema
reasoning_state = {
"user_input": user_prompt,
@@ -114,10 +118,12 @@ class GenerateCodeNode(BaseNode):
"html_analysis": html_info,
"generated_code": "",
"execution_result": None,
+ "reference_answer": answer,
"errors": {
"syntax": [],
"execution": [],
- "validation": []
+ "validation": [],
+ "semantic": []
},
"iteration": 0
}
@@ -131,6 +137,7 @@ class GenerateCodeNode(BaseNode):
def overall_reasoning_loop(self, state: dict) -> dict:
state["generated_code"] = self.generate_initial_code(state)
+ state["generated_code"] = self.extract_code(state["generated_code"])
while state["iteration"] < self.max_iterations["overall"]:
state["iteration"] += 1
@@ -147,6 +154,10 @@ class GenerateCodeNode(BaseNode):
if state["errors"]["validation"]:
continue
+ state = self.semantic_comparison_loop(state)
+ if state["errors"]["semantic"]:
+ continue
+
# If we've made it here, the code is valid and produces the correct output
break
@@ -162,11 +173,12 @@ class GenerateCodeNode(BaseNode):
state["errors"]["syntax"] = [syntax_message]
analysis = self.syntax_focused_analysis(state)
state["generated_code"] = self.syntax_focused_code_generation(state, analysis)
+ state["generated_code"] = self.extract_code(state["generated_code"])
return state
- def execution_reasoning_loop(self, state: dict, raw_html: str) -> dict:
+ def execution_reasoning_loop(self, state: dict) -> dict:
for _ in range(self.max_iterations["execution"]):
- execution_success, execution_result = self.create_sandbox_and_execute(state["generated_code"], raw_html)
+ execution_success, execution_result = self.create_sandbox_and_execute(state["generated_code"])
if execution_success:
state["execution_result"] = execution_result
state["errors"]["execution"] = []
@@ -175,6 +187,7 @@ class GenerateCodeNode(BaseNode):
state["errors"]["execution"] = [execution_result]
analysis = self.execution_focused_analysis(state)
state["generated_code"] = self.execution_focused_code_generation(state, analysis)
+ state["generated_code"] = self.extract_code(state["generated_code"])
return state
def validation_reasoning_loop(self, state: dict) -> dict:
@@ -187,6 +200,20 @@ class GenerateCodeNode(BaseNode):
state["errors"]["validation"] = errors
analysis = self.validation_focused_analysis(state)
state["generated_code"] = self.validation_focused_code_generation(state, analysis)
+ state["generated_code"] = self.extract_code(state["generated_code"])
+ return state
+
+ 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"])
+ if comparison_result["are_semantically_equivalent"]:
+ state["errors"]["semantic"] = []
+ return state
+
+ state["errors"]["semantic"] = comparison_result["differences"]
+ analysis = self.semantic_focused_analysis(state, comparison_result)
+ state["generated_code"] = self.semantic_focused_code_generation(state, analysis)
+ state["generated_code"] = self.extract_code(state["generated_code"])
return state
def generate_initial_code(self, state: dict) -> str:
@@ -409,6 +436,114 @@ class GenerateCodeNode(BaseNode):
"json_schema": state["json_schema"]
})
+ def semantic_comparison(self, generated_result: Any, reference_result: Any) -> Dict[str, Any]:
+ reference_result_dict = self.output_schema(**reference_result).dict()
+
+ # Check if generated result and reference result are actually equal
+ if are_content_equal(generated_result, reference_result_dict):
+ return {
+ "are_semantically_equivalent": True,
+ "differences": [],
+ "explanation": "The generated result and reference result are exactly equal."
+ }
+
+ response_schemas = [
+ ResponseSchema(name="are_semantically_equivalent", description="Boolean indicating if the results are semantically equivalent"),
+ ResponseSchema(name="differences", description="List of semantic differences between the results, if any"),
+ ResponseSchema(name="explanation", description="Detailed explanation of the comparison and reasoning")
+ ]
+ output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
+
+ template = """
+ Compare the Generated Result with the Reference Result and determine if they are semantically equivalent:
+
+ Generated Result:
+ {generated_result}
+
+ Reference Result (Correct Output):
+ {reference_result}
+
+ Analyze the content, structure, and meaning of both results. They should be considered semantically equivalent if they convey the same information, even if the exact wording or structure differs.
+ If they are not semantically equivalent, identify what are the key differences in the Generated Result. The Reference Result should be considered the correct output, you need to pinpoint the problems in the Generated Result.
+
+ {format_instructions}
+
+ Human: Are the generated result and reference result semantically equivalent? If not, what are the key differences?
+
+ Assistant: Let's analyze the two results carefully:
+
+ """
+
+ prompt = PromptTemplate(
+ template=template,
+ input_variables=["generated_result", "reference_result"],
+ partial_variables={"format_instructions": output_parser.get_format_instructions()}
+ )
+
+ chain = prompt | self.llm_model | output_parser
+ return chain.invoke({
+ "generated_result": json.dumps(generated_result, indent=2),
+ "reference_result": json.dumps(reference_result_dict, indent=2)
+ })
+
+ def semantic_focused_analysis(self, state: dict, comparison_result: Dict[str, Any]) -> str:
+ template = """
+ The current code's output is semantically different from the reference answer. Here are the details:
+
+ Current Code:
+ ```python
+ {generated_code}
+ ```
+
+ Semantic Differences:
+ {differences}
+
+ Comparison Explanation:
+ {explanation}
+
+ Please analyze these semantic differences and suggest how to modify the code to produce a result that is semantically equivalent to the reference answer. Focus on addressing the key differences while maintaining the overall structure and functionality of the code.
+
+ Provide your analysis and suggestions for fixing the semantic differences. DO NOT generate any code in your response.
+ """
+
+ prompt = PromptTemplate(template=template, input_variables=["generated_code", "differences", "explanation"])
+ chain = prompt | self.llm_model | StrOutputParser()
+ return chain.invoke({
+ "generated_code": state["generated_code"],
+ "differences": json.dumps(comparison_result["differences"], indent=2),
+ "explanation": comparison_result["explanation"]
+ })
+
+ def semantic_focused_code_generation(self, state: dict, analysis: str) -> str:
+ template = """
+ Based on the following analysis of semantic differences, please generate the corrected code:
+
+ Semantic Analysis:
+ {analysis}
+
+ Original Code:
+ ```python
+ {generated_code}
+ ```
+
+ Generated Result:
+ {generated_result}
+
+ Reference Result:
+ {reference_result}
+
+ Generate the corrected code, applying the suggestions from the analysis to make the output semantically equivalent to the reference result. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
+ """
+
+ prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code", "generated_result", "reference_result"])
+ chain = prompt | self.llm_model | StrOutputParser()
+ return chain.invoke({
+ "analysis": analysis,
+ "generated_code": state["generated_code"],
+ "generated_result": json.dumps(state["execution_result"], indent=2),
+ "reference_result": json.dumps(state["reference_answer"], indent=2)
+ })
+
def syntax_check(self, code):
try:
ast.parse(code)
@@ -416,7 +551,7 @@ class GenerateCodeNode(BaseNode):
except SyntaxError as e:
return False, f"Syntax error: {str(e)}"
- def create_sandbox_and_execute(self, function_code, html_doc):
+ def create_sandbox_and_execute(self, function_code):
# Create a sandbox environment
sandbox_globals = {
'BeautifulSoup': BeautifulSoup,
@@ -439,7 +574,7 @@ class GenerateCodeNode(BaseNode):
raise NameError("Function 'extract_data' not found in the generated code.")
# Execute the extract_data function with the provided HTML
- result = extract_data(html_doc)
+ result = extract_data(self.raw_html)
return True, result
except Exception as e:
@@ -464,4 +599,35 @@ class GenerateCodeNode(BaseNode):
match = re.search(pattern, code, re.DOTALL)
# If a code block is found, return the code, otherwise return the entire string
- return match.group(1) if match else code
\ No newline at end of file
+ return match.group(1) if match else code
+
+def normalize_string(s: str) -> str:
+ # Convert to lowercase, remove extra spaces, and strip punctuation
+ return ''.join(c for c in s.lower().strip() if c not in string.punctuation)
+
+def normalize_dict(d: dict) -> dict:
+ """
+ Normalize the dictionary by:
+ - Converting all string values to lowercase and stripping spaces.
+ - Recursively normalizing nested dictionaries.
+ - Sorting the dictionary to ensure key order doesn't matter.
+ """
+ normalized = {}
+ for key, value in d.items():
+ if isinstance(value, str):
+ # Normalize string values
+ normalized[key] = normalize_string(value)
+ elif isinstance(value, dict):
+ # Recursively normalize nested dictionaries
+ normalized[key] = normalize_dict(value)
+ elif isinstance(value, list):
+ # Sort lists and normalize elements
+ normalized[key] = sorted(normalize_dict(v) if isinstance(v, dict) else normalize_string(v) if isinstance(v, str) else v for v in value)
+ else:
+ # Keep other types (e.g., numbers) as is
+ normalized[key] = value
+ return dict(sorted(normalized.items())) # Ensure dictionary is sorted by keys
+
+def are_content_equal(generated_result: dict, reference_result: dict) -> bool:
+ # Normalize both dictionaries and compare
+ return normalize_dict(generated_result) == normalize_dict(reference_result)
\ No newline at end of file