Skip to content

Python scraper based on AI

refactoring of code, add example on the readme

VinciGit001afb950751bd
diff --git a/README.md b/README.md
index adcb92c0..b250c9fc 100644
--- a/README.md
+++ b/README.md
@@ -49,20 +49,31 @@ You can use the `SmartScraper` class to extract information from a website using
The `SmartScraper` class is a direct graph implementation that uses the most common nodes present in a web scraping pipeline. For more information, please see the [documentation](https://scrapegraph-ai.readthedocs.io/en/latest/).
```python
-from scrapegraphai.graphs import SmartScraper
-
-OPENAI_API_KEY = "YOUR_API_KEY"
-
-llm_config = {
- "api_key": OPENAI_API_KEY,
- "model_name": "gpt-3.5-turbo",
+import os
+from dotenv import load_dotenv
+from scrapegraphai.graphs import SmartScraperGraph
+
+load_dotenv()
+openai_key = os.getenv("OPENAI_APIKEY")
+
+# Define the configuration for the graph
+graph_config = {
+ "llm": {
+ "api_key": openai_key,
+ "model": "gpt-3.5-turbo",
+ },
}
-smart_scraper = SmartScraper("List me all the titles and project descriptions",
- "https://perinim.github.io/projects/", llm_config)
+# Create the SmartScraperGraph instance
+smart_scraper_graph = SmartScraperGraph(
+ prompt="List me all the titles and project descriptions"
+ file_source="https://perinim.github.io/projects/", # also accepts a local file path
+ config=graph_config
+)
+
+result = smart_scraper_graph.run()
+print(result)
-answer = smart_scraper.run()
-print(answer)
```
The output will be a dictionary with the extracted information, for example:
diff --git a/deploy_on_pip.sh b/deploy_on_pip.sh
new file mode 100755
index 00000000..0060fc98
--- /dev/null
+++ b/deploy_on_pip.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+# Install dependencies using Poetry
+poetry install
+
+# Check for any potential issues in the project
+poetry check
+
+# Build the project
+poetry build
+
+# Publish the project to PyPI
+poetry publish
diff --git a/examples/graph_examples/custom_graph_gemini.py b/examples/graph_examples/custom_graph_gemini.py
index ec2627c2..581d186d 100644
--- a/examples/graph_examples/custom_graph_gemini.py
+++ b/examples/graph_examples/custom_graph_gemini.py
@@ -27,21 +27,21 @@ llm_model = Gemini(graph_config["llm"])
fetch_node = FetchNode(
input="url | local_dir",
output=["doc"],
- )
+)
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
- )
+)
rag_node = RAGNode(
input="user_prompt & (parsed_doc | doc)",
output=["relevant_chunks"],
model_config={"llm_model": llm_model},
- )
+)
generate_answer_node = GenerateAnswerNode(
input="user_prompt & (relevant_chunks | parsed_doc | doc)",
output=["answer"],
model_config={"llm_model": llm_model},
- )
+)
# create the graph by defining the nodes and their connections
graph = BaseGraph(
@@ -63,7 +63,7 @@ graph = BaseGraph(
result = graph.execute({
"user_prompt": "List me the projects with their description",
"url": "https://perinim.github.io/projects/"
- })
+})
# get the answer from the result
result = result.get("answer", "No answer found.")
diff --git a/examples/graph_examples/custom_graph_openai.py b/examples/graph_examples/custom_graph_openai.py
index 8a051c5f..6c86ecde 100644
--- a/examples/graph_examples/custom_graph_openai.py
+++ b/examples/graph_examples/custom_graph_openai.py
@@ -27,21 +27,21 @@ llm_model = OpenAI(graph_config["llm"])
fetch_node = FetchNode(
input="url | local_dir",
output=["doc"],
- )
+)
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
- )
+)
rag_node = RAGNode(
input="user_prompt & (parsed_doc | doc)",
output=["relevant_chunks"],
model_config={"llm_model": llm_model},
- )
+)
generate_answer_node = GenerateAnswerNode(
input="user_prompt & (relevant_chunks | parsed_doc | doc)",
output=["answer"],
model_config={"llm_model": llm_model},
- )
+)
# create the graph by defining the nodes and their connections
graph = BaseGraph(
@@ -63,7 +63,7 @@ graph = BaseGraph(
result = graph.execute({
"user_prompt": "List me the projects with their description",
"url": "https://perinim.github.io/projects/"
- })
+})
# get the answer from the result
result = result.get("answer", "No answer found.")
diff --git a/examples/graph_examples/smart_scraper_example.py b/examples/graph_examples/smart_scraper_example.py
index da0507aa..414e16ab 100644
--- a/examples/graph_examples/smart_scraper_example.py
+++ b/examples/graph_examples/smart_scraper_example.py
@@ -19,9 +19,9 @@ graph_config = {
# Create the SmartScraperGraph instance
smart_scraper_graph = SmartScraperGraph(
- prompt = "List me all the news with their description.",
- file_source = "https://www.ansa.it/veneto/", # also accepts a local file path
- config = graph_config
+ prompt="List me all the news with their description.",
+ file_source="https://www.ansa.it/veneto/", # also accepts a local file path
+ config=graph_config
)
result = smart_scraper_graph.run()
diff --git a/examples/graph_examples/speech_graph_example.py b/examples/graph_examples/speech_graph_example.py
index 7e571fe3..7afac269 100644
--- a/examples/graph_examples/speech_graph_example.py
+++ b/examples/graph_examples/speech_graph_example.py
@@ -10,9 +10,9 @@ load_dotenv()
openai_key = os.getenv("OPENAI_APIKEY")
# Save the audio to a file
-file_name = "website_summary.mp3"
+FILE_NAME = "website_summary.mp3"
curr_dir = os.path.dirname(os.path.realpath(__file__))
-output_path = os.path.join(curr_dir, file_name)
+output_path = os.path.join(curr_dir, FILE_NAME)
# Define the configuration for the graph
graph_config = {
@@ -29,9 +29,9 @@ graph_config = {
}
speech_graph = SpeechGraph(
- prompt = "Create a summary of the website",
- file_source = "https://perinim.github.io/projects/",
- config = graph_config,
+ prompt="Create a summary of the website",
+ file_source="https://perinim.github.io/projects/",
+ config=graph_config,
)
result = speech_graph.run()
diff --git a/pyproject.toml b/pyproject.toml
index c6b131e6..ec306ecb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "scrapegraphai"
-version = "0.0.9"
+version = "0.0.10"
description = "A web scraping library based on LangChain which uses LLM and direct graph logic to create scraping pipelines."
authors = [
"Marco Vinciguerra <[email protected]>",
diff --git a/scrapegraphai/builders/graph_builder.py b/scrapegraphai/builders/graph_builder.py
index 6b6e5c02..56576b4b 100644
--- a/scrapegraphai/builders/graph_builder.py
+++ b/scrapegraphai/builders/graph_builder.py
@@ -67,7 +67,7 @@ class GraphBuilder:
llm_params = {**llm_defaults, **llm_config}
if "api_key" not in llm_params:
raise ValueError("LLM configuration must include an 'api_key'.")
-
+
# select the model based on the model name
if "gpt-" in llm_params["model"]:
return OpenAI(llm_params)
diff --git a/scrapegraphai/evaluators/trulens_evaluator.py b/scrapegraphai/evaluators/trulens_evaluator.py
index 6dc875a5..d6011a95 100644
--- a/scrapegraphai/evaluators/trulens_evaluator.py
+++ b/scrapegraphai/evaluators/trulens_evaluator.py
@@ -52,10 +52,10 @@ class TrulensEvaluator:
output = SmartScraperGraph(*params).run()
self.tru_llm_standalone_recorder.app(params[0], output)
self.graph_output.append(output)
-
+
if dashboard:
self.tru.run_dashboard()
-
+
return (self.tru.get_records_and_feedback(app_ids=[])[0], self.graph_output)
def llm_standalone(self, prompt, response):
diff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.py
index 1dfad54a..d9943ee1 100644
--- a/scrapegraphai/graphs/smart_scraper_graph.py
+++ b/scrapegraphai/graphs/smart_scraper_graph.py
@@ -8,7 +8,8 @@ from ..nodes import (
ParseNode,
RAGNode,
GenerateAnswerNode
- )
+)
+
class SmartScraperGraph:
"""
@@ -83,21 +84,21 @@ class SmartScraperGraph:
fetch_node = FetchNode(
input="url | local_dir",
output=["doc"],
- )
+ )
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
- )
+ )
rag_node = RAGNode(
input="user_prompt & (parsed_doc | doc)",
output=["relevant_chunks"],
model_config={"llm_model": self.llm_model},
- )
+ )
generate_answer_node = GenerateAnswerNode(
input="user_prompt & (relevant_chunks | parsed_doc | doc)",
output=["answer"],
model_config={"llm_model": self.llm_model},
- )
+ )
return BaseGraph(
nodes={
@@ -122,7 +123,6 @@ class SmartScraperGraph:
str: The answer extracted from the web page, corresponding to the given 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.py
index 6275ccce..1e70e01d 100644
--- a/scrapegraphai/graphs/speech_graph.py
+++ b/scrapegraphai/graphs/speech_graph.py
@@ -85,21 +85,21 @@ class SpeechGraph:
fetch_node = FetchNode(
input="url | local_dir",
output=["doc"],
- )
+ )
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
- )
+ )
rag_node = RAGNode(
input="user_prompt & (parsed_doc | doc)",
output=["relevant_chunks"],
model_config={"llm_model": self.llm_model},
- )
+ )
generate_answer_node = GenerateAnswerNode(
input="user_prompt & (relevant_chunks | parsed_doc | doc)",
output=["answer"],
model_config={"llm_model": self.llm_model},
- )
+ )
text_to_speech_node = TextToSpeechNode(
input="answer",
output=["audio"],
diff --git a/scrapegraphai/nodes/base_node.py b/scrapegraphai/nodes/base_node.py
index f2f1001b..e9766588 100644
--- a/scrapegraphai/nodes/base_node.py
+++ b/scrapegraphai/nodes/base_node.py
@@ -5,6 +5,7 @@ from abc import ABC, abstractmethod
from typing import Optional, List
import re
+
class BaseNode(ABC):
"""
An abstract base class for nodes in a graph-based workflow. Each node is
@@ -78,12 +79,13 @@ class BaseNode(ABC):
self._validate_input_keys(input_keys)
return input_keys
except ValueError as e:
- raise ValueError(f"Error parsing input keys for {self.node_name}: {str(e)}")
+ raise ValueError(
+ f"Error parsing input keys for {self.node_name}: {str(e)}")
-
def _validate_input_keys(self, input_keys):
if len(input_keys) < self.min_input_len:
- raise ValueError(f"{self.node_name} requires at least {self.min_input_len} input keys, got {len(input_keys)}.")
+ raise ValueError(
+ f"{self.node_name} requires at least {self.min_input_len} input keys, got {len(input_keys)}.")
def _parse_input_keys(self, state: dict, expression: str) -> List[str]:
"""
@@ -102,17 +104,22 @@ class BaseNode(ABC):
raise ValueError("Empty expression.")
# Check for adjacent state keys without an operator between them
- pattern = r'\b(' + '|'.join(re.escape(key) for key in state.keys()) + r')(\b\s*\b)(' + '|'.join(re.escape(key) for key in state.keys()) + r')\b'
+ pattern = r'\b(' + '|'.join(re.escape(key) for key in state.keys()) + \
+ r')(\b\s*\b)(' + '|'.join(re.escape(key)
+ for key in state.keys()) + r')\b'
if re.search(pattern, expression):
- raise ValueError("Adjacent state keys found without an operator between them.")
+ raise ValueError(
+ "Adjacent state keys found without an operator between them.")
# Remove spaces
expression = expression.replace(" ", "")
-
+
# Check for operators with empty adjacent tokens or at the start/end
- if expression[0] in '&|' or expression[-1] in '&|' or '&&' in expression or '||' in expression or '&|' in expression or '|&' in expression:
+ if expression[0] in '&|' or expression[-1] in '&|' \
+ or '&&' in expression or '||' in expression or \
+ '&|' in expression or '|&' in expression:
raise ValueError("Invalid operator usage.")
-
+
# Check for balanced parentheses and valid operator placement
open_parentheses = close_parentheses = 0
for i, char in enumerate(expression):
@@ -122,11 +129,13 @@ class BaseNode(ABC):
close_parentheses += 1
# Check for invalid operator sequences
if char in "&|" and i + 1 < len(expression) and expression[i + 1] in "&|":
- raise ValueError("Invalid operator placement: operators cannot be adjacent.")
-
+ raise ValueError(
+ "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.")
+ raise ValueError(
+ "Missing or unbalanced parentheses in expression.")
# Helper function to evaluate an expression without parentheses
def evaluate_simple_expression(exp):
@@ -147,11 +156,12 @@ class BaseNode(ABC):
# 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:]
+ expression = expression[:start] + \
+ '|'.join(sub_result) + expression[end+1:]
return evaluate_simple_expression(expression)
result = evaluate_expression(expression)
-
+
if not result:
raise ValueError("No state keys matched the expression.")
@@ -161,4 +171,4 @@ class BaseNode(ABC):
if key not in final_result:
final_result.append(key)
- return final_result
\ No newline at end of file
+ return final_result
diff --git a/scrapegraphai/nodes/fetch_node.py b/scrapegraphai/nodes/fetch_node.py
index 8cad7186..e761c200 100644
--- a/scrapegraphai/nodes/fetch_node.py
+++ b/scrapegraphai/nodes/fetch_node.py
@@ -2,10 +2,11 @@
Module for fetching the HTML node
"""
+from typing import List
from langchain_community.document_loaders import AsyncHtmlLoader
from langchain_core.documents import Document
from .base_node import BaseNode
-from typing import List
+
class FetchNode(BaseNode):
"""
@@ -59,10 +60,10 @@ class FetchNode(BaseNode):
necessary information to perform the operation is missing.
"""
print(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]
@@ -74,7 +75,7 @@ class FetchNode(BaseNode):
document = Document(page_content=file_content, metadata={
"source": source
})
-
+
# if it is a URL
else:
loader = AsyncHtmlLoader(source)
diff --git a/scrapegraphai/nodes/generate_answer_node.py b/scrapegraphai/nodes/generate_answer_node.py
index 2caabe82..9a400d56 100644
--- a/scrapegraphai/nodes/generate_answer_node.py
+++ b/scrapegraphai/nodes/generate_answer_node.py
@@ -2,6 +2,7 @@
Module for generating the answer node
"""
# Imports from standard library
+from typing import List
from tqdm import tqdm
# Imports from Langchain
@@ -11,7 +12,7 @@ from langchain_core.runnables import RunnableParallel
# Imports from the library
from .base_node import BaseNode
-from typing import List
+
class GenerateAnswerNode(BaseNode):
"""
@@ -38,7 +39,8 @@ class GenerateAnswerNode(BaseNode):
updating the state with the generated answer under the 'answer' key.
"""
- def __init__(self, input: str, output: List[str], model_config: dict, node_name: str = "GenerateAnswer"):
+ def __init__(self, input: str, output: List[str], model_config: dict,
+ node_name: str = "GenerateAnswer"):
"""
Initializes the GenerateAnswerNode with a language model client and a node name.
Args:
@@ -68,10 +70,10 @@ class GenerateAnswerNode(BaseNode):
"""
print(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]
@@ -127,4 +129,4 @@ class GenerateAnswerNode(BaseNode):
# Update the state with the generated answer
state.update({self.output[0]: answer})
- return state
\ No newline at end of file
+ return state
diff --git a/scrapegraphai/nodes/get_probable_tags_node.py b/scrapegraphai/nodes/get_probable_tags_node.py
index 66b3d37b..a5391a28 100644
--- a/scrapegraphai/nodes/get_probable_tags_node.py
+++ b/scrapegraphai/nodes/get_probable_tags_node.py
@@ -1,10 +1,11 @@
"""
Module for proobable tags
"""
+from typing import List
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain.prompts import PromptTemplate
from .base_node import BaseNode
-from typing import List
+
class GetProbableTagsNode(BaseNode):
"""
@@ -29,7 +30,8 @@ class GetProbableTagsNode(BaseNode):
probable HTML tags, updating the state with these tags under the 'tags' key.
"""
- def __init__(self, input: str, output: List[str], model_config: dict, node_name: str = "GetProbableTags"):
+ def __init__(self, input: str, output: List[str], model_config: dict,
+ node_name: str = "GetProbableTags"):
"""
Initializes the GetProbableTagsNode with a language model client and a node name.
Args:
@@ -58,10 +60,10 @@ class GetProbableTagsNode(BaseNode):
"""
print(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]
diff --git a/scrapegraphai/nodes/parse_node.py b/scrapegraphai/nodes/parse_node.py
index e2b417dc..866487d8 100644
--- a/scrapegraphai/nodes/parse_node.py
+++ b/scrapegraphai/nodes/parse_node.py
@@ -1,10 +1,10 @@
"""
Module for parsing the HTML node
"""
+from typing import List
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_transformers import Html2TextTransformer
from .base_node import BaseNode
-from typing import List
class ParseNode(BaseNode):
@@ -61,13 +61,13 @@ class ParseNode(BaseNode):
"""
print(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]
-
+
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=4000,
chunk_overlap=0,
@@ -77,8 +77,6 @@ class ParseNode(BaseNode):
docs_transformed = Html2TextTransformer(
).transform_documents(input_data[0])[0]
- # TODO: keep the metadata
-
chunks = text_splitter.split_text(docs_transformed.page_content)
state.update({self.output[0]: chunks})
diff --git a/scrapegraphai/nodes/rag_node.py b/scrapegraphai/nodes/rag_node.py
index 9432d0b5..1bb648a6 100644
--- a/scrapegraphai/nodes/rag_node.py
+++ b/scrapegraphai/nodes/rag_node.py
@@ -2,16 +2,16 @@
Module for parsing the HTML node
"""
+from typing import List
from langchain.docstore.document import Document
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import EmbeddingsFilter, DocumentCompressorPipeline
from langchain_community.document_transformers import EmbeddingsRedundantFilter
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
-from typing import List
-
from .base_node import BaseNode
+
class RAGNode(BaseNode):
"""
A node responsible for compressing the input tokens and storing the document
@@ -56,10 +56,10 @@ class RAGNode(BaseNode):
"""
print(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]
@@ -90,7 +90,6 @@ class RAGNode(BaseNode):
pipeline_compressor = DocumentCompressorPipeline(
transformers=[redundant_filter, relevant_filter]
)
-
# redundant + relevant filter compressor
compression_retriever = ContextualCompressionRetriever(
base_compressor=pipeline_compressor, base_retriever=retriever
@@ -103,8 +102,8 @@ class RAGNode(BaseNode):
compressed_docs = compression_retriever.get_relevant_documents(
user_prompt)
-
+
print("--- (tokens compressed and vector stored) ---")
-
+
state.update({self.output[0]: compressed_docs})
return state
diff --git a/scrapegraphai/nodes/text_to_speech_node.py b/scrapegraphai/nodes/text_to_speech_node.py
index 978548f4..a9250842 100644
--- a/scrapegraphai/nodes/text_to_speech_node.py
+++ b/scrapegraphai/nodes/text_to_speech_node.py
@@ -2,9 +2,9 @@
"""
Module for parsing the text to voice
"""
-
-from .base_node import BaseNode
from typing import List
+from .base_node import BaseNode
+
class TextToSpeechNode(BaseNode):
"""
@@ -17,7 +17,8 @@ class TextToSpeechNode(BaseNode):
execute(state, text): Execute the node's logic and return the updated state.
"""
- def __init__(self, input: str, output: List[str], model_config: dict, node_name: str = "TextToSpeech"):
+ def __init__(self, input: str, output: List[str],
+ model_config: dict, node_name: str = "TextToSpeech"):
"""
Initializes an instance of the TextToSpeechNode class.
"""
@@ -35,17 +36,17 @@ class TextToSpeechNode(BaseNode):
"""
print(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]
# get the text to translate
text2translate = str(next(iter(input_data[0].values())))
# text2translate = str(input_data[0])
-
+
audio = self.tts_model.run(text2translate)
state.update({self.output[0]: audio})
diff --git a/scrapegraphai/utils/parse_state_keys.py b/scrapegraphai/utils/parse_state_keys.py
index 097ad825..c5da7e8a 100644
--- a/scrapegraphai/utils/parse_state_keys.py
+++ b/scrapegraphai/utils/parse_state_keys.py
@@ -1,22 +1,35 @@
+"""
+Parse_state_key module
+"""
import re
-def parse_expression(expression, state):
+
+def parse_expression(expression, state: dict):
+ """
+ Function for parsing the expressions
+ """
# Check for empty expression
if not expression:
raise ValueError("Empty expression.")
# Check for adjacent state keys without an operator between them
- pattern = r'\b(' + '|'.join(re.escape(key) for key in state.keys()) + r')(\b\s*\b)(' + '|'.join(re.escape(key) for key in state.keys()) + r')\b'
+ pattern = r'\b(' + '|'.join(re.escape(key) for key in state.keys()) + \
+ r')(\b\s*\b)(' + '|'.join(re.escape(key)
+ for key in state.keys()) + r')\b'
if re.search(pattern, expression):
- raise ValueError("Adjacent state keys found without an operator between them.")
+ raise ValueError(
+ "Adjacent state keys found without an operator between them.")
# Remove spaces
expression = expression.replace(" ", "")
-
+
# Check for operators with empty adjacent tokens or at the start/end
- if expression[0] in '&|' or expression[-1] in '&|' or '&&' in expression or '||' in expression or '&|' in expression or '|&' in expression:
+ if expression[0] in '&|' or expression[-1] in '&|' or \
+ '&&' in expression or '||' in expression or \
+ '&|' in expression or '|&' in expression:
+
raise ValueError("Invalid operator usage.")
-
+
# Check for balanced parentheses and valid operator placement
open_parentheses = close_parentheses = 0
for i, char in enumerate(expression):
@@ -26,8 +39,9 @@ def parse_expression(expression, state):
close_parentheses += 1
# Check for invalid operator sequences
if char in "&|" and i + 1 < len(expression) and expression[i + 1] in "&|":
- raise ValueError("Invalid operator placement: operators cannot be adjacent.")
-
+ raise ValueError(
+ "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.")
@@ -51,11 +65,12 @@ def parse_expression(expression, state):
# 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:]
+ expression = expression[:start] + \
+ '|'.join(sub_result) + expression[end+1:]
return evaluate_simple_expression(expression)
result = evaluate_expression(expression)
-
+
if not result:
raise ValueError("No state keys matched the expression.")
@@ -67,7 +82,8 @@ def parse_expression(expression, state):
return final_result
-expression = "user_input & (relevant_chunks | parsed_document | document)"
+
+EXPRESSION = "user_input & (relevant_chunks | parsed_document | document)"
state = {
"user_input": None,
"document": None,
@@ -76,7 +92,7 @@ state = {
}
try:
- result = parse_expression(expression, state)
+ result = parse_expression(EXPRESSION, state)
print("Matched keys:", result)
except ValueError as e:
print("Error:", e)
diff --git a/scrapegraphai/utils/test_node.py b/scrapegraphai/utils/test_node.py
index fb6fcd82..4abf744c 100644
--- a/scrapegraphai/utils/test_node.py
+++ b/scrapegraphai/utils/test_node.py
@@ -1,7 +1,11 @@
-from scrapegraphai.nodes import FetchNode, ParseNode, RAGNode, GenerateAnswerNode
+"""
+Module for making the tests
+"""
import os
from dotenv import load_dotenv
from scrapegraphai.models import OpenAI
+from scrapegraphai.nodes import FetchNode, ParseNode, RAGNode, GenerateAnswerNode
+
load_dotenv()
# Define the configuration for the language model
@@ -24,14 +28,14 @@ fetch_node = FetchNode(
input="url | local_dir",
output=["doc"],
node_name="fetch_html"
- )
+)
updated_state = fetch_node.execute(state)
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
node_name="parse_document"
- )
+)
updated_state = parse_node.execute(updated_state)
@@ -40,7 +44,7 @@ rag_node = RAGNode(
output=["relevant_chunks"],
model_config={"llm_model": llm_model},
node_name="rag_node"
- )
+)
updated_state = rag_node.execute(updated_state)
@@ -49,6 +53,6 @@ generate_answer_node = GenerateAnswerNode(
output=["answer"],
model_config={"llm_model": llm_model},
node_name="generate_answer"
- )
+)
-print(generate_answer_node.execute(updated_state))
\ No newline at end of file
+print(generate_answer_node.execute(updated_state))