webshaker 0.0.1

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: bb805fb1517334406d00c9d9fb55510dff22c70bb8a83423fcd3befcaa62e4dd
4
+ data.tar.gz: e6f746ab29119f1c72a06f63aaced60cef06615c103768b072001d595d31646a
5
+ SHA512:
6
+ metadata.gz: e275d2788b214596062e56e6fc218853c414dc83d6938c4d4d60a188db23f6a6138a97a80c91de9aa53113101c051ca976c19148f8d9fad8388ff0afc191ffe7
7
+ data.tar.gz: 6ea99e1174a443bcdbf60011f7171be02b7dda8ef7e33ac559999c723cfeb235a4a6e232d16a7598883c1954b9fa82aff05a655f60a5dbe64f603f49e82a922e
data/.env.sample ADDED
@@ -0,0 +1,2 @@
1
+ WEBSHAKER_OPEN_AI_KEY=<your_open_ai_key>
2
+ WEBSHAKER_OPEN_AI_MODEL=<the_model_you_want_to_use | optional>
data/.env.test ADDED
@@ -0,0 +1,2 @@
1
+ WEBSHAKER_OPEN_AI_KEY=fake_key
2
+ WEBSHAKER_OPEN_AI_MODEL=gpt-4o-mini
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.2
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
3
+ ruby_version: 3.2.2
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at martin.mochetti@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in revolut-connect.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.2"
9
+
10
+ group :development, :test do
11
+ gem "byebug", "~> 11.1"
12
+ gem "pry", "~> 0.14.2"
13
+ gem "pry-byebug", "~> 3.10"
14
+ gem "pry-rescue", "~> 1.5"
15
+ gem "dotenv"
16
+ gem "pry-stack_explorer", "~> 0.6.1"
17
+ gem "standard", "~> 1.36"
18
+ end
19
+
20
+ group :test do
21
+ gem "rspec", "~> 3.0"
22
+ gem "webmock", "~> 3.23.1"
23
+ gem "simplecov"
24
+ gem "simplecov-cobertura"
25
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,158 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ webshaker (0.0.1)
5
+ ruby-openai
6
+ selenium-webdriver (~> 4.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ addressable (2.8.7)
12
+ public_suffix (>= 2.0.2, < 7.0)
13
+ ast (2.4.2)
14
+ base64 (0.2.0)
15
+ bigdecimal (3.1.8)
16
+ binding_of_caller (1.0.1)
17
+ debug_inspector (>= 1.2.0)
18
+ byebug (11.1.3)
19
+ coderay (1.1.3)
20
+ crack (1.0.0)
21
+ bigdecimal
22
+ rexml
23
+ debug_inspector (1.2.0)
24
+ diff-lcs (1.5.1)
25
+ docile (1.4.1)
26
+ dotenv (3.1.2)
27
+ event_stream_parser (1.0.0)
28
+ faraday (2.10.1)
29
+ faraday-net_http (>= 2.0, < 3.2)
30
+ logger
31
+ faraday-multipart (1.0.4)
32
+ multipart-post (~> 2)
33
+ faraday-net_http (3.1.1)
34
+ net-http
35
+ hashdiff (1.1.1)
36
+ interception (0.5)
37
+ json (2.7.2)
38
+ language_server-protocol (3.17.0.3)
39
+ lint_roller (1.1.0)
40
+ logger (1.6.0)
41
+ method_source (1.1.0)
42
+ multipart-post (2.4.1)
43
+ net-http (0.4.1)
44
+ uri
45
+ parallel (1.25.1)
46
+ parser (3.3.4.0)
47
+ ast (~> 2.4.1)
48
+ racc
49
+ pry (0.14.2)
50
+ coderay (~> 1.1)
51
+ method_source (~> 1.0)
52
+ pry-byebug (3.10.1)
53
+ byebug (~> 11.0)
54
+ pry (>= 0.13, < 0.15)
55
+ pry-rescue (1.6.0)
56
+ interception (>= 0.5)
57
+ pry (>= 0.12.0)
58
+ pry-stack_explorer (0.6.1)
59
+ binding_of_caller (~> 1.0)
60
+ pry (~> 0.13)
61
+ public_suffix (6.0.1)
62
+ racc (1.8.1)
63
+ rainbow (3.1.1)
64
+ rake (13.2.1)
65
+ regexp_parser (2.9.2)
66
+ rexml (3.3.4)
67
+ strscan
68
+ rspec (3.13.0)
69
+ rspec-core (~> 3.13.0)
70
+ rspec-expectations (~> 3.13.0)
71
+ rspec-mocks (~> 3.13.0)
72
+ rspec-core (3.13.0)
73
+ rspec-support (~> 3.13.0)
74
+ rspec-expectations (3.13.1)
75
+ diff-lcs (>= 1.2.0, < 2.0)
76
+ rspec-support (~> 3.13.0)
77
+ rspec-mocks (3.13.1)
78
+ diff-lcs (>= 1.2.0, < 2.0)
79
+ rspec-support (~> 3.13.0)
80
+ rspec-support (3.13.1)
81
+ rubocop (1.64.1)
82
+ json (~> 2.3)
83
+ language_server-protocol (>= 3.17.0)
84
+ parallel (~> 1.10)
85
+ parser (>= 3.3.0.2)
86
+ rainbow (>= 2.2.2, < 4.0)
87
+ regexp_parser (>= 1.8, < 3.0)
88
+ rexml (>= 3.2.5, < 4.0)
89
+ rubocop-ast (>= 1.31.1, < 2.0)
90
+ ruby-progressbar (~> 1.7)
91
+ unicode-display_width (>= 2.4.0, < 3.0)
92
+ rubocop-ast (1.31.3)
93
+ parser (>= 3.3.1.0)
94
+ rubocop-performance (1.21.1)
95
+ rubocop (>= 1.48.1, < 2.0)
96
+ rubocop-ast (>= 1.31.1, < 2.0)
97
+ ruby-openai (7.1.0)
98
+ event_stream_parser (>= 0.3.0, < 2.0.0)
99
+ faraday (>= 1)
100
+ faraday-multipart (>= 1)
101
+ ruby-progressbar (1.13.0)
102
+ rubyzip (2.3.2)
103
+ selenium-webdriver (4.23.0)
104
+ base64 (~> 0.2)
105
+ logger (~> 1.4)
106
+ rexml (~> 3.2, >= 3.2.5)
107
+ rubyzip (>= 1.2.2, < 3.0)
108
+ websocket (~> 1.0)
109
+ simplecov (0.22.0)
110
+ docile (~> 1.1)
111
+ simplecov-html (~> 0.11)
112
+ simplecov_json_formatter (~> 0.1)
113
+ simplecov-cobertura (2.1.0)
114
+ rexml
115
+ simplecov (~> 0.19)
116
+ simplecov-html (0.12.3)
117
+ simplecov_json_formatter (0.1.4)
118
+ standard (1.39.2)
119
+ language_server-protocol (~> 3.17.0.2)
120
+ lint_roller (~> 1.0)
121
+ rubocop (~> 1.64.0)
122
+ standard-custom (~> 1.0.0)
123
+ standard-performance (~> 1.4)
124
+ standard-custom (1.0.2)
125
+ lint_roller (~> 1.0)
126
+ rubocop (~> 1.50)
127
+ standard-performance (1.4.0)
128
+ lint_roller (~> 1.1)
129
+ rubocop-performance (~> 1.21.0)
130
+ strscan (3.1.0)
131
+ unicode-display_width (2.5.0)
132
+ uri (0.13.0)
133
+ webmock (3.23.1)
134
+ addressable (>= 2.8.0)
135
+ crack (>= 0.3.2)
136
+ hashdiff (>= 0.4.0, < 2.0.0)
137
+ websocket (1.2.11)
138
+
139
+ PLATFORMS
140
+ x86_64-darwin-23
141
+
142
+ DEPENDENCIES
143
+ byebug (~> 11.1)
144
+ dotenv
145
+ pry (~> 0.14.2)
146
+ pry-byebug (~> 3.10)
147
+ pry-rescue (~> 1.5)
148
+ pry-stack_explorer (~> 0.6.1)
149
+ rake (~> 13.2)
150
+ rspec (~> 3.0)
151
+ simplecov
152
+ simplecov-cobertura
153
+ standard (~> 1.36)
154
+ webmock (~> 3.23.1)
155
+ webshaker!
156
+
157
+ BUNDLED WITH
158
+ 2.4.22
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Martin Mochetti
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # Webshaker
2
+
3
+ An intelligent web scraper that uses Selenium WebDriver to scrape a URL and parse its content using AI.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem "webshaker"
11
+ ```
12
+
13
+ ### Configuration
14
+
15
+ In rails applications, it's standard to provide an initializer (e.g `config/initializers/webshaker.rb`) to load all the configuration settings of the gem. If you follow the previous step (First Time Authorization), you can do the following:
16
+
17
+ ```rb
18
+ Webshaker.configure do |config|
19
+ # Your app private key. Typically stored in the environment variables as it's a sensitive secret.
20
+ config.open_ai_key = ENV["WEBSHAKER_OPEN_AI_KEY"]
21
+
22
+ # The model you want to use to analyze the html content.
23
+ config.model = ENV["WEBSHAKER_OPEN_AI_MODEL"]
24
+ end
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Basic usage
30
+
31
+ ```ruby
32
+ # Create a shaker out of a specific URL.
33
+ # Make sure certain xpath is fulfilled before downloading the HTML content (to circumvent client dynamic hydration).
34
+ # You can also wait for css: {wait_for: {css: ".some-class"}}
35
+ # Or you can wait for some tag name: {wait_for: {tag_name: "body"}}
36
+ shaker = Webshaker::Shaker.new(
37
+ "https://www.google.com",
38
+ {wait_for: {xpath: "/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[3]"}}
39
+ )
40
+
41
+ # Query anything about the website.
42
+ result = shaker.shake(with_prompt: "What's this website about?")
43
+ # => "This website appears to be the homepage of Google, specifically targeting users in Uruguay (as indicated by the reference to \"Uruguay\" and the Spanish language). It contains links to various Google services such as Gmail, Google Images, and a login page for Google accounts. Additionally, there are sections for user feedback, search functionalities, and links to Google policies and services. The layout includes buttons, forms, and elements for user interaction, typical of a search engine homepage."
44
+
45
+ result = shaker.shake(with_prompt: "Give me a list of all the links", respond_with: :json)
46
+ # =>
47
+ # {"links"=>
48
+ # ["https://mail.google.com/mail/&ogbl",
49
+ # "https://www.google.com/imghp?hl=es-419&ogbl",
50
+ # "https://accounts.google.com/ServiceLogin?hl=es-419&passive=true&continue=https://www.google.com/&ec=GAZAmgQ",
51
+ # "/search?sca_esv=08a7c6c574dce941&sca_upv=1&q=vela+olimpiadas&oi=ddle&ct=335645951&hl=es-419&sa=X&ved=0ahUKEwiBsrmL9taHAxWGq5UCHV1hEJkQPQgC",
52
+ # "https://about.google/?utm_source=google-UY&utm_medium=referral&utm_campaign=hp-footer&fg=1",
53
+ # "https://www.google.com/intl/es-419_uy/ads/?subid=ww-ww-et-g-awa-a-g_hpafoot1_1!o2&utm_source=google.com&utm_medium=referral&utm_campaign=google_hpafooter&fg=1",
54
+ # "https://www.google.com/services/?subid=ww-ww-et-g-awa-a-g_hpbfoot1_1!o2&utm_source=google.com&utm_medium=referral&utm_campaign=google_hpbfooter&fg=1",
55
+ # "https://google.com/search/howsearchworks/?fg=1",
56
+ # "https://policies.google.com/privacy?hl=es-419&fg=1",
57
+ # "https://policies.google.com/terms?hl=es-419&fg=1",
58
+ # "https://www.google.com/preferences?hl=es-419&fg=1",
59
+ # "/advanced_search?hl=es-419&fg=1",
60
+ # "/history/privacyadvisor/search/unauth?utm_source=googlemenu&fg=1&cctld=com",
61
+ # "/history/optout?hl=es-419&fg=1",
62
+ # "https://support.google.com/websearch/?p=ws_results_help&hl=es-419&fg=1"]}
63
+ ```
64
+
65
+ ## Development
66
+
67
+ You can use `bin/console` to access an interactive console. This will preload environment variables from a `.env` file.
68
+
69
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
70
+
71
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
72
+
73
+ ## Contributing
74
+
75
+ Bug reports and pull requests are welcome on GitHub at <https://github.com/mochetts/webshaker>. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/mochetts/webshaker/blob/main/CODE_OF_CONDUCT.md).
76
+
77
+ ## License
78
+
79
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
80
+
81
+ ## Code of Conduct
82
+
83
+ Everyone interacting in the Revolut::Connect project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/mochetts/webshaker/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
@@ -0,0 +1,27 @@
1
+ module Webshaker
2
+ class ScrapeResult
3
+ attr_accessor :screenshot, :html
4
+
5
+ def initialize(screenshot, html)
6
+ @screenshot = screenshot
7
+ @html = html
8
+ end
9
+
10
+ def save_to(output_dir_path)
11
+ save_shot(output_dir_path)
12
+ save_html(output_dir_path)
13
+ end
14
+
15
+ private
16
+
17
+ def save_shot(output_dir_path)
18
+ shot_path = File.join(output_dir_path, "screenshot.png")
19
+ File.write(shot_path, Base64.decode64(screenshot))
20
+ end
21
+
22
+ def save_html(output_dir_path)
23
+ html_path = File.join(output_dir_path, "content.html")
24
+ File.write(html_path, html)
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,81 @@
1
+ require "selenium-webdriver"
2
+ require "base64"
3
+ require "nokogiri"
4
+
5
+ module Webshaker
6
+ class Scraper
7
+ attr_reader :url, :driver, :options
8
+
9
+ def initialize(url, options = {})
10
+ @url = url
11
+ @options = options
12
+ @driver = Selenium::WebDriver.for(
13
+ :chrome,
14
+ options: Selenium::WebDriver::Chrome::Options.new.tap(&method(:configure))
15
+ )
16
+ end
17
+
18
+ def scrape
19
+ driver.navigate.to url
20
+
21
+ do_wait
22
+
23
+ screenshot = driver.screenshot_as :base64
24
+ html_content = driver.page_source
25
+ driver.quit
26
+ ScrapeResult.new(screenshot, clean_up(html_content))
27
+ end
28
+
29
+ def self.scrape(url, options = {})
30
+ new(url, options).scrape
31
+ end
32
+
33
+ private
34
+
35
+ def configure(driver_options)
36
+ driver_options.add_argument("--headless") if options.fetch(:headless, true)
37
+ driver_options
38
+ end
39
+
40
+ def do_wait
41
+ wait_until = options[:wait_until]
42
+
43
+ return if wait_until.nil?
44
+
45
+ wait = Selenium::WebDriver::Wait.new(timeout: 10) # Waits a maximum of 10 seconds
46
+
47
+ wait.until do
48
+ if wait_until.is_a?(Proc)
49
+ wait_until.call(driver)
50
+ elsif wait_until.is_a?(Hash)
51
+ selector = wait_until[:css] || wait_until[:tag_name] || wait_until[:xpath] || raise(ArgumentError, "wait_until must be a hash with one of these keys: :css, :tag_name, or :xpath")
52
+ driver.find_element(wait_until.keys.first, selector)
53
+ end
54
+ end
55
+ end
56
+
57
+ def clean_up(html_content)
58
+ # Parse the HTML content
59
+
60
+ doc = Nokogiri::HTML5(html_content)
61
+
62
+ # Remove scripts, styles, stylesheets and SVGs
63
+ doc.xpath("//script").remove
64
+ doc.xpath("//style").remove
65
+ doc.xpath("//link").remove
66
+ doc.xpath("//*[local-name() = 'svg']").remove
67
+
68
+ # Recursively remove attributes from nodes (except href's)
69
+ doc.traverse do |node|
70
+ if node.element?
71
+ node.attributes.each_key do |attr|
72
+ node.remove_attribute(attr) unless attr == "href"
73
+ end
74
+ end
75
+ end
76
+
77
+ # Return the cleaned HTML (without newlines and with no spaces between tags)
78
+ doc.inner_html.delete("\n").gsub(/>\s*</, "><")
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,53 @@
1
+ require "openai"
2
+
3
+ module Webshaker
4
+ class Shaker
5
+ attr_reader :url, :scrape_options
6
+
7
+ def initialize(url, scrape_options = {})
8
+ @url = url
9
+ @scrape_options = scrape_options
10
+ end
11
+
12
+ def shake(with_prompt:, respond_with: :text, temperature: 0.8)
13
+ ai_result(
14
+ with_prompt,
15
+ respond_with:,
16
+ temperature:
17
+ )
18
+ end
19
+
20
+ private
21
+
22
+ def html
23
+ @html ||= Webshaker::Scraper.new(url, scrape_options).scrape.html
24
+ end
25
+
26
+ def ai_result(user_prompt, respond_with: :text, temperature: 0.8)
27
+ response = ai_client.chat(
28
+ parameters: {
29
+ model: Webshaker.config.model,
30
+ messages: ai_prompt(user_prompt, html).concat((respond_with == :json) ? [{role: "user", content: "respond with json"}] : []),
31
+ temperature:
32
+ }.merge(
33
+ (respond_with == :json) ? {response_format: {type: "json_object"}} : {}
34
+ )
35
+ )
36
+ response = response["choices"][0]["message"]["content"]
37
+ response = JSON.parse(response) if respond_with === :json
38
+ response
39
+ end
40
+
41
+ def ai_client
42
+ @client ||= OpenAI::Client.new(access_token: Webshaker.config.open_ai_key)
43
+ end
44
+
45
+ def ai_prompt(user_prompt, html_content)
46
+ [
47
+ {role: "system", content: "You are an HTML interpreter. The user will give you the contents of an HTML and ask you something about it. Please comply with what the user asks."},
48
+ {role: "user", content: html_content},
49
+ {role: "user", content: user_prompt}
50
+ ]
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,3 @@
1
+ module Webshaker
2
+ VERSION = "0.0.1"
3
+ end
data/lib/webshaker.rb ADDED
@@ -0,0 +1,26 @@
1
+ require "webshaker/scrape_result"
2
+ require "webshaker/scraper"
3
+ require "webshaker/shaker"
4
+
5
+ module Webshaker
6
+ class Configuration
7
+ attr_accessor :open_ai_key, :model
8
+
9
+ def initialize
10
+ @open_ai_key = ENV.fetch("WEBSHAKER_OPEN_AI_KEY", nil)
11
+ @model = ENV.fetch("WEBSHAKER_OPEN_AI_MODEL", "gpt-4o-mini")
12
+ end
13
+ end
14
+
15
+ class << self
16
+ attr_writer :config
17
+
18
+ def config
19
+ @config ||= Webshaker::Configuration.new
20
+ end
21
+
22
+ def configure
23
+ yield(config)
24
+ end
25
+ end
26
+ end
metadata ADDED
@@ -0,0 +1,86 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: webshaker
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Martin Mochetti
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-08-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: selenium-webdriver
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: ruby-openai
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Web scraper that shakes a link to extract info out of it using AI.
42
+ email:
43
+ - martin@mochetts.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".env.sample"
49
+ - ".env.test"
50
+ - ".ruby-version"
51
+ - ".standard.yml"
52
+ - CODE_OF_CONDUCT.md
53
+ - Gemfile
54
+ - Gemfile.lock
55
+ - LICENSE.txt
56
+ - README.md
57
+ - Rakefile
58
+ - lib/webshaker.rb
59
+ - lib/webshaker/scrape_result.rb
60
+ - lib/webshaker/scraper.rb
61
+ - lib/webshaker/shaker.rb
62
+ - lib/webshaker/version.rb
63
+ homepage: https://github.com/mochetts/webshaker
64
+ licenses:
65
+ - MIT
66
+ metadata: {}
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 3.0.0
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubygems_version: 3.2.3
83
+ signing_key:
84
+ specification_version: 4
85
+ summary: An Intelligent web scraper
86
+ test_files: []