├── models
├── cv.pkl
├── mnb.pkl
├── pac.pkl
├── tfv.pkl
├── tfv_vec.pkl
├── mnb_clf_joblib
└── mnb_clf_joblib.pkl
├── app.js
├── requirements.txt
├── .gitignore
├── README.md
├── machine_learning_news_scrapper.py
└── LICENSE
/models/cv.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/metacall/ml-news-article-scraper-example/HEAD/models/cv.pkl
--------------------------------------------------------------------------------
/models/mnb.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/metacall/ml-news-article-scraper-example/HEAD/models/mnb.pkl
--------------------------------------------------------------------------------
/models/pac.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/metacall/ml-news-article-scraper-example/HEAD/models/pac.pkl
--------------------------------------------------------------------------------
/models/tfv.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/metacall/ml-news-article-scraper-example/HEAD/models/tfv.pkl
--------------------------------------------------------------------------------
/models/tfv_vec.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/metacall/ml-news-article-scraper-example/HEAD/models/tfv_vec.pkl
--------------------------------------------------------------------------------
/models/mnb_clf_joblib:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/metacall/ml-news-article-scraper-example/HEAD/models/mnb_clf_joblib
--------------------------------------------------------------------------------
/models/mnb_clf_joblib.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/metacall/ml-news-article-scraper-example/HEAD/models/mnb_clf_joblib.pkl
--------------------------------------------------------------------------------
/app.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | const readline = require("readline-sync");
4 | const { similarNews } = require('./machine_learning_news_scrapper.py');
5 |
6 | console.log("Enter the News URL:");
7 | url = String(readline.question());
8 |
9 | console.table(similarNews(url));
10 |
11 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | beautifulsoup4==4.9.1
2 | bs4==0.0.1
3 | certifi==2020.6.20
4 | chardet==3.0.4
5 | click==7.1.2
6 | cssselect==1.1.0
7 | feedfinder2==0.0.4
8 | feedparser==6.0.2
9 | filelock==3.0.12
10 | google==3.0.0
11 | idna==2.10
12 | jieba3k==0.35.1
13 | joblib==1.0.1
14 | lxml==4.6.3
15 | newspaper3k==0.2.8
16 | nltk==3.5
17 | numpy==1.19.5
18 | pandas==1.1.5
19 | Pillow==8.1.2
20 | python-dateutil==2.8.1
21 | pytz==2021.1
22 | PyYAML==5.4.1
23 | regex==2021.3.17
24 | requests==2.24.0
25 | requests-file==1.5.1
26 | scikit-learn==0.22.1
27 | scipy==1.5.4
28 | sgmllib3k==1.0.0
29 | six==1.15.0
30 | sklearn==0.0
31 | soupsieve==2.0.1
32 | threadpoolctl==2.1.0
33 | tinysegmenter==0.3
34 | tldextract==3.1.0
35 | tqdm==4.59.0
36 | urllib3==1.25.9
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ######################
2 | # Python #
3 | ######################
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # C extensions
11 | *.so
12 |
13 | # Distribution / packaging
14 | .Python
15 | env/
16 | #build/
17 | develop-eggs/
18 | dist/
19 | downloads/
20 | eggs/
21 | .eggs/
22 | lib/
23 | lib64/
24 | parts/
25 | sdist/
26 | var/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 |
31 | # PyInstaller
32 | # Usually these files are written by a python script from a template
33 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
34 | *.manifest
35 | *.spec
36 |
37 | # Installer logs
38 | pip-log.txt
39 | pip-delete-this-directory.txt
40 |
41 | # Unit test / coverage reports
42 | htmlcov/
43 | .tox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *,cover
50 | .hypothesis/
51 |
52 | # Translations
53 | *.mo
54 | *.pot
55 |
56 | # Django stuff:
57 | *.log
58 | local_settings.py
59 |
60 | # Flask instance folder
61 | instance/
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # IPython Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # dotenv
82 | .env
83 |
84 | # virtualenv
85 | venv/
86 | ENV/
87 |
88 | # Spyder project settings
89 | .spyderproject
90 |
91 | # Others
92 | .project
93 | .settings
94 | .classpath
95 | .idea
96 |
97 | ######################
98 | # Node #
99 | ######################
100 |
101 | # Logs
102 | logs
103 | *.log
104 | npm-debug.log*
105 |
106 | # Runtime data
107 | pids
108 | *.pid
109 | *.seed
110 |
111 | # Directory for instrumented libs generated by jscoverage/JSCover
112 | lib-cov
113 |
114 | # Coverage directory used by tools like istanbul
115 | coverage
116 |
117 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
118 | .grunt
119 |
120 | # node-waf configuration
121 | .lock-wscript
122 |
123 | # Compiled binary addons (http://nodejs.org/api/addons.html)
124 | build/Release
125 |
126 | # Dependency directories
127 | node_modules
128 | jspm_packages
129 |
130 | # Optional npm cache directory
131 | .npm
132 |
133 | # Optional REPL history
134 | .node_repl_history
135 |
136 | ######################
137 | # OS generated files #
138 | ######################
139 |
140 | __MACOSX
141 | .DS_Store
142 | ._*
143 |
144 | .Spotlight-V100
145 | .Trashes
146 |
147 | ehthumbs.db
148 | Thumbs.db
149 |
150 | ############
151 | # Packages #
152 | ############
153 | # it's better to unpack these files and commit the raw source
154 | # git has its own built in compression methods
155 | *.7z
156 | *.dmg
157 | *.gz
158 | *.iso
159 | *.jar
160 | *.rar
161 | *.tar
162 | *.zip
163 | .DS_Store
164 |
165 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Polyglot Machine Learning example for scraping similar news articles
2 |
3 |
4 |

5 |
6 |
7 | In this example, we will see how we can work with Machine Learning applications written in Python with a NodeJS Script, to build a **Polyglot Machine Learning application for scraping similar news articles**.
8 |
9 | ## Install
10 |
11 | Install MetaCall CLI:
12 |
13 | ```sh
14 | $ curl -sL https://raw.githubusercontent.com/metacall/install/master/install.sh | sh
15 | ```
16 |
17 | Install application dependencies:
18 |
19 | - For Python: `metacall pip3 install -r requirements.txt`
20 | - For NodeJS: `metacall npm i readline-sync`
21 |
22 | ## Run the Example
23 |
24 | ```sh
25 | $ metacall app.js
26 | ```
27 |
28 | Once the application is kick-started, you will be prompted to enter a News Article which you would like to find similar articles for. Let's use this sample article for testing our application: **https://www.nytimes.com/2021/03/23/business/teslas-autopilot-safety-investigations.html**
29 |
30 | Here is the application output:
31 |
32 | ```
33 | $ metacall app.js
34 | Information: Global configuration loaded from /gnu/store/5cxmq6y8z24ijnvhh6lndgpriwnhf3jl-metacall-0.3.17/configurations/global.json
35 | Enter the News URL:
36 | https://www.nytimes.com/2021/03/23/business/teslas-autopilot-safety-investigations.html
37 | ┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬───────────────┐
38 | │ (index) │ Values │
39 | ├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼───────────────┤
40 | │ https://auto.timesofindia.com/news/others/teslas-autopilot-technology-faces-fresh-scrutiny/articleshow/81652823.cms │ '83.68405286' │
41 | │ https://www.autosafety.org/teslas-autopilot-technology-faces-fresh-scrutiny/ │ '60.35694007' │
42 | │ https://www.anandmarket.in/teslas-autopilot-technology-faces-fresh-scrutiny/ │ '94.97681053' │
43 | │ https://www.entrepreneur.com/article/367724 │ '60.67538891' │
44 | │ http://www.newsnetworks.in/india/teslas-autopilot-technology-faces-fresh-scrutiny/ │ '0.' │
45 | └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴───────────────┘
46 | Script (app.js) loaded correctly
47 | ```
48 | ## Deployment using MetaCall FaaS
49 |
50 | After deploying the application into the FaaS https://dashboard.metacall.io, it can be accessed with (change `` by the alias you used to sign up):
51 |
52 | ```sh
53 | curl -X POST https://api.metacall.io//ml-news-article-scraper-example/v1/call/similarNews -X POST --data '{ "url": "https://www.nytimes.com/2021/03/23/business/teslas-autopilot-safety-investigations.html" }'
54 | ```
55 | ## LICENSE
56 | [Apache License 2.0](./LICENSE)
57 |
58 |
59 |
--------------------------------------------------------------------------------
/machine_learning_news_scrapper.py:
--------------------------------------------------------------------------------
1 | import warnings
2 | import re
3 | from newspaper import Article
4 | from sklearn.feature_extraction.text import TfidfVectorizer
5 | from sklearn.metrics.pairwise import cosine_similarity
6 | from sklearn.model_selection import train_test_split
7 | import joblib
8 | from googlesearch import search
9 | from urllib.parse import urlparse
10 | warnings.filterwarnings("ignore")
11 |
12 | def extractor(url):
13 | """
14 | Extractor function that gets the article body from the URL
15 | Args:
16 | url: URL of the News Article/Source
17 | Returns:
18 | article: Raw Article Body
19 | article_title: Title of the Article that has been extracted
20 | """
21 |
22 | article = Article(url)
23 | try:
24 | article.download()
25 | article.parse()
26 | except:
27 | pass
28 |
29 | #Get the article title and convert them to lower-case
30 | article_title = article.title
31 | article = article.text.lower()
32 | article = [article]
33 | return (article, article_title)
34 |
35 |
36 | def text_area_extractor(text):
37 | """
38 | Textbox extractor function to preprocess and extract text
39 | Args:
40 | text: Raw Extracted Text from the News Article
41 | Returns:
42 | text: Preprocessed and clean text ready for analysis
43 | """
44 | text = text.lower()
45 | text = re.sub(r'[^a-zA-Z0-9\s]', ' ', text)
46 | text = re.sub("(\\r|\r|\n)\\n$", " ", text)
47 | text = [text]
48 | return text
49 |
50 | def google_search(title, url):
51 | """
52 | Function to perform a Google Search with the specified title and URL
53 | Args:
54 | title: Title of the Article
55 | url: URL of the specified article
56 | Returns:
57 | search_urls: Similar News Articles found over the Web
58 | source_sites: Hostname of the Articles founder over the Web
59 | """
60 | target = url
61 | domain = urlparse(target).hostname
62 | search_urls = []
63 | source_sites = []
64 | for i in search(title, tld = "com", num = 10, start = 1, stop = 6):
65 | if "youtube" not in i and domain not in i:
66 | source_sites.append(urlparse(i).hostname)
67 | search_urls.append(i)
68 | return search_urls, source_sites
69 |
70 | def similarity(url_list, article):
71 | """
72 | Function to check the similarity of the News Article through Cosine Similarity
73 | Args:
74 | url_list: List of the URLs similar to the news article
75 | article: Preprocessed article which would be vectorized
76 | Returns:
77 | cosine_cleaned: Cosine Similarity Scores of each URL passed
78 | average_score: Average value of the cosine similarity scores fetched
79 | """
80 | article = article
81 | sim_tfv = TfidfVectorizer(stop_words ="english")
82 | sim_transform1 = sim_tfv.fit_transform(article)
83 | cosine = []
84 | cosine_cleaned = []
85 | cosine_average = 0
86 | count = 0
87 |
88 | for i in url_list:
89 | test_article, test_title = extractor(i)
90 | test_article = [test_article]
91 | sim_transform2 = sim_tfv.transform(test_article[0])
92 | score = cosine_similarity(sim_transform1, sim_transform2)
93 | cosine.append(score*100)
94 | count+=1
95 | for i in cosine:
96 | x = str(i).replace('[','').replace(']','')
97 | cosine_cleaned.append(x)
98 |
99 | for i in cosine:
100 | if i !=0:
101 | cosine_average = cosine_average + i
102 | else:
103 | count-=1
104 |
105 | average_score = cosine_average/count
106 | average_score = str(average_score).replace('[','').replace(']','')
107 | average_score = float(average_score)
108 | return cosine_cleaned, average_score
109 |
110 | def handlelink(article_link):
111 | """
112 | Classification function to take the article link and predict the similar news articles
113 | Args:
114 | article_link: URL of the article
115 | Returns:
116 | pred: Predicted news sources from the machine learning model
117 | article_title: Title of the Article
118 | article: Article fetched from the URL
119 | url: URL of the article
120 | """
121 |
122 | job_pac = joblib.load('models/pac.pkl')
123 | job_vec = joblib.load('models/tfv.pkl')
124 | url = (article_link)
125 | article, article_title = extractor(article_link)
126 | pred = job_pac.predict(job_vec.transform(article))
127 | return pred, article_title, article, url
128 |
129 |
130 | def similarNews(url):
131 | """
132 | Driver function to return a dictionary with all the similar news and their similarity score
133 | Args:
134 | url: URL of the article
135 | Returns:
136 | dictionary: Dictionary containing all the similar news articles and their similarity score
137 | """
138 | prediction, article_title, article, url = handlelink(article_link=url)
139 | url_list, sitename = google_search(article_title, url)
140 | similarity_score, avgScore = similarity(url_list, article)
141 | dictionary = dict(zip(url_list, similarity_score))
142 | return dictionary
143 |
144 |
145 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | https://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | Copyright 2013-2018 Docker, Inc.
180 |
181 | Licensed under the Apache License, Version 2.0 (the "License");
182 | you may not use this file except in compliance with the License.
183 | You may obtain a copy of the License at
184 |
185 | https://www.apache.org/licenses/LICENSE-2.0
186 |
187 | Unless required by applicable law or agreed to in writing, software
188 | distributed under the License is distributed on an "AS IS" BASIS,
189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190 | See the License for the specific language governing permissions and
191 | limitations under the License.
192 |
193 |
--------------------------------------------------------------------------------