scrapegraphai 0.0.1__tar.gz

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.
@@ -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
+ [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](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
+ [![Contributors](https://contrib.rocks/image?repo=VinciGit00/Scrapegraph-ai)](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,100 @@
1
+ # 🕷️ ScrapeGraphAI: You Only Scrape Once
2
+
3
+ ScrapeGraphAI is a *web scraping* python library based on LangChain which uses LLM and direct graph logic to create scraping pipelines.
4
+ Just say which information you want to extract and the library will do it for you!
5
+
6
+ <p align="center">
7
+ <img src="docs/assets/scrapegraphai_logo.png" alt="Scrapegraph-ai Logo" style="width: 50%;">
8
+ </p>
9
+
10
+
11
+ ## 🚀 Quick install
12
+
13
+ ```bash
14
+ pip install scrapegraphai
15
+ ```
16
+ ## 🔍 Demo
17
+
18
+ Try out ScrapeGraphAI in your browser:
19
+
20
+ [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/VinciGit00/Scrapegraph-ai)
21
+
22
+ ## 📖 Documentation
23
+
24
+ The documentation for ScrapeGraphAI can be found [here](https://scrapegraph-ai.readthedocs.io/en/latest/).
25
+ Behind this there is also the docusaurus documentation [here]([https://scrapegraph-ai.readthedocs.io/en/latest/](https://scrapegraph-doc.onrender.com/)).
26
+
27
+ ## Setup the api keys
28
+
29
+ The procedure per for activatating the openai keys are in the following link: [link](https://scrapegraph-ai.readthedocs.io/en/latest/index.html).
30
+
31
+ ## 💻 Usage
32
+
33
+ ### Case 1: Extracting information using a prompt
34
+
35
+ You can use the `SmartScraper` class to extract information from a website using a prompt.
36
+
37
+ 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/).
38
+
39
+ ```python
40
+ from scrapegraphai.graphs import SmartScraper
41
+
42
+ OPENAI_API_KEY = "YOUR_API_KEY"
43
+
44
+ llm_config = {
45
+ "api_key": OPENAI_API_KEY,
46
+ "model_name": "gpt-3.5-turbo",
47
+ }
48
+
49
+ smart_scraper = SmartScraper("List me all the titles and project descriptions",
50
+ "https://perinim.github.io/projects/", llm_config)
51
+
52
+ answer = smart_scraper.run()
53
+ print(answer)
54
+ ```
55
+
56
+ The output will be a dictionary with the extracted information, for example:
57
+
58
+ ```bash
59
+ {
60
+ 'titles': [
61
+ 'Rotary Pendulum RL'
62
+ ],
63
+ 'descriptions': [
64
+ 'Open Source project aimed at controlling a real life rotary pendulum using RL algorithms'
65
+ ]
66
+ }
67
+ ```
68
+
69
+ ## 🤝 Contributing
70
+
71
+ Contributions are welcome! Please check out the todos below, and feel free to open a pull request.
72
+ For more information, please see the [contributing guidelines](CONTRIBUTING.md).
73
+
74
+ 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.
75
+
76
+ ```bash
77
+ pip install -e .[dev]
78
+ ```
79
+
80
+ ## Contributors
81
+
82
+ [![Contributors](https://contrib.rocks/image?repo=VinciGit00/Scrapegraph-ai)](https://github.com/VinciGit00/Scrapegraph-ai/graphs/contributors)
83
+
84
+ ## Authors
85
+
86
+ <p align="center">
87
+ <img src="docs/assets/logo_authors.png" alt="Authors Logos"">
88
+ </p>
89
+
90
+ ## 📜 License
91
+
92
+ ScrapeGraphAI is licensed under the Apache 2.0 License. See the [LICENSE](LICENSE) file for more information.
93
+
94
+ ## Acknowledgements
95
+
96
+ - We would like to thank all the contributors to the project and the open-source community for their support.
97
+ - ScrapeGraphAI is meant to be used for data exploration and research purposes only. We are not responsible for any misuse of the library.
98
+
99
+ ## Thanks to:
100
+ - [nicolapiazzalunga](https://github.com/nicolapiazzalunga) for having inspired us to the functions: scrapegraph/convert_to_json.py and scrapegraph/convert_to_csv.py
@@ -0,0 +1,48 @@
1
+ [tool.poetry]
2
+ name = "scrapegraphai"
3
+ version = "0.0.1"
4
+ description = "A web scraping library based on LangChain which uses LLM and direct graph logic to create scraping pipelines."
5
+ authors = [
6
+ "Marco Vinciguerra <mvincig11@gmail.com>",
7
+ "Marco Perini <perinim.98@gmail.com>",
8
+ "Lorenzo Padoan <lorenzo.padoan977@gmail.com>"
9
+ ]
10
+ license = "MIT"
11
+ readme = "README.md"
12
+ homepage = "https://scrapegraph-ai.readthedocs.io/"
13
+ repository = "https://github.com/VinciGit00/Scrapegraph-ai"
14
+ documentation = "https://scrapegraph-doc.onrender.com/"
15
+ 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"]
16
+ classifiers = [
17
+ "Intended Audience :: Developers",
18
+ "Topic :: Software Development :: Libraries :: Python Modules",
19
+ "Programming Language :: Python :: 3",
20
+ "Operating System :: OS Independent",
21
+ ]
22
+
23
+ [tool.poetry.dependencies]
24
+ python = "^3.9"
25
+ langchain = "0.1.6"
26
+ langchain_community = "0.0.19"
27
+ langchain_core = "0.1.22"
28
+ langchain_openai = "0.0.5"
29
+ beautifulsoup4 = "4.12.3"
30
+ pandas = "2.0.3"
31
+ python-dotenv = "1.0.1"
32
+ tiktoken = {version = ">=0.5.2,<0.6.0"}
33
+ tqdm = "4.66.1"
34
+
35
+ [tool.poetry.dev-dependencies]
36
+ pytest = "8.0.0"
37
+
38
+ [tool.poetry.group.docs]
39
+ optional = true
40
+
41
+ [tool.poetry.group.docs.dependencies]
42
+ sphinx = "7.1.2"
43
+ sphinx-rtd-theme = "2.0.0"
44
+
45
+ [build-system]
46
+ requires = ["poetry-core>=1.0.0"]
47
+ build-backend = "poetry.core.masonry.api"
48
+
@@ -0,0 +1,3 @@
1
+ """
2
+ __init__.py file for scrapegraphai folder
3
+ """
@@ -0,0 +1,5 @@
1
+ """
2
+ __init__.py file for graphs folder
3
+ """
4
+ from .base_graph import BaseGraph
5
+ from .smart_scraper_graph import SmartScraper
@@ -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.")