forked from insitro/redun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkflow.py
More file actions
211 lines (169 loc) · 5.72 KB
/
workflow.py
File metadata and controls
211 lines (169 loc) · 5.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import csv
import os
from collections import defaultdict
from typing import Dict, List, Optional, Sequence, Tuple, TypeVar
from urllib.parse import urljoin, urlparse, urlunparse
import requests
from bs4 import BeautifulSoup
from redun import File, cond, task
from redun.functools import flat_map, flatten
from redun.tools import render_template
redun_namespace = "redun.examples.scraper"
S = TypeVar("S")
T = TypeVar("T")
def make_local_filename(out_path: str, url: str) -> str:
"""
Choose a local filename for a given URL.
"""
filename = os.path.join(out_path, url).replace(":", "")
if filename.endswith("/") or os.path.isdir(filename):
filename += "index.html"
elif not filename.endswith(".html"):
filename = filename + ".html"
return filename
def get_base_url(url: str) -> str:
"""
Strip the query and fragment from a URL.
"""
parts = urlparse(url)
return urlunparse((parts.scheme, parts.netloc, parts.path, "", "", ""))
def clean_url(url: str, base_url: str) -> str:
"""
Clean a URL for use in crawling.
"""
# Make url absolute.
if not urlparse(url).netloc:
url = urljoin(base_url, url)
# Discard query params and fragment.
return get_base_url(url)
def clean_word(word: str) -> str:
"""
Clean a word for counting.
"""
return word.strip(",.:()&-").lower()
@task(limits=["crawl"])
def scrape_page(url: str, out_path: str) -> Optional[File]:
"""
Copy an HTML page to a local file.
"""
# We use `limits` above to limit up to 5 downloads at once (see .redun/redun.ini)
response = requests.head(url)
if response.ok and "text/html" in response.headers["Content-Type"]:
# If page is accessible and HTML, download it.
return File(url).copy_to(File(make_local_filename(out_path, url)))
else:
return None
@task()
def get_links(file: File, base_url: str, url_prefix: str) -> List[str]:
"""
Returns the links within an HTML file.
"""
soup = BeautifulSoup(file.read(), "html.parser")
base_url = get_base_url(base_url)
urls = []
for link in soup.find_all("a"):
url = link.get("href")
url = clean_url(url, base_url)
if url.startswith(url_prefix):
# Only keep links that are within the same site (i.e. shared the prefix).
urls.append(url)
return urls
@task()
def process_page(file: File, url: str, url_prefix: str, out_path: str, depth: int) -> List[File]:
"""
Process a page by finding more links.
"""
links = get_links(file, url, url_prefix)
# Recursively crawl if desired.
if depth > 1:
subfiles = flat_map(
crawl.partial(url_prefix=url_prefix, out_path=out_path, depth=depth - 1),
links,
)
# We use flatten to concatenate our main file with the subfiles list.
return flatten([[file], subfiles])
else:
return [file]
@task(check_valid="shallow")
def crawl(url: str, url_prefix: str, out_path: str, depth: int) -> List[File]:
"""
Recursively crawl a website and save each HTML page to a local file.
"""
# We use `check_valid="shallow"` to make resuming a past execution faster.
# See task options documentation for more details.
if depth <= 0:
return []
file = scrape_page(url, out_path)
# If the page scraping is successful, process it.
# We use cond (a lazy if-statement) since `file` is a lazy expression.
return cond(file, process_page(file, url, url_prefix, out_path, depth), [])
@task()
def write_csv(out_path: str, columns: List[str], data: List[Sequence]) -> File:
"""
Write a table to a CSV.
"""
file = File(out_path)
with file.open("w") as out:
writer = csv.writer(out, delimiter="\t")
writer.writerow(columns)
for row in data:
writer.writerow(row)
return file
@task()
def count_words(files: List[File]) -> List[Tuple[str, int]]:
"""
Count the word frequency in a list of files and write to the countds to a CSV.
"""
# Count word frequency across all files.
word_count = defaultdict(int)
for file in files:
soup = BeautifulSoup(file.read(), "html.parser")
words = soup.text.split()
for word in words:
word = clean_word(word)
if word:
word_count[word] += 1
counts = sorted(word_count.items(), key=lambda word_count: word_count[1], reverse=True)
return counts
@task()
def make_report(
report_path: str, url: str, files: List[File], word_counts: List[Tuple[str, int]]
) -> File:
"""
Make an HTML report for the web scraping.
"""
context = {
"url": url,
"files": files,
"word_counts": word_counts,
}
# Since we pass the template as a File, our pipeline is reactive to changes
# we might make in the template (e.g. changing the report structure).
return render_template(report_path, File("templates/report.html"), context)
@task()
def main(
url: str = "https://www.python.org/",
url_prefix: str = "https://www.python.org",
out_path: str = "./",
depth: int = 2,
) -> Dict[str, File]:
"""
Scrape a website, compute the word frequency, generate an HTML report.
"""
files = crawl(url, url, os.path.join(out_path, "crawl"), depth)
word_counts = count_words(files)
word_counts_file = write_csv(
os.path.join(out_path, "computed/word_counts.txt"),
["word", "count"],
word_counts,
)
report_file = make_report(
report_path=os.path.join(out_path, "reports/report.html"),
url=url,
files=files,
word_counts=word_counts,
)
return {
"word_counts": word_counts_file,
"report_file": report_file,
}