scrapegraphai 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scrapegraphai/__init__.py +3 -0
- scrapegraphai/graphs/__init__.py +5 -0
- scrapegraphai/graphs/base_graph.py +76 -0
- scrapegraphai/graphs/smart_scraper_graph.py +107 -0
- scrapegraphai/info/dictionaries.py +40 -0
- scrapegraphai/nodes/__init__.py +8 -0
- scrapegraphai/nodes/base_node.py +66 -0
- scrapegraphai/nodes/conditional_node.py +68 -0
- scrapegraphai/nodes/fetch_html_node.py +67 -0
- scrapegraphai/nodes/generate_answer_node.py +100 -0
- scrapegraphai/nodes/get_probable_tags_node.py +88 -0
- scrapegraphai/nodes/parse_html_node.py +74 -0
- scrapegraphai/utils/convert_to_csv.py +36 -0
- scrapegraphai/utils/convert_to_json.py +36 -0
- scrapegraphai/utils/getter.py +18 -0
- scrapegraphai/utils/remover.py +40 -0
- scrapegraphai/utils/token_calculator.py +31 -0
- scrapegraphai-0.0.1.dist-info/LICENSE +201 -0
- scrapegraphai-0.0.1.dist-info/METADATA +133 -0
- scrapegraphai-0.0.1.dist-info/RECORD +21 -0
- scrapegraphai-0.0.1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for creating the base graphs
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BaseGraph:
|
|
7
|
+
"""
|
|
8
|
+
BaseGraph manages the execution flow of a graph composed of interconnected nodes.
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
nodes (dict): A dictionary mapping each node's name to its corresponding node instance.
|
|
12
|
+
edges (dict): A dictionary representing the directed edges of the graph where each
|
|
13
|
+
key-value pair corresponds to the from-node and to-node relationship.
|
|
14
|
+
entry_point (str): The name of the entry point node from which the graph execution begins.
|
|
15
|
+
|
|
16
|
+
Methods:
|
|
17
|
+
execute(initial_state): Executes the graph's nodes starting from the entry point and
|
|
18
|
+
traverses the graph based on the provided initial state.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
nodes (iterable): An iterable of node instances that will be part of the graph.
|
|
22
|
+
edges (iterable): An iterable of tuples where each tuple represents a directed edge
|
|
23
|
+
in the graph, defined by a pair of nodes (from_node, to_node).
|
|
24
|
+
entry_point (BaseNode): The node instance that represents the entry point of the graph.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, nodes: dict, edges: dict, entry_point: str):
|
|
28
|
+
"""
|
|
29
|
+
Initializes the graph with nodes, edges, and the entry point.
|
|
30
|
+
"""
|
|
31
|
+
self.nodes = {node.node_name: node for node in nodes}
|
|
32
|
+
self.edges = self._create_edges(edges)
|
|
33
|
+
self.entry_point = entry_point.node_name
|
|
34
|
+
|
|
35
|
+
def _create_edges(self, edges: dict) -> dict:
|
|
36
|
+
"""
|
|
37
|
+
Helper method to create a dictionary of edges from the given iterable of tuples.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
edges (iterable): An iterable of tuples representing the directed edges.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
dict: A dictionary of edges with the from-node as keys and to-node as values.
|
|
44
|
+
"""
|
|
45
|
+
edge_dict = {}
|
|
46
|
+
for from_node, to_node in edges:
|
|
47
|
+
edge_dict[from_node.node_name] = to_node.node_name
|
|
48
|
+
return edge_dict
|
|
49
|
+
|
|
50
|
+
def execute(self, initial_state: dict) -> dict:
|
|
51
|
+
"""
|
|
52
|
+
Executes the graph by traversing nodes starting from the entry point. The execution
|
|
53
|
+
follows the edges based on the result of each node's execution and continues until
|
|
54
|
+
it reaches a node with no outgoing edges.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
initial_state (dict): The initial state to pass to the entry point node.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
dict: The state after execution has completed, which may have been altered by the nodes.
|
|
61
|
+
"""
|
|
62
|
+
current_node_name = self.entry_point
|
|
63
|
+
state = initial_state
|
|
64
|
+
|
|
65
|
+
while current_node_name is not None:
|
|
66
|
+
current_node = self.nodes[current_node_name]
|
|
67
|
+
result = current_node.execute(state)
|
|
68
|
+
|
|
69
|
+
if current_node.node_type == "conditional_node":
|
|
70
|
+
current_node_name = result
|
|
71
|
+
elif current_node_name in self.edges:
|
|
72
|
+
current_node_name = self.edges[current_node_name]
|
|
73
|
+
else:
|
|
74
|
+
current_node_name = None
|
|
75
|
+
|
|
76
|
+
return state
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for creating the smart scaper
|
|
3
|
+
"""
|
|
4
|
+
from langchain_openai import ChatOpenAI
|
|
5
|
+
from .base_graph import BaseGraph
|
|
6
|
+
from ..nodes import FetchHTMLNode, ConditionalNode, GetProbableTagsNode
|
|
7
|
+
from ..nodes import GenerateAnswerNode, ParseHTMLNode
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SmartScraper:
|
|
11
|
+
"""
|
|
12
|
+
SmartScraper is a comprehensive web scraping tool that automates the process of extracting
|
|
13
|
+
information from web pages using a natural language model to interpret and answer prompts.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
prompt (str): The user's natural language prompt for the information to be extracted.
|
|
17
|
+
url (str): The URL of the web page to scrape.
|
|
18
|
+
llm_config (dict): Configuration parameters for the language model, with
|
|
19
|
+
'api_key' being mandatory.
|
|
20
|
+
llm (ChatOpenAI): An instance of the ChatOpenAI class configured with llm_config.
|
|
21
|
+
graph (BaseGraph): An instance of the BaseGraph class representing the scraping workflow.
|
|
22
|
+
|
|
23
|
+
Methods:
|
|
24
|
+
run(): Executes the web scraping process and returns the answer to the prompt.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
prompt (str): The user's natural language prompt for the information to be extracted.
|
|
28
|
+
url (str): The URL of the web page to scrape.
|
|
29
|
+
llm_config (dict): A dictionary containing configuration options for the language model.
|
|
30
|
+
Must include 'api_key', may also specify 'model_name',
|
|
31
|
+
'temperature', and 'streaming'.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, prompt: str, url: str, llm_config: dict):
|
|
35
|
+
"""
|
|
36
|
+
Initializes the SmartScraper with a prompt, URL, and language model configuration.
|
|
37
|
+
"""
|
|
38
|
+
self.prompt = prompt
|
|
39
|
+
self.url = url
|
|
40
|
+
self.llm_config = llm_config
|
|
41
|
+
self.llm = self._create_llm()
|
|
42
|
+
self.graph = self._create_graph()
|
|
43
|
+
|
|
44
|
+
def _create_llm(self):
|
|
45
|
+
"""
|
|
46
|
+
Creates an instance of the ChatOpenAI class with the provided language model configuration.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
ChatOpenAI: An instance of the ChatOpenAI class.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
ValueError: If 'api_key' is not provided in llm_config.
|
|
53
|
+
"""
|
|
54
|
+
llm_defaults = {
|
|
55
|
+
"model_name": "gpt-3.5-turbo",
|
|
56
|
+
"temperature": 0,
|
|
57
|
+
"streaming": True
|
|
58
|
+
}
|
|
59
|
+
# Update defaults with any LLM parameters that were provided
|
|
60
|
+
llm_params = {**llm_defaults, **self.llm_config}
|
|
61
|
+
# Ensure the api_key is set, raise an error if it's not
|
|
62
|
+
if "api_key" not in llm_params:
|
|
63
|
+
raise ValueError("LLM configuration must include an 'api_key'.")
|
|
64
|
+
# Create the ChatOpenAI instance with the provided and default parameters
|
|
65
|
+
return ChatOpenAI(**llm_params)
|
|
66
|
+
|
|
67
|
+
def _create_graph(self):
|
|
68
|
+
"""
|
|
69
|
+
Creates the graph of nodes representing the workflow for web scraping.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
BaseGraph: An instance of the BaseGraph class.
|
|
73
|
+
"""
|
|
74
|
+
fetch_html_node = FetchHTMLNode("fetch_html")
|
|
75
|
+
get_probable_tags_node = GetProbableTagsNode(
|
|
76
|
+
self.llm, "get_probable_tags")
|
|
77
|
+
parse_document_node = ParseHTMLNode("parse_document")
|
|
78
|
+
generate_answer_node = GenerateAnswerNode(self.llm, "generate_answer")
|
|
79
|
+
conditional_node = ConditionalNode(
|
|
80
|
+
"conditional", [parse_document_node, generate_answer_node])
|
|
81
|
+
|
|
82
|
+
return BaseGraph(
|
|
83
|
+
nodes={
|
|
84
|
+
fetch_html_node,
|
|
85
|
+
get_probable_tags_node,
|
|
86
|
+
conditional_node,
|
|
87
|
+
parse_document_node,
|
|
88
|
+
generate_answer_node,
|
|
89
|
+
},
|
|
90
|
+
edges={
|
|
91
|
+
(fetch_html_node, get_probable_tags_node),
|
|
92
|
+
(get_probable_tags_node, conditional_node),
|
|
93
|
+
(parse_document_node, generate_answer_node)
|
|
94
|
+
},
|
|
95
|
+
entry_point=fetch_html_node
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
def run(self) -> str:
|
|
99
|
+
"""
|
|
100
|
+
Executes the scraping process by running the graph and returns the extracted information.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
str: The answer extracted from the web page, corresponding to the given prompt.
|
|
104
|
+
"""
|
|
105
|
+
inputs = {"keys": {"user_input": self.prompt, "url": self.url}}
|
|
106
|
+
final_state = self.graph.execute(inputs)
|
|
107
|
+
return final_state["keys"].get("answer", "No answer found.")
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for defining dictionaries and token limits
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
schema_example = {
|
|
6
|
+
"properties": {
|
|
7
|
+
"person_name": {"type": "string"},
|
|
8
|
+
"person_surname": {"type": "string"},
|
|
9
|
+
"profession": {"type": "string"},
|
|
10
|
+
"hobbies": {"type": "string"},
|
|
11
|
+
"projects": {
|
|
12
|
+
"type": "array",
|
|
13
|
+
"items": {
|
|
14
|
+
"type": "object",
|
|
15
|
+
"properties": {
|
|
16
|
+
"project_name": {"type": "string"},
|
|
17
|
+
"project_description": {"type": "string"},
|
|
18
|
+
"url": {"type": "string"}
|
|
19
|
+
},
|
|
20
|
+
"required": ["project_name", "project_description", "url"],
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
"required": ["person_name", "person_surname", "profession", "hobbies", "projects"],
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
models_tokens = {
|
|
28
|
+
"gpt-3.5-turbo-0125": 16385,
|
|
29
|
+
"gpt-3.5-turbo": 4096,
|
|
30
|
+
"gpt-3.5-turbo-1106": 16385,
|
|
31
|
+
"gpt-3.5-turbo-instruct": 4096,
|
|
32
|
+
"gpt-4-0125-preview": 128000,
|
|
33
|
+
"gpt-4-turbo-preview": 128000,
|
|
34
|
+
"gpt-4-1106-preview": 128000,
|
|
35
|
+
"gpt-4-vision-preview": 128000,
|
|
36
|
+
"gpt-4": 8192,
|
|
37
|
+
"gpt-4-0613": 8192,
|
|
38
|
+
"gpt-4-32k": 32768,
|
|
39
|
+
"gpt-4-32k-0613": 32768,
|
|
40
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""
|
|
2
|
+
__init__.py file for node folder
|
|
3
|
+
"""
|
|
4
|
+
from .fetch_html_node import FetchHTMLNode
|
|
5
|
+
from .conditional_node import ConditionalNode
|
|
6
|
+
from .get_probable_tags_node import GetProbableTagsNode
|
|
7
|
+
from .generate_answer_node import GenerateAnswerNode
|
|
8
|
+
from .parse_html_node import ParseHTMLNode
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for creating the basic node
|
|
3
|
+
"""
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class BaseNode(ABC):
|
|
8
|
+
"""
|
|
9
|
+
An abstract base class for nodes in a graph-based workflow. Each node is
|
|
10
|
+
intended to perform a specific action when executed as part of the graph's
|
|
11
|
+
processing flow.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
node_name (str): A unique identifier for the node.
|
|
15
|
+
node_type (str): Specifies the node's type, which influences how the
|
|
16
|
+
node interacts within the graph. Valid values are
|
|
17
|
+
"node" for standard nodes and "conditional_node" for
|
|
18
|
+
nodes that determine the flow based on conditions.
|
|
19
|
+
|
|
20
|
+
Methods:
|
|
21
|
+
execute(state): An abstract method that subclasses must implement. This
|
|
22
|
+
method should contain the logic that the node executes
|
|
23
|
+
when it is reached in the graph's flow. It takes the
|
|
24
|
+
graph's current state as input and returns the updated
|
|
25
|
+
state after execution.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
node_name (str): The unique identifier name for the node. This name is
|
|
29
|
+
used to reference the node within the graph.
|
|
30
|
+
node_type (str): The type of the node, limited to "node" or
|
|
31
|
+
"conditional_node". This categorization helps in
|
|
32
|
+
determining the node's role and behavior within the
|
|
33
|
+
graph.
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
ValueError: If the provided `node_type` is not one of the allowed
|
|
37
|
+
values ("node" or "conditional_node"), a ValueError is
|
|
38
|
+
raised to indicate the incorrect usage.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, node_name: str, node_type: str):
|
|
42
|
+
"""
|
|
43
|
+
Initialize the node with a unique identifier and a specified node type.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
node_name (str): The unique identifier name for the node.
|
|
47
|
+
node_type (str): The type of the node, limited to "node" or "conditional_node".
|
|
48
|
+
|
|
49
|
+
Raises:
|
|
50
|
+
ValueError: If node_type is not "node" or "conditional_node".
|
|
51
|
+
"""
|
|
52
|
+
self.node_name = node_name
|
|
53
|
+
if node_type not in ["node", "conditional_node"]:
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f"node_type must be 'node' or 'conditional_node', got '{node_type}'")
|
|
56
|
+
self.node_type = node_type
|
|
57
|
+
|
|
58
|
+
@abstractmethod
|
|
59
|
+
def execute(self, state: dict):
|
|
60
|
+
"""
|
|
61
|
+
Execute the node's logic and return the updated state.
|
|
62
|
+
Args:
|
|
63
|
+
state (dict): The current state of the graph.
|
|
64
|
+
:return: The updated state after executing this node.
|
|
65
|
+
"""
|
|
66
|
+
pass
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for implementing the conditional node
|
|
3
|
+
"""
|
|
4
|
+
from .base_node import BaseNode
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ConditionalNode(BaseNode):
|
|
8
|
+
"""
|
|
9
|
+
A node that determines the next step in the graph's execution flow based on
|
|
10
|
+
the presence and content of a specified key in the graph's state. It extends
|
|
11
|
+
the BaseNode by adding condition-based logic to the execution process.
|
|
12
|
+
|
|
13
|
+
This node type is used to implement branching logic within the graph, allowing
|
|
14
|
+
for dynamic paths based on the data available in the current state.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
key_name (str): The name of the key in the state to check for its presence.
|
|
18
|
+
next_nodes (list): A list of two node instances. The first node is chosen
|
|
19
|
+
for execution if the key exists and has a non-empty value,
|
|
20
|
+
and the second node is chosen if the key does not exist or
|
|
21
|
+
is empty.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
key_name (str): The name of the key to check in the graph's state. This is
|
|
25
|
+
used to determine the path the graph's execution should take.
|
|
26
|
+
next_nodes (list): A list containing exactly two node instances, specifying
|
|
27
|
+
the next nodes to execute based on the condition's outcome.
|
|
28
|
+
node_name (str, optional): The unique identifier name for the node. Defaults
|
|
29
|
+
to "ConditionalNode".
|
|
30
|
+
|
|
31
|
+
Raises:
|
|
32
|
+
ValueError: If next_nodes does not contain exactly two elements, indicating
|
|
33
|
+
a misconfiguration in specifying the conditional paths.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, key_name: str, next_nodes: list, node_name="ConditionalNode"):
|
|
37
|
+
"""
|
|
38
|
+
Initializes the node with the key to check and the next node names based on the condition.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
key_name (str): The name of the key to check in the state.
|
|
42
|
+
next_nodes (list): A list containing exactly two names of the next nodes.
|
|
43
|
+
The first is used if the key exists, the second if it does not.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
ValueError: If next_nodes does not contain exactly two elements.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
super().__init__(node_name, "conditional_node")
|
|
50
|
+
self.key_name = key_name
|
|
51
|
+
if len(next_nodes) != 2:
|
|
52
|
+
raise ValueError("next_nodes must contain exactly two elements.")
|
|
53
|
+
self.next_nodes = next_nodes
|
|
54
|
+
|
|
55
|
+
def execute(self, state: dict) -> str:
|
|
56
|
+
"""
|
|
57
|
+
Checks if the specified key is present in the state and decides the next node accordingly.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
state (dict): The current state of the graph.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
str: The name of the next node to execute based on the presence of the key.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
if self.key_name in state.get("keys", {}) and len(state["keys"][self.key_name]) > 0:
|
|
67
|
+
return self.next_nodes[0].node_name
|
|
68
|
+
return self.next_nodes[1].node_name
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for fetching the HTML node
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from langchain_community.document_loaders import AsyncHtmlLoader
|
|
6
|
+
from .base_node import BaseNode
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FetchHTMLNode(BaseNode):
|
|
10
|
+
"""
|
|
11
|
+
A node responsible for fetching the HTML content of a specified URL and updating
|
|
12
|
+
the graph's state with this content. It uses the AsyncHtmlLoader for asynchronous
|
|
13
|
+
document loading.
|
|
14
|
+
|
|
15
|
+
This node acts as a starting point in many scraping workflows, preparing the state
|
|
16
|
+
with the necessary HTML content for further processing by subsequent nodes in the graph.
|
|
17
|
+
|
|
18
|
+
Attributes:
|
|
19
|
+
node_name (str): The unique identifier name for the node.
|
|
20
|
+
node_type (str): The type of the node, defaulting to "node". This categorization
|
|
21
|
+
helps in determining the node's role and behavior within the graph.
|
|
22
|
+
The "node" type is used for standard operational nodes.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
node_name (str): The unique identifier name for the node. This name is used to
|
|
26
|
+
reference the node within the graph.
|
|
27
|
+
node_type (str, optional): The type of the node, limited to "node" or
|
|
28
|
+
"conditional_node". Defaults to "node".
|
|
29
|
+
|
|
30
|
+
Methods:
|
|
31
|
+
execute(state): Fetches the HTML content for the URL specified in the state and
|
|
32
|
+
updates the state with this content under the 'document' key.
|
|
33
|
+
The 'url' key must be present in the state for the operation
|
|
34
|
+
to succeed.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, node_name: str, node_type: str = "node"):
|
|
38
|
+
"""
|
|
39
|
+
Initializes the FetchHTMLNode with a node name and node type.
|
|
40
|
+
"""
|
|
41
|
+
super().__init__(node_name, node_type)
|
|
42
|
+
|
|
43
|
+
def execute(self, state: dict) -> dict:
|
|
44
|
+
"""
|
|
45
|
+
Executes the node's logic to fetch HTML content from a specified URL and
|
|
46
|
+
update the state with this content.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
state (dict): The current state of the graph, expected to contain a 'url' key.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
dict: The updated state with a new 'document' key containing the fetched HTML content.
|
|
53
|
+
|
|
54
|
+
Raises:
|
|
55
|
+
KeyError: If the 'url' key is not found in the state, indicating that the
|
|
56
|
+
necessary information to perform the operation is missing.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
url = state["keys"]["url"]
|
|
60
|
+
except KeyError as e:
|
|
61
|
+
print(f"Error: {e} not found in state.")
|
|
62
|
+
raise
|
|
63
|
+
loader = AsyncHtmlLoader(url)
|
|
64
|
+
document = loader.load()
|
|
65
|
+
state["keys"]["document"] = document
|
|
66
|
+
|
|
67
|
+
return state
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for generating the answer node
|
|
3
|
+
"""
|
|
4
|
+
from langchain_core.output_parsers import JsonOutputParser
|
|
5
|
+
from langchain.prompts import PromptTemplate
|
|
6
|
+
from .base_node import BaseNode
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class GenerateAnswerNode(BaseNode):
|
|
10
|
+
"""
|
|
11
|
+
A node that generates an answer using a language model (LLM) based on the user's input
|
|
12
|
+
and the content extracted from a webpage. It constructs a prompt from the user's input
|
|
13
|
+
and the scraped content, feeds it to the LLM, and parses the LLM's response to produce
|
|
14
|
+
an answer.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
llm (ChatOpenAI): An instance of a language model client, configured for generating answers.
|
|
18
|
+
node_name (str): The unique identifier name for the node, defaulting
|
|
19
|
+
to "GenerateAnswerNode".
|
|
20
|
+
node_type (str): The type of the node, set to "node" indicating a
|
|
21
|
+
standard operational node.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
llm: An instance of the language model client (e.g., ChatOpenAI) used
|
|
25
|
+
for generating answers.
|
|
26
|
+
node_name (str, optional): The unique identifier name for the node.
|
|
27
|
+
Defaults to "GenerateAnswerNode".
|
|
28
|
+
|
|
29
|
+
Methods:
|
|
30
|
+
execute(state): Processes the input and document from the state to generate an answer,
|
|
31
|
+
updating the state with the generated answer under the 'answer' key.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, llm, node_name: str = "GenerateAnswerNode"):
|
|
35
|
+
"""
|
|
36
|
+
Initializes the GenerateAnswerNode with a language model client and a node name.
|
|
37
|
+
"""
|
|
38
|
+
super().__init__(node_name, "node")
|
|
39
|
+
self.llm = llm
|
|
40
|
+
|
|
41
|
+
def execute(self, state: dict) -> dict:
|
|
42
|
+
"""
|
|
43
|
+
Generates an answer by constructing a prompt from the user's input and the scraped
|
|
44
|
+
content, querying the language model, and parsing its response.
|
|
45
|
+
|
|
46
|
+
The method updates the state with the generated answer under the 'answer' key.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
state (dict): The current state of the graph, expected to contain 'user_input',
|
|
50
|
+
and optionally 'parsed_document' or 'relevant_chunks' within 'keys'.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
dict: The updated state with the 'answer' key containing the generated answer.
|
|
54
|
+
|
|
55
|
+
Raises:
|
|
56
|
+
KeyError: If 'user_input' or 'document' is not found in the state, indicating
|
|
57
|
+
that the necessary information for generating an answer is missing.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
print("---GENERATE ANSWER---")
|
|
61
|
+
try:
|
|
62
|
+
user_input = state["keys"]["user_input"]
|
|
63
|
+
document = state["keys"]["document"]
|
|
64
|
+
except KeyError as e:
|
|
65
|
+
print(f"Error: {e} not found in state.")
|
|
66
|
+
raise
|
|
67
|
+
|
|
68
|
+
parsed_document = state["keys"].get("parsed_document", None)
|
|
69
|
+
relevant_chunks = state["keys"].get("relevant_chunks", None)
|
|
70
|
+
|
|
71
|
+
if relevant_chunks:
|
|
72
|
+
context = relevant_chunks
|
|
73
|
+
elif parsed_document:
|
|
74
|
+
context = parsed_document
|
|
75
|
+
else:
|
|
76
|
+
context = document
|
|
77
|
+
|
|
78
|
+
output_parser = JsonOutputParser()
|
|
79
|
+
format_instructions = output_parser.get_format_instructions()
|
|
80
|
+
|
|
81
|
+
template = """You are a website scraper and you have just scraped the
|
|
82
|
+
following content from a website.
|
|
83
|
+
You are now asked to answer a question about the content you have scraped.\n {format_instructions} \n The content is as follows: {context}
|
|
84
|
+
Question: {question}
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
schema_prompt = PromptTemplate(
|
|
88
|
+
template=template,
|
|
89
|
+
input_variables=["context", "question"],
|
|
90
|
+
partial_variables={"format_instructions": format_instructions},
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Chain
|
|
94
|
+
schema_chain = schema_prompt | self.llm | output_parser
|
|
95
|
+
answer = schema_chain.invoke(
|
|
96
|
+
{"context": context, "question": user_input})
|
|
97
|
+
|
|
98
|
+
# Update the state with the generated answer
|
|
99
|
+
state["keys"].update({"answer": answer})
|
|
100
|
+
return state
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for proobable tags
|
|
3
|
+
"""
|
|
4
|
+
from langchain.output_parsers import CommaSeparatedListOutputParser
|
|
5
|
+
from langchain.prompts import PromptTemplate
|
|
6
|
+
from .base_node import BaseNode
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class GetProbableTagsNode(BaseNode):
|
|
10
|
+
"""
|
|
11
|
+
A node that utilizes a language model to identify probable HTML tags within a document that
|
|
12
|
+
are likely to contain the information relevant to a user's query. This node generates a prompt
|
|
13
|
+
describing the task, submits it to the language model, and processes the output to produce a
|
|
14
|
+
list of probable tags.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
llm: An instance of a language model client, configured for generating tag predictions.
|
|
18
|
+
node_name (str): The unique identifier name for the node,
|
|
19
|
+
defaulting to "GetProbableTagsNode".
|
|
20
|
+
node_type (str): The type of the node, set to "node" indicating a standard operational node.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
llm: An instance of the language model client (e.g., ChatOpenAI) used for tag predictions.
|
|
24
|
+
node_name (str, optional): The unique identifier name for the node.
|
|
25
|
+
Defaults to "GetProbableTagsNode".
|
|
26
|
+
|
|
27
|
+
Methods:
|
|
28
|
+
execute(state): Processes the user's input and the URL from the state to generate a list of
|
|
29
|
+
probable HTML tags, updating the state with these tags under the 'tags' key.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, llm, node_name: str = "GetProbableTagsNode"):
|
|
33
|
+
"""
|
|
34
|
+
Initializes the GetProbableTagsNode with a language model client and a node name.
|
|
35
|
+
"""
|
|
36
|
+
super().__init__(node_name, "node")
|
|
37
|
+
self.llm = llm
|
|
38
|
+
|
|
39
|
+
def execute(self, state: dict):
|
|
40
|
+
"""
|
|
41
|
+
Generates a list of probable HTML tags based on the user's input and updates the state
|
|
42
|
+
with this list. The method constructs a prompt for the language model, submits it, and
|
|
43
|
+
parses the output to identify probable tags.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
state (dict): The current state of the graph, expected to contain 'user_input', 'url',
|
|
47
|
+
and optionally 'document' within 'keys'.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
dict: The updated state with the 'tags' key containing a list of probable HTML tags.
|
|
51
|
+
|
|
52
|
+
Raises:
|
|
53
|
+
KeyError: If 'user_input' or 'url' is not found in the state, indicating that the
|
|
54
|
+
necessary information for generating tag predictions is missing.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
print("---GET PROBABLE TAGS---")
|
|
58
|
+
try:
|
|
59
|
+
user_input = state["keys"]["user_input"]
|
|
60
|
+
url = state["keys"]["url"]
|
|
61
|
+
except KeyError as e:
|
|
62
|
+
print(f"Error: {e} not found in state.")
|
|
63
|
+
raise
|
|
64
|
+
|
|
65
|
+
output_parser = CommaSeparatedListOutputParser()
|
|
66
|
+
format_instructions = output_parser.get_format_instructions()
|
|
67
|
+
|
|
68
|
+
template = """You are a website scraper that knows all the types of html tags.
|
|
69
|
+
You are now asked to list all the html tags where you think you can find the information of the asked question.\n
|
|
70
|
+
{format_instructions} \n The webpage is: {webpage} \n The asked question is the following: {question}
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
tag_prompt = PromptTemplate(
|
|
74
|
+
template=template,
|
|
75
|
+
input_variables=["question"],
|
|
76
|
+
partial_variables={
|
|
77
|
+
"format_instructions": format_instructions, "webpage": url},
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
# Execute the chain to get probable tags
|
|
81
|
+
tag_answer = tag_prompt | self.llm | output_parser
|
|
82
|
+
probable_tags = tag_answer.invoke({"question": user_input})
|
|
83
|
+
|
|
84
|
+
print("Possible tags: ", *probable_tags)
|
|
85
|
+
|
|
86
|
+
# Update the nested 'keys' dictionary with probable tags
|
|
87
|
+
state["keys"].update({"tags": probable_tags})
|
|
88
|
+
return state
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for parsing the HTML node
|
|
3
|
+
"""
|
|
4
|
+
from langchain_community.document_transformers import BeautifulSoupTransformer
|
|
5
|
+
from .base_node import BaseNode
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ParseHTMLNode(BaseNode):
|
|
9
|
+
"""
|
|
10
|
+
A node responsible for parsing HTML content from a document using specified tags.
|
|
11
|
+
It uses BeautifulSoupTransformer for parsing, providing flexibility in extracting
|
|
12
|
+
specific parts of an HTML document based on the tags provided in the state.
|
|
13
|
+
|
|
14
|
+
This node enhances the scraping workflow by allowing for targeted extraction of
|
|
15
|
+
content, thereby optimizing the processing of large HTML documents.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
node_name (str): The unique identifier name for the node, defaulting to "ParseHTMLNode".
|
|
19
|
+
node_type (str): The type of the node, set to "node" indicating a standard operational node.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
node_name (str, optional): The unique identifier name for the node.
|
|
23
|
+
Defaults to "ParseHTMLNode".
|
|
24
|
+
|
|
25
|
+
Methods:
|
|
26
|
+
execute(state): Parses the HTML document contained within the state using
|
|
27
|
+
the specified tags, if provided, and updates the state with the parsed content.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, node_name="ParseHTMLNode"):
|
|
31
|
+
"""
|
|
32
|
+
Initializes the ParseHTMLNode with a node name.
|
|
33
|
+
"""
|
|
34
|
+
super().__init__(node_name, "node")
|
|
35
|
+
|
|
36
|
+
def execute(self, state):
|
|
37
|
+
"""
|
|
38
|
+
Executes the node's logic to parse the HTML document based on specified tags.
|
|
39
|
+
If tags are provided in the state, the document is parsed accordingly; otherwise,
|
|
40
|
+
the document remains unchanged. The method updates the state with either the original
|
|
41
|
+
or parsed document under the 'parsed_document' key.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
state (dict): The current state of the graph, expected to contain
|
|
45
|
+
'document' within 'keys', and optionally 'tags' for targeted parsing.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
dict: The updated state with the 'parsed_document' key containing the parsed content,
|
|
49
|
+
if tags were provided, or the original document otherwise.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
KeyError: If 'document' is not found in the state, indicating that the necessary
|
|
53
|
+
information for parsing is missing.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
print("---PARSE HTML DOCUMENT---")
|
|
57
|
+
try:
|
|
58
|
+
document = state["keys"]["document"]
|
|
59
|
+
except KeyError as e:
|
|
60
|
+
print(f"Error: {e} not found in state.")
|
|
61
|
+
raise
|
|
62
|
+
|
|
63
|
+
tags = state["keys"].get("tags", None)
|
|
64
|
+
|
|
65
|
+
if not tags:
|
|
66
|
+
print("No specific tags provided; returning document as is.")
|
|
67
|
+
return state
|
|
68
|
+
|
|
69
|
+
bs_transformer = BeautifulSoupTransformer()
|
|
70
|
+
parsed_document = bs_transformer.transform_documents(
|
|
71
|
+
document, tags_to_extract=tags)
|
|
72
|
+
print("Document parsed with specified tags.")
|
|
73
|
+
state["keys"].update({"parsed_document": parsed_document})
|
|
74
|
+
return state
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module that given a filename and a position saves the file in the csv format
|
|
3
|
+
"""
|
|
4
|
+
import os
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def convert_to_csv(data: dict, filename: str, position: str):
|
|
9
|
+
"""
|
|
10
|
+
Convert data to JSON format and save it to a file.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
data (dict): Data to save.
|
|
14
|
+
filename (str): Name of the file to save without .csv extension.
|
|
15
|
+
position (str): Directory where the file should be saved.
|
|
16
|
+
|
|
17
|
+
Raises:
|
|
18
|
+
ValueError: If filename contains '.csv'.
|
|
19
|
+
FileNotFoundError: If the specified directory does not exist.
|
|
20
|
+
PermissionError: If the program does not have permission to write to the directory.
|
|
21
|
+
"""
|
|
22
|
+
if ".csv" in filename:
|
|
23
|
+
raise ValueError("The filename should not contain '.csv'")
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
os.makedirs(position, exist_ok=True)
|
|
27
|
+
pd.DataFrame.from_dict(data, orient='index').to_csv(
|
|
28
|
+
os.path.join(position, f"{filename}.csv"), index=False)
|
|
29
|
+
except FileNotFoundError as fnfe:
|
|
30
|
+
raise FileNotFoundError(
|
|
31
|
+
f"The specified directory '{position}' does not exist.") from fnfe
|
|
32
|
+
except PermissionError as pe:
|
|
33
|
+
raise PermissionError(
|
|
34
|
+
f"You don't have permission to write to '{position}'.") from pe
|
|
35
|
+
except Exception as e:
|
|
36
|
+
raise e
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module that given a filename and a position saves the file in the json format
|
|
3
|
+
"""
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def convert_to_json(data: dict, filename: str, position: str):
|
|
9
|
+
"""
|
|
10
|
+
Convert data to CSV format and save it to a file.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
data (dict): Data to save.
|
|
14
|
+
filename (str): Name of the file to save without .json extension.
|
|
15
|
+
position (str): Directory where the file should be saved.
|
|
16
|
+
|
|
17
|
+
Raises:
|
|
18
|
+
ValueError: If filename contains '.json'.
|
|
19
|
+
FileNotFoundError: If the specified directory does not exist.
|
|
20
|
+
PermissionError: If the program does not have permission to write to the directory.
|
|
21
|
+
"""
|
|
22
|
+
if ".json" in filename:
|
|
23
|
+
raise ValueError("The filename should not contain '.json'")
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
os.makedirs(position, exist_ok=True)
|
|
27
|
+
with open(os.path.join(position, f"{filename}.json"), "w", encoding="utf-8") as f:
|
|
28
|
+
f.write(json.dumps(data))
|
|
29
|
+
except FileNotFoundError as fnfe:
|
|
30
|
+
raise FileNotFoundError(
|
|
31
|
+
f"The specified directory '{position}' does not exist.") from fnfe
|
|
32
|
+
except PermissionError as pe:
|
|
33
|
+
raise PermissionError(
|
|
34
|
+
f"You don't have permission to write to '{position}'.") from pe
|
|
35
|
+
except Exception as e:
|
|
36
|
+
raise e
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for retrieving content from a URL
|
|
3
|
+
"""
|
|
4
|
+
from langchain_community.document_loaders import AsyncHtmlLoader
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _get_function(link: str) -> str:
|
|
8
|
+
"""
|
|
9
|
+
It sends a GET request to the specified link with optional headers.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
link (str): The URL to send the GET request to.
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
str: The content of the response as a string.
|
|
16
|
+
"""
|
|
17
|
+
loader = AsyncHtmlLoader(link)
|
|
18
|
+
return str(loader.load())
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for removing the unused html tags
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def remover(file: str, only_body: bool = False) -> str:
|
|
7
|
+
"""
|
|
8
|
+
This function elaborates the HTML file and remove all the not necessary tag
|
|
9
|
+
|
|
10
|
+
Parameters:
|
|
11
|
+
file (str): the file to parse
|
|
12
|
+
|
|
13
|
+
Returns:
|
|
14
|
+
str: the parsed file
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
res = ""
|
|
18
|
+
|
|
19
|
+
if only_body:
|
|
20
|
+
is_body = True
|
|
21
|
+
else:
|
|
22
|
+
is_body = False
|
|
23
|
+
|
|
24
|
+
for elem in file.splitlines():
|
|
25
|
+
if "<title>" in elem:
|
|
26
|
+
res = res + elem
|
|
27
|
+
|
|
28
|
+
if "<body>" in elem:
|
|
29
|
+
is_body = True
|
|
30
|
+
|
|
31
|
+
if "</body>" in elem:
|
|
32
|
+
break
|
|
33
|
+
|
|
34
|
+
if "<script>" in elem:
|
|
35
|
+
continue
|
|
36
|
+
|
|
37
|
+
if is_body:
|
|
38
|
+
res = res + elem
|
|
39
|
+
|
|
40
|
+
return res.replace("\\n", "")
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module for truncatinh in chunks the messages
|
|
3
|
+
"""
|
|
4
|
+
from typing import List
|
|
5
|
+
import tiktoken
|
|
6
|
+
from .info.dictionaries import models_tokens
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def truncate_text_tokens(text: str, model: str, encoding_name: str) -> List[str]:
|
|
10
|
+
"""
|
|
11
|
+
It creates a list of strings to create max dimension tokenizable elements
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
text (str): The input text to be truncated into tokenizable elements.
|
|
15
|
+
model (str): The name of the language model to be used.
|
|
16
|
+
encoding_name (str): The name of the encoding to be used (default: EMBEDDING_ENCODING).
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
List[str]: A list of tokenizable elements created from the input text.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
encoding = tiktoken.get_encoding(encoding_name)
|
|
23
|
+
max_tokens = models_tokens[model] - 500
|
|
24
|
+
encoded_text = encoding.encode(text)
|
|
25
|
+
|
|
26
|
+
chunks = [encoded_text[i:i + max_tokens]
|
|
27
|
+
for i in range(0, len(encoded_text), max_tokens)]
|
|
28
|
+
|
|
29
|
+
result = [encoding.decode(chunk) for chunk in chunks]
|
|
30
|
+
|
|
31
|
+
return result
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 Marco Vinciguerra
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: scrapegraphai
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: A web scraping library based on LangChain which uses LLM and direct graph logic to create scraping pipelines.
|
|
5
|
+
Home-page: https://scrapegraph-ai.readthedocs.io/
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: langchain,ai,artificial intelligence,gpt,machine learning,rag,nlp,natural language processing,openai,scraping,web scraping,web scraping library,web scraping tool,webscraping,graph,scrapegraph
|
|
8
|
+
Author: Marco Vinciguerra
|
|
9
|
+
Author-email: mvincig11@gmail.com
|
|
10
|
+
Requires-Python: >=3.9,<4.0
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Dist: beautifulsoup4 (==4.12.3)
|
|
21
|
+
Requires-Dist: langchain (==0.1.6)
|
|
22
|
+
Requires-Dist: langchain_community (==0.0.19)
|
|
23
|
+
Requires-Dist: langchain_core (==0.1.22)
|
|
24
|
+
Requires-Dist: langchain_openai (==0.0.5)
|
|
25
|
+
Requires-Dist: pandas (==2.0.3)
|
|
26
|
+
Requires-Dist: python-dotenv (==1.0.1)
|
|
27
|
+
Requires-Dist: tiktoken (>=0.5.2,<0.6.0)
|
|
28
|
+
Requires-Dist: tqdm (==4.66.1)
|
|
29
|
+
Project-URL: Documentation, https://scrapegraph-doc.onrender.com/
|
|
30
|
+
Project-URL: Repository, https://github.com/VinciGit00/Scrapegraph-ai
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# 🕷️ ScrapeGraphAI: You Only Scrape Once
|
|
34
|
+
|
|
35
|
+
ScrapeGraphAI is a *web scraping* python library based on LangChain which uses LLM and direct graph logic to create scraping pipelines.
|
|
36
|
+
Just say which information you want to extract and the library will do it for you!
|
|
37
|
+
|
|
38
|
+
<p align="center">
|
|
39
|
+
<img src="docs/assets/scrapegraphai_logo.png" alt="Scrapegraph-ai Logo" style="width: 50%;">
|
|
40
|
+
</p>
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
## 🚀 Quick install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install scrapegraphai
|
|
47
|
+
```
|
|
48
|
+
## 🔍 Demo
|
|
49
|
+
|
|
50
|
+
Try out ScrapeGraphAI in your browser:
|
|
51
|
+
|
|
52
|
+
[](https://codespaces.new/VinciGit00/Scrapegraph-ai)
|
|
53
|
+
|
|
54
|
+
## 📖 Documentation
|
|
55
|
+
|
|
56
|
+
The documentation for ScrapeGraphAI can be found [here](https://scrapegraph-ai.readthedocs.io/en/latest/).
|
|
57
|
+
Behind this there is also the docusaurus documentation [here]([https://scrapegraph-ai.readthedocs.io/en/latest/](https://scrapegraph-doc.onrender.com/)).
|
|
58
|
+
|
|
59
|
+
## Setup the api keys
|
|
60
|
+
|
|
61
|
+
The procedure per for activatating the openai keys are in the following link: [link](https://scrapegraph-ai.readthedocs.io/en/latest/index.html).
|
|
62
|
+
|
|
63
|
+
## 💻 Usage
|
|
64
|
+
|
|
65
|
+
### Case 1: Extracting information using a prompt
|
|
66
|
+
|
|
67
|
+
You can use the `SmartScraper` class to extract information from a website using a prompt.
|
|
68
|
+
|
|
69
|
+
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/).
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from scrapegraphai.graphs import SmartScraper
|
|
73
|
+
|
|
74
|
+
OPENAI_API_KEY = "YOUR_API_KEY"
|
|
75
|
+
|
|
76
|
+
llm_config = {
|
|
77
|
+
"api_key": OPENAI_API_KEY,
|
|
78
|
+
"model_name": "gpt-3.5-turbo",
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
smart_scraper = SmartScraper("List me all the titles and project descriptions",
|
|
82
|
+
"https://perinim.github.io/projects/", llm_config)
|
|
83
|
+
|
|
84
|
+
answer = smart_scraper.run()
|
|
85
|
+
print(answer)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The output will be a dictionary with the extracted information, for example:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
{
|
|
92
|
+
'titles': [
|
|
93
|
+
'Rotary Pendulum RL'
|
|
94
|
+
],
|
|
95
|
+
'descriptions': [
|
|
96
|
+
'Open Source project aimed at controlling a real life rotary pendulum using RL algorithms'
|
|
97
|
+
]
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## 🤝 Contributing
|
|
102
|
+
|
|
103
|
+
Contributions are welcome! Please check out the todos below, and feel free to open a pull request.
|
|
104
|
+
For more information, please see the [contributing guidelines](CONTRIBUTING.md).
|
|
105
|
+
|
|
106
|
+
After installing and activating the virtual environment, please remember to install the library using the "dev" extra parameter to have the extra dependencies for development.
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
pip install -e .[dev]
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Contributors
|
|
113
|
+
|
|
114
|
+
[](https://github.com/VinciGit00/Scrapegraph-ai/graphs/contributors)
|
|
115
|
+
|
|
116
|
+
## Authors
|
|
117
|
+
|
|
118
|
+
<p align="center">
|
|
119
|
+
<img src="docs/assets/logo_authors.png" alt="Authors Logos"">
|
|
120
|
+
</p>
|
|
121
|
+
|
|
122
|
+
## 📜 License
|
|
123
|
+
|
|
124
|
+
ScrapeGraphAI is licensed under the Apache 2.0 License. See the [LICENSE](LICENSE) file for more information.
|
|
125
|
+
|
|
126
|
+
## Acknowledgements
|
|
127
|
+
|
|
128
|
+
- We would like to thank all the contributors to the project and the open-source community for their support.
|
|
129
|
+
- ScrapeGraphAI is meant to be used for data exploration and research purposes only. We are not responsible for any misuse of the library.
|
|
130
|
+
|
|
131
|
+
## Thanks to:
|
|
132
|
+
- [nicolapiazzalunga](https://github.com/nicolapiazzalunga) for having inspired us to the functions: scrapegraph/convert_to_json.py and scrapegraph/convert_to_csv.py
|
|
133
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
scrapegraphai/__init__.py,sha256=tdcyvY2aV8oK3-PzGgX5GN_ZtTA3Eg7EKWf-Rsv_8N0,57
|
|
2
|
+
scrapegraphai/graphs/__init__.py,sha256=YABWf6FCiDmGt__zr-oyJzJYkpBMr3oSWxIbSan9MKk,129
|
|
3
|
+
scrapegraphai/graphs/base_graph.py,sha256=9xIH04Xfgnn88cpCcO1ltrSwsGN_OOVnWpD7G6v16pA,3117
|
|
4
|
+
scrapegraphai/graphs/smart_scraper_graph.py,sha256=GQhntpolTwQn5ydBYJbtKbCm5wHtVxB0dEePh-ZVZIQ,4358
|
|
5
|
+
scrapegraphai/info/dictionaries.py,sha256=p17RcmLht6FjzGps3sBD7-ROQQ5UhmHhY50MbLSr69g,1216
|
|
6
|
+
scrapegraphai/nodes/__init__.py,sha256=awtwOn83YSlK5ZGiw0LplYPJAO3tUNSIi4UCdbkOn2k,292
|
|
7
|
+
scrapegraphai/nodes/base_node.py,sha256=rdVCCno-0Rp7t5TUqt8usRjyp_xeIeywxLmzBP7ggjo,2732
|
|
8
|
+
scrapegraphai/nodes/conditional_node.py,sha256=dnGSHm9SzJkOisCs9a80fTBPS8_rFG_UT4RVy9M4A0s,3006
|
|
9
|
+
scrapegraphai/nodes/fetch_html_node.py,sha256=8lhG25E9_KOmdR07HzBJUeApy1PcmPzXKWytkpx2v-A,2698
|
|
10
|
+
scrapegraphai/nodes/generate_answer_node.py,sha256=_aCkakZlO3kr6aETlb3GoCEoe8XBP21WXHv-y5U_av8,4002
|
|
11
|
+
scrapegraphai/nodes/get_probable_tags_node.py,sha256=Mkm6BrDCHB-1uvAGfpctIF7dXdRP-adBRKup_g4aMVM,3775
|
|
12
|
+
scrapegraphai/nodes/parse_html_node.py,sha256=dH0OXLk1G7GBdKqJp6HwFM5js6WOHPmLF_04Udgei8w,2990
|
|
13
|
+
scrapegraphai/utils/convert_to_csv.py,sha256=vn1PvKW3TaZexO0OsSVWcG39ucl3y7T_rQN0BzXH8W0,1307
|
|
14
|
+
scrapegraphai/utils/convert_to_json.py,sha256=o2M1yTdGyHfimKKY2mNSa05wqEb6g1YsfdFzqDm_QRA,1304
|
|
15
|
+
scrapegraphai/utils/getter.py,sha256=yufZ-jkPvGMpJKpKfLHyxX4osqcMzSRDhiaqA9tgqwY,459
|
|
16
|
+
scrapegraphai/utils/remover.py,sha256=FYjYciow-tMRHIvLV_3ebgCjCF2qwVJeWb2On6GCjqc,770
|
|
17
|
+
scrapegraphai/utils/token_calculator.py,sha256=Yep-MJ7nYsWZGWhrPn2aSJuH-KPB5NAP3y9XyhTIJOw,1016
|
|
18
|
+
scrapegraphai-0.0.1.dist-info/LICENSE,sha256=0e0T0fhnrfvsU9jAvrmSPCXQPFG3uxnb0T4az_WUz5s,11138
|
|
19
|
+
scrapegraphai-0.0.1.dist-info/METADATA,sha256=s3qwNz8g8NUq1bSmWoTgjr1p37Bbc2wzexdaGYMEV48,4914
|
|
20
|
+
scrapegraphai-0.0.1.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
|
|
21
|
+
scrapegraphai-0.0.1.dist-info/RECORD,,
|