websucker-pip/mongo/mongocrawler.py

824 lines
27 KiB
Python
Raw Normal View History

2023-03-05 14:44:49 +00:00
import pymongo
2023-04-01 18:44:37 +00:00
import pymongo.errors
2023-03-05 14:44:49 +00:00
import trafilatura
import trafilatura.feeds
import trafilatura.sitemaps
import trafilatura.spider
2023-03-10 12:01:11 +00:00
import trafilatura.utils
2023-03-16 15:06:07 +00:00
import trafilatura.external
2023-03-05 14:44:49 +00:00
import sys
2023-03-07 07:58:28 +00:00
import courlan
2023-03-11 13:14:39 +00:00
import urllib
2023-04-12 12:35:35 +00:00
from datetime import datetime as dat
import datetime
2023-03-12 05:16:47 +00:00
import click
2023-03-12 08:50:22 +00:00
import logging as LOGGER
import os
2023-03-16 15:06:07 +00:00
import pprint
2023-04-01 08:49:28 +00:00
import re
2023-04-03 14:37:01 +00:00
import time
import collections
import math
2023-04-05 15:09:42 +00:00
import random
2023-04-06 10:15:33 +00:00
import hashlib
2023-04-13 14:16:11 +00:00
from bs4 import BeautifulSoup
import urllib.parse
import os.path
2023-04-17 13:07:58 +00:00
import binascii
import json
2023-03-05 14:44:49 +00:00
2023-04-17 12:32:52 +00:00
# database options
2023-03-12 08:50:22 +00:00
CONNECTION=os.getenv("SUCKER_CONNECTION","mongodb://root:example@localhost:27017/")
DBNAME=os.getenv("SUCKER_DBNAME","crawler")
2023-04-17 12:32:52 +00:00
# retrieving filter
BATCH_SIZE = int(os.getenv("SUCKER_BATCH_SIZE","10"))
MIN_FILE_SIZE=int(os.getenv("SUCKER_MIN_FILE_SIZE","300"))
MAX_FILE_SIZE=int(os.getenv("SUCKER_MAX_FILE_SIZE","10000000"))
# document originality filter
MIN_TEXT_SIZE=int(os.getenv("SUCKER_MIN_TEXT_SIZE","200"))
CHECK_PARAGRAPH_SIZE=int(os.getenv("SUCKER_CHECK_PARAGRAPH_SIZE","150"))
TEXT_TRASH_RATIO=float(os.getenv("SUCKER_TEXT_TRASH_RATIO","0.6"))
# link and domain sampling
DISCOVER_LINK_RATIO = float(os.getenv("SUCKER_DISCOVER_LINK_RATIO","0.3"))
SAMPLE_SET_SIZE = int(os.getenv("SUCKER_DISCOVER_LINK_RATIO","10000"))
CLASSIFIER_SET_SIZE = int(os.getenv("SUCKER_DISCOVER_LINK_RATIO","200"))
# link filter
LANGUAGE= os.getenv("SUCKER_LANGUAGE","sk")
DOMAIN = os.getenv("SUCKER_DOMAIN","sk")
STOP_PATHS=os.getenv("SUCKER_STOP_PATHS","xml,rss,login,admin").split(",")
2023-04-13 14:16:11 +00:00
def get_bs_links(link,html):
# Extrakcia linkov zo stranky
bs = BeautifulSoup(html, "lxml")
base = link
if bs.base is not None and "href" in bs.base.attrs:
base = bs.base["href"]
base = urllib.parse.urlparse(courlan.normalize_url(base))
links = set()
# Normalizacia linkov
for l in bs.find_all("a", href=True):
if "rel" in l.attrs and l.attrs["rel"] == "nofollow" or "nofollow" in l.attrs:
continue
href = l["href"]
try:
parsed = urllib.parse.urlparse(courlan.normalize_url(href))
netloc = parsed.netloc
path = os.path.normpath(parsed.path)
scheme = parsed.scheme
2023-04-14 06:22:24 +00:00
query = parsed.query
2023-04-13 14:16:11 +00:00
# internal link
if parsed.netloc == "":
scheme = base.scheme
netloc = base.netloc
if not parsed.path.startswith("/"):
path = os.path.normpath(base.path +"/" + path)
if not scheme.startswith("http"):
continue
if path.startswith("/"):
path = path[1:]
if path.endswith(")"):
# javascript
continue
2023-04-14 06:22:24 +00:00
href = urllib.parse.urlunparse((scheme,netloc,path,"",query,""))
2023-04-13 14:16:11 +00:00
href = courlan.normalize_url(href)
links.add(href)
except ValueError as err:
print(err)
pass
return links
2023-04-30 11:54:36 +00:00
2023-04-06 10:15:33 +00:00
def split_train(res):
trainset = []
testset = []
for i,item in enumerate(res):
if i % 10 == 0:
testset.append(item)
else:
trainset.append(item)
return trainset,testset
2023-03-17 15:40:55 +00:00
2023-03-07 15:18:32 +00:00
def calculate_checksums(text):
2023-03-05 17:53:14 +00:00
"""
2023-04-23 08:02:52 +00:00
Paragraph separation must be compatible with text extraction. Are paragraphs separated with a blank line or a white line?
@return fingerprints of a paragraphs in text. Paragraphs are separated by a new line.
2023-03-05 17:53:14 +00:00
"""
checksums = []
sizes = []
hval = 0
hsz = 0
sz = 0
for c in text:
cv = ord(c)
sz += 1
2023-04-04 12:39:03 +00:00
if cv > 64: # ignore non-ascii
2023-03-05 17:53:14 +00:00
hval += (hval << 3) + cv
zv = hval >> 31
hval &= 0x7fffffff
hval += zv
hsz += 1
if c == "\n" and hsz > 0:
2023-04-01 04:47:12 +00:00
if hsz > CHECK_PARAGRAPH_SIZE:
2023-03-05 17:53:14 +00:00
checksums.append(hval)
sizes.append(sz)
sz = 0
hsz = 0
2023-04-01 04:47:12 +00:00
if hsz > CHECK_PARAGRAPH_SIZE:
2023-03-05 17:53:14 +00:00
checksums.append(hval)
sizes.append(sz)
return checksums, sizes
2023-03-11 10:30:30 +00:00
def is_robot_good(link,rules):
# check robots.txt rules
2023-03-12 08:50:22 +00:00
if rules is not None and not rules.can_fetch("*", link):
2023-03-11 10:30:30 +00:00
return False
return True
def is_link_good(link):
2023-03-11 13:14:39 +00:00
r = courlan.check_url(link,strict=True,language=LANGUAGE)
2023-03-11 10:30:30 +00:00
if r is None:
return None
2023-03-17 11:30:53 +00:00
llink,lhostname = r
2023-04-08 08:33:40 +00:00
paths = set(llink.split("/"))
for item in STOP_PATHS:
if item in paths:
return None
2023-03-17 11:30:53 +00:00
#print(llink,lhostname)
# hostname rules
if not lhostname.endswith(DOMAIN):
LOGGER.debug("bad hostname")
2023-03-11 10:30:30 +00:00
return None
if courlan.is_not_crawlable(llink):
2023-03-12 08:50:22 +00:00
LOGGER.debug("not crawlable")
2023-03-11 10:30:30 +00:00
return None
2023-03-11 13:14:39 +00:00
return llink
2023-03-11 10:30:30 +00:00
2023-04-07 13:56:43 +00:00
def get_link_doc(link:str,status="frontlink")->dict:
2023-04-23 08:02:52 +00:00
parsed = urllib.parse.urlparse(courlan.normalize_url(link))
url = urllib.parse.urlunparse(parsed)
tokens = parsed.netloc.split(".")
domain = tokens[-2] + "." + tokens[-1]
return {"url":link,"host":parsed.netloc,"domain":domain,"status":status,"created_at":dat.utcnow()}
2023-03-05 17:53:14 +00:00
2023-03-07 15:18:32 +00:00
2023-04-07 13:56:43 +00:00
def fetch_page(link:str)->(str,str):
2023-04-05 15:09:42 +00:00
print("fetching:::::")
print(link)
final_link = link
2024-03-06 07:59:17 +00:00
response = trafilatura.fetch_response(link,decode=False)
print(response)
2023-04-05 15:09:42 +00:00
time.sleep(2)
html = None
if response is not None :
good = True
if response.status != 200:
good = False
LOGGER.error('not a 200 response: %s for URL %s', response.status, url)
2023-04-17 12:32:52 +00:00
elif response.data is None or len(response.data) < MIN_FILE_SIZE:
2023-04-05 15:09:42 +00:00
LOGGER.error('too small/incorrect for URL %s', link)
good = False
# raise error instead?
2023-04-17 12:32:52 +00:00
elif len(response.data) > MAX_FILE_SIZE:
2023-04-05 15:09:42 +00:00
good = False
LOGGER.error('too large: length %s for URL %s', len(response.data), link)
if good:
2024-03-06 07:59:17 +00:00
html = trafilatura.utils.decode_file(response.data)
2023-04-05 15:09:42 +00:00
if html is not None:
html, final_link = trafilatura.spider.refresh_detection(html, final_link)
# is there a meta-refresh on the page?
if final_link is None: # malformed or malicious content
html = None
2023-04-08 08:12:31 +00:00
final_link = courlan.normalize_url(final_link)
2023-04-05 15:09:42 +00:00
return final_link,html
2023-03-07 09:57:47 +00:00
2023-04-07 13:56:43 +00:00
def fetch_robot(base_url:str)->urllib.robotparser.RobotFileParser:
2023-03-10 12:01:11 +00:00
try:
2023-03-29 08:17:57 +00:00
rawrules = trafilatura.fetch_url("https://"+ base_url + "/robots.txt")
#print(rawrules)
rules = urllib.robotparser.RobotFileParser()
rules.parse(rawrules.split("\n"))
2023-03-14 09:59:58 +00:00
LOGGER.info('got robots')
2023-03-10 12:01:11 +00:00
except Exception as exc:
2023-03-12 08:50:22 +00:00
LOGGER.error('cannot read robots.txt: %s', exc)
2023-03-10 12:01:11 +00:00
rules = None
2023-03-29 08:17:57 +00:00
# exceptions happening here
2023-03-10 15:19:24 +00:00
return rules
2023-04-13 14:11:19 +00:00
def extract_page(final_link,html):
doc = None
if html is not None:
doc = trafilatura.bare_extraction(html,url=final_link,with_metadata=True,include_formatting=False,target_language=LANGUAGE,favor_precision=True)
if doc is not None:
2023-05-16 13:18:01 +00:00
lines = doc["text"].split("\n")
# filter out tables
good_lines = []
for line in lines:
if line.startswith("|") or line.startswith("1 2 3 4") or line.startswith("12345"):
continue
good_lines.append(line)
doc["text"] = "\n".join(good_lines)
# text too small
2023-04-17 12:32:52 +00:00
if not "text" in doc or len(doc["text"]) < MIN_TEXT_SIZE:
2023-04-13 14:11:19 +00:00
doc = None
return doc
2023-03-07 09:57:47 +00:00
2023-04-11 11:41:28 +00:00
def set_content_checksums(doc):
2023-04-09 07:37:52 +00:00
text = doc["text"]
checksums,sizes = calculate_checksums(text)
doc["text_size"] = len(text)
doc["text_md5"] = hashlib.md5(text.encode("utf8")).hexdigest()
doc["paragraph_checksums"] = checksums
doc["paragraph_sizes"] = sizes
doc["paragraph_sizes_sum"] = sum(sizes)
end_sentence_marker = re.compile("\w[\.]")
sentences = 0
for item in re.finditer(end_sentence_marker,text):
t = item.group(0)
if t[0].islower():
sentences += 1
doc["sentences_count"] = sentences
2023-03-08 09:56:39 +00:00
2023-05-18 08:23:13 +00:00
def index_page(db,original_link:str,final_link:str,html:bytes,doc,filter_content=True):
2023-03-07 09:57:47 +00:00
linkcol = db["links"]
htmlcol = db["html"]
2023-03-07 15:18:32 +00:00
contentcol = db["content"]
2023-04-01 04:47:12 +00:00
checkcol = db["check"]
2023-04-13 14:11:19 +00:00
state = "good"
link = original_link
if original_link != final_link:
linkcol.update_one({"url":original_link},{"$set":{"status":"redirect"}})
link = final_link
if html is None:
state = "html_error"
elif doc is None:
state = "content_error"
if doc is not None:
set_content_checksums(doc)
tsz = doc["text_size"]
psz = doc["paragraph_sizes_sum"]
2023-04-17 13:07:58 +00:00
if filter_content and (tsz < MIN_TEXT_SIZE or psz/tsz < TEXT_TRASH_RATIO):
2023-04-13 14:11:19 +00:00
state = "small"
# check copy
if state == "good":
origsz = 0
for chs,paragraph_size in zip(doc["paragraph_checksums"],doc["paragraph_sizes"]):
# index paragraph checksums
nd = checkcol.find_one({"_id":chs})
if nd is None:
origsz += paragraph_size
doc["original_text_size"] = origsz
2023-04-17 13:07:58 +00:00
if filter_content and (1 - (origsz / tsz)) > TEXT_TRASH_RATIO:
2023-04-13 14:11:19 +00:00
state = "copy"
if state == "good":
htdoc = get_link_doc(link,state)
htdoc["html"] = html
htdoc["html_size"] = len(html)
2023-05-18 08:23:13 +00:00
htdoc["html_md5"]= hashlib.md5(html).hexdigest()
2023-04-13 14:11:19 +00:00
# can be revisited - upsert
del htdoc["url"]
htmlcol.update_one({"url":link},{"$set":htdoc},upsert=True)
doc.update(get_link_doc(link,"good"))
# todo extract links
print(link,doc)
del doc["url"]
contentcol.update_one({"url":link},{"$set":doc},upsert=True)
for chs in doc["paragraph_checksums"]:
2023-04-14 06:22:24 +00:00
checkcol.update_one({"_id":chs},{"$inc":{"count":1}},upsert=True)
2023-04-13 14:11:19 +00:00
linkdoc = get_link_doc(link,state)
del linkdoc["url"]
linkcol.update_one({"url":link},{"$set":linkdoc})
return state
def save_batch_info(db,host,states,docs):
2023-04-11 11:41:28 +00:00
good_document_count = 0
original_text_size = 0
2023-04-13 14:11:19 +00:00
batch_size = 0
2023-04-13 14:16:11 +00:00
d = host.split(".")
domain = d[-2] + "." + d[-1]
2023-04-13 14:11:19 +00:00
for state,doc in zip(states,docs):
batch_size += 1
2023-03-12 08:50:22 +00:00
if state == "good":
2023-04-11 11:41:28 +00:00
good_document_count += 1
2023-04-13 14:11:19 +00:00
original_text_size += doc["original_text_size"]
2023-04-11 11:41:28 +00:00
batchdoc = {
2023-04-13 14:11:19 +00:00
"host": host,
"domain": domain,
2023-04-12 12:35:35 +00:00
"created_at": dat.utcnow(),
2023-04-11 11:41:28 +00:00
"good_document_count":good_document_count,
"original_text_size":original_text_size,
2023-04-13 14:11:19 +00:00
"good_prob": good_document_count / batch_size,
"batch_size": batch_size,
2023-04-11 11:41:28 +00:00
}
db["batches"].insert_one(batchdoc)
2023-03-10 15:19:24 +00:00
2023-03-11 10:30:30 +00:00
2023-04-07 13:56:43 +00:00
def extract_links(link_batch:list,responses:list,hostname:str,rules,default_status="frontlink")->list:
2023-03-11 10:30:30 +00:00
links = {}
2023-03-29 08:17:57 +00:00
badrobot = 0
2023-03-11 13:14:39 +00:00
for original_link,(final_link,html) in zip(link_batch,responses):
2023-03-11 10:30:30 +00:00
status = default_status
2023-04-08 08:12:31 +00:00
if html is None or len(html) < 256:
continue
2023-04-12 12:35:35 +00:00
page_links = get_bs_links(final_link,html)
for link in page_links:
if not courlan.is_external(link,final_link) and not is_robot_good(link,rules):
2023-03-29 08:17:57 +00:00
badrobot += 1
continue
2023-03-12 12:53:17 +00:00
status = str(default_status)
2023-03-11 10:30:30 +00:00
links[link] = status
outlinks = []
2023-03-14 09:59:58 +00:00
badlink = 0
2023-03-11 10:30:30 +00:00
for link,status in links.items():
link = is_link_good(link)
if link is None:
2023-03-14 09:59:58 +00:00
badlink += 1
2023-03-11 10:30:30 +00:00
continue
outlinks.append((link,status))
2023-03-14 09:59:58 +00:00
print(f"{len(links)} total links, {badrobot} badrobot {badlink} badlinks")
2023-03-11 10:30:30 +00:00
return outlinks
def index_links(db,extracted_links):
linkcol=db["links"]
for link,status in extracted_links:
2023-04-03 14:37:01 +00:00
if not is_link_good(link):
continue
2023-05-18 08:23:13 +00:00
if status == "frontlink" :
2023-04-05 15:09:42 +00:00
doc = get_link_doc(link,status)
try:
linkcol.insert_one(doc)
# dont overwrite
except pymongo.errors.DuplicateKeyError as ex:
pass
else:
print("updating " + link,status)
2023-04-12 12:35:35 +00:00
linkcol.update_one({"url":link},{"$set":{"status":status,"updated_at":dat.utcnow()}})
2023-03-07 09:57:47 +00:00
2023-04-03 07:39:10 +00:00
def get_link_features(link):
a, urlpath = courlan.get_host_and_path(link)
2023-04-03 14:37:01 +00:00
features = re.split("[/?&]",urlpath)
#features = re.split("[/?-_=]",urlpath)
res = []
2023-04-05 15:09:42 +00:00
for i,feature in enumerate(features):
2023-04-03 14:37:01 +00:00
if len(feature) < 1:
continue
2023-04-06 11:21:34 +00:00
feature = re.sub("[0-9]","*",feature)
2023-04-05 15:09:42 +00:00
res.append(str(i)+ "-" + feature)
2023-04-03 14:37:01 +00:00
if len(res) < 2:
2023-04-03 07:39:10 +00:00
return None
2023-04-03 14:37:01 +00:00
res = res[:-1]
return res
class LinkClassifier:
def __init__(self):
self.goodcounter = collections.Counter()
self.badcounter = collections.Counter()
self.good_count = 0
self.bad_count = 0
self.alpha = 0.001
2023-04-05 15:09:42 +00:00
def train(self,links):
for i,item in enumerate(links):
2023-04-03 14:37:01 +00:00
link = item["url"]
state = item["status"]
cl = 0
if state == "good":
cl = 1
print(cl,state,link)
features = get_link_features(link)
if features is None:
continue
lf = len(features)
if state == "good":
for feature in features:
self.good_count += 1
self.goodcounter[feature] += 1
else:
for feature in features:
self.bad_count += 1
self.badcounter[feature] += 1
self.bdictsize = len(self.badcounter)
self.gdictsize = len(self.goodcounter)
2023-04-06 10:15:33 +00:00
def test(self,testset):
2023-04-03 14:37:01 +00:00
# eval
gg = 0
2023-04-06 11:21:34 +00:00
true_positive = 0
positive = 0
false_negative = 0
2023-04-06 10:15:33 +00:00
for item in testset:
l = item["url"]
cl = 0
if item["status"] == "good":
cl = 1
2023-04-03 14:37:01 +00:00
pcp = self.classify(l)
r = 0
if pcp > 0:
r = 1
2023-04-06 11:21:34 +00:00
if cl == 1:
if r == 1:
true_positive += 1
positive += 1
if r == 1 and cl == 0:
false_negative += 1
2023-04-03 14:37:01 +00:00
if r == cl:
gg += 1
else:
print("MISS",l,cl,pcp)
print(len(testset))
2023-04-06 11:21:34 +00:00
print("Precision: {}, Recall: {}".format(true_positive/positive,true_positive/(true_positive+false_negative)))
print("Accuracy:")
2023-04-05 15:09:42 +00:00
acc = gg / len(testset)
print(acc)
return acc
2023-04-03 07:39:10 +00:00
2023-04-03 14:37:01 +00:00
def classify(self,link):
2023-04-06 10:15:33 +00:00
if self.good_count == 0 or self.bad_count == 0:
2023-04-05 15:09:42 +00:00
return random.uniform(-0.1,0.1)
2023-04-03 07:39:10 +00:00
features = get_link_features(link)
2023-04-03 14:37:01 +00:00
res = 0
gp = math.log(self.good_count) - math.log(self.good_count + self.bad_count)
bp = math.log(self.bad_count) - math.log(self.good_count + self.bad_count)
2023-04-03 07:39:10 +00:00
if features is None:
2023-04-03 14:37:01 +00:00
return math.exp(gp) - math.exp(bp)
gcc = math.log(self.gdictsize * self.alpha + self.good_count)
bcc = math.log(self.bdictsize * self.alpha + self.bad_count)
goodprob = 0
badprob = 0
2023-04-03 07:39:10 +00:00
for feature in features:
2023-04-06 10:15:33 +00:00
g = math.log((self.goodcounter[feature] + self.alpha)) - gcc
2023-04-03 14:37:01 +00:00
goodprob += g
b = math.log(self.badcounter[feature] + self.alpha) - bcc
badprob += b
pa = math.exp(goodprob + gp)
pb = math.exp(badprob + bp)
2023-04-06 10:15:33 +00:00
return pa - pb #+ random.uniform(-0.001,0.001)
2023-04-03 07:39:10 +00:00
2023-03-29 08:17:57 +00:00
def get_links(db,hostname,status,batch_size):
2023-03-08 09:56:39 +00:00
linkcol = db["links"]
2023-04-05 15:09:42 +00:00
res = linkcol.find({"host":hostname,"status":status},limit=batch_size)
links = []
for item in res:
links.append(item["url"])
print("Got {} {}".format(len(links),status))
return links
2023-03-07 07:58:28 +00:00
2023-04-01 18:44:37 +00:00
def fetch_sitemap_links(start_link):
out = []
navigation_links = trafilatura.sitemaps.sitemap_search(start_link,target_lang=LANGUAGE)
for link in navigation_links:
out.append((link,"frontlink"))
2023-04-05 15:09:42 +00:00
print("Fetched {} sitemap links".format(len(out)))
2023-04-01 18:44:37 +00:00
return out
2023-03-05 14:44:49 +00:00
2023-04-05 15:09:42 +00:00
def fetch_front_links(start_link,rules):
start_link,hostname = courlan.check_url(start_link)
response = fetch_page(start_link)
extracted_links = extract_links([start_link],[response],hostname,rules,"frontlink")
print("Fetched {} frontlinks".format(len(extracted_links)))
return extracted_links
2023-03-11 10:30:30 +00:00
2023-03-12 05:16:47 +00:00
2023-03-17 11:30:53 +00:00
def link_summary(db,hostname):
2023-03-12 05:16:47 +00:00
linkcol = db["links"]
2023-03-17 11:30:53 +00:00
#res = linkcol.distinct("hostname",{"hostname":hostname})
2023-03-12 05:16:47 +00:00
res = linkcol.aggregate([
2023-03-17 11:30:53 +00:00
{"$match":{"host":hostname}},
2023-04-05 15:09:42 +00:00
{"$group":{"_id":"$status",
2023-04-12 12:35:35 +00:00
"count":{"$sum":1},
2023-04-05 15:09:42 +00:00
}
},
2023-03-12 05:16:47 +00:00
])
2023-04-04 12:04:33 +00:00
badcount = 0
goodcount = 0
info = {}
2023-04-05 15:09:42 +00:00
crawled_count = 0
2023-04-06 11:21:34 +00:00
bad_crawl_count = 0
2023-03-12 05:16:47 +00:00
for item in res:
2023-04-05 15:09:42 +00:00
count = item["count"]
st = item["_id"]
print(st,count)
if st == "good":
goodcount += count
2023-05-18 08:23:13 +00:00
if st != "frontlink":
2023-04-05 15:09:42 +00:00
crawled_count += count
2023-04-06 11:21:34 +00:00
if st != "good":
bad_crawl_count += count
2023-04-05 15:09:42 +00:00
info[st] = count
2023-04-06 11:21:34 +00:00
info["crawled_count"] = crawled_count
info["bad_crawl_count"] = bad_crawl_count
2023-04-05 15:09:42 +00:00
baclink_cout = 0
good_prob= 0
if crawled_count > 0:
good_prob = goodcount / crawled_count
2023-04-04 12:04:33 +00:00
info["good_prob"] = good_prob
2023-03-25 13:39:36 +00:00
print(">>>Domain Content")
2023-03-12 08:50:22 +00:00
contentcol = db["content"]
res = contentcol.aggregate([
2023-03-25 13:39:36 +00:00
{"$match":{"host":hostname}},
#{"$project": {"textsum":{"$sum":"$text_size"}}}
2023-03-29 08:17:57 +00:00
{"$group":{"_id":None,
"text_size_sum":{"$sum":"$text_size"},
}
},
2023-03-12 08:50:22 +00:00
])
2023-04-04 12:04:33 +00:00
text_size = 0
2023-03-12 08:50:22 +00:00
for item in res:
2023-04-04 12:04:33 +00:00
text_size = item["text_size_sum"]
2023-04-05 03:44:09 +00:00
good_document_characters = 0
2023-04-05 15:09:42 +00:00
fetch_average_characters = 0
2023-04-05 03:44:09 +00:00
if goodcount > 0:
good_document_characters = text_size / goodcount
2023-04-05 15:09:42 +00:00
fetch_average_characters = text_size / crawled_count
2023-04-04 12:04:33 +00:00
info["total_good_characters"] = text_size
info["average_good_characters"] = good_document_characters
info["average_fetch_characters"] = fetch_average_characters
2023-04-12 12:35:35 +00:00
domaincol = db["domains"]
2023-04-05 15:09:42 +00:00
domaincol.update_one({"host":hostname},{"$set":info},upsert=True)
2023-04-06 10:15:33 +00:00
res = domaincol.find_one({"host":hostname})
print(res)
2023-04-05 15:09:42 +00:00
def sample_links(db,hostname,status,batch_size):
2023-04-08 08:12:31 +00:00
print("Sampling links")
2023-04-05 15:09:42 +00:00
linkcol = db["links"]
2023-05-18 08:23:13 +00:00
res = linkcol.find({"host":hostname,"status": {"$not":{"$in":["frontlink"]}}})
2023-04-05 15:09:42 +00:00
cl = LinkClassifier()
crawled_links = list(res)
crawled_count = len(crawled_links)
prediction_accuracy = 0
2023-04-08 08:12:31 +00:00
if crawled_count > CLASSIFIER_SET_SIZE:
2023-04-05 15:09:42 +00:00
# train on crawled links
2023-04-06 10:15:33 +00:00
trainset,testset = split_train(crawled_links)
cl.train(trainset)
prediction_accuracy = cl.test(testset)
2023-04-11 11:41:28 +00:00
2023-04-08 08:12:31 +00:00
sample_set_size = SAMPLE_SET_SIZE
2023-04-07 13:56:43 +00:00
res = linkcol.find({"host":hostname,"status": status})
2023-04-05 15:09:42 +00:00
predicted_good = 0
2023-04-07 13:56:43 +00:00
visitcounter = collections.Counter()
good_links = []
discover_links = []
2023-04-05 15:09:42 +00:00
for item in res:
2023-04-07 13:56:43 +00:00
link = item["url"]
cll = cl.classify(link)
if cll > 0:
good_links.append(link)
features = get_link_features(link)
discover_links.append(link)
if features is None:
continue
for feature in features:
visitcounter[feature] += 1
2023-04-08 08:12:31 +00:00
mls = int(min(batch_size*(1- DISCOVER_LINK_RATIO),len(good_links)))
2023-04-07 13:56:43 +00:00
random.shuffle(good_links)
2023-04-11 11:41:28 +00:00
links = list(good_links[0:mls])
2023-04-07 13:56:43 +00:00
numdiscover = len(discover_links)
eval_discover_links = []
for link in discover_links:
features = get_link_features(link)
prob = 0
if features is not None:
for feature in features:
2023-04-08 08:12:31 +00:00
c = visitcounter[feature]
prob -= math.log(c) / c
2023-04-07 13:56:43 +00:00
eval_discover_links.append((link,prob))
eval_discover_links.sort(key=lambda x: x[1],reverse=True)
2023-04-08 08:12:31 +00:00
#print(eval_discover_links)
mls = int(min(batch_size * DISCOVER_LINK_RATIO,len(eval_discover_links)))
2023-04-07 13:56:43 +00:00
links += [l[0] for l in eval_discover_links[0:mls]]
2023-04-11 11:41:28 +00:00
return list(set(links))
2023-03-12 05:16:47 +00:00
2023-04-03 07:39:10 +00:00
def domain_summary(db,hostname):
linkcol = db["links"]
#res = linkcol.distinct("hostname",{"hostname":hostname})
# count links
res = linkcol.aggregate([
{"$group":{"_id":"$hostname","text_size_sum":{"$sum":"$text_size"}}},
])
for item in res:
print(item)
2023-03-12 08:50:22 +00:00
2023-04-30 11:54:36 +00:00
def dropdb():
myclient = pymongo.MongoClient(CONNECTION)
print("write name of database to drop")
dbname = sys.stdin.readline().strip()
myclient.drop_database(dbname)
2023-03-12 08:50:22 +00:00
2023-03-12 09:08:21 +00:00
def createdb():
2023-03-12 08:50:22 +00:00
myclient = pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
2023-03-12 05:16:47 +00:00
linkcol = db["links"]
2023-03-12 09:08:21 +00:00
linkcol.create_index("url",unique=True)
linkcol.create_index("host")
2023-03-12 05:16:47 +00:00
contentcol = db["content"]
2023-04-06 10:15:33 +00:00
contentcol.create_index("url")
contentcol.create_index("text_md5",unique=True)
2023-03-12 09:08:21 +00:00
#contentcol.create_index({"paragraph_checksums":1})
2023-03-29 08:17:57 +00:00
contentcol.create_index("host")
2023-03-12 05:16:47 +00:00
htmlcol = db["html"]
2023-04-06 10:15:33 +00:00
htmlcol.create_index("url")
htmlcol.create_index("html_md5",unique=True)
2023-04-04 12:04:33 +00:00
domaincol = db["domains"]
domaincol.create_index("host",unique=True)
2023-04-27 05:29:15 +00:00
domaincol.create_index([("average_fetch_characters",pymongo.DESCENDING)])
2023-04-11 11:41:28 +00:00
batchcol = db["batches"]
batchcol.create_index("host")
batchcol.create_index("created_at")
2023-03-12 05:16:47 +00:00
2023-03-25 12:48:38 +00:00
def parseurl(link):
2023-03-25 13:39:36 +00:00
link,hostname = courlan.check_url(link)
rawrules = trafilatura.fetch_url("https://"+ hostname + "/robots.txt")
print(rawrules)
rules = urllib.robotparser.RobotFileParser()
rules.parse(rawrules.split("\n"))
print(rules.can_fetch("*",link))
print(rules.site_maps())
print(rules.crawl_delay("*"))
2023-03-25 12:48:38 +00:00
html = trafilatura.fetch_url(link,decode=True)
2023-04-07 13:56:43 +00:00
get_bs_links(link,html)
2023-05-16 13:18:01 +00:00
doc = extract_page(link,html)
if doc is not None:
import pprint
pprint.pprint(doc)
2024-03-05 18:58:15 +00:00
links = get_bs_links(link,html)
print(links)
2023-04-11 11:41:28 +00:00
2023-03-25 12:48:38 +00:00
def externaldomains(link):
html = trafilatura.fetch_url(link,decode=True)
external_links = courlan.extract_links(html,link,external_bool=True,language=LANGUAGE)
domains = set()
for l in external_links:
r = courlan.check_url(l)
if r is None:
pass
link,domain = r
domains.add(domain)
for d in domains:
print(d)
2023-04-03 14:37:01 +00:00
def classify(start_link):
myclient = pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
start_link,hostname = courlan.check_url(start_link)
cl = LinkClassifier()
2023-04-06 10:15:33 +00:00
linkcol = db["links"]
2023-05-18 08:23:13 +00:00
res = linkcol.find({"host":hostname,"status": {"$not":{"$in":["frontlink"]}}})
2023-04-06 10:15:33 +00:00
trainset, testset = split_train(res)
cl.train(trainset)
cl.test(testset)
2023-03-16 15:06:07 +00:00
2023-04-17 13:07:58 +00:00
def visit(hostname,filter_content=True):
2023-03-12 08:50:22 +00:00
myclient = pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
2023-04-17 12:32:52 +00:00
batch_size = BATCH_SIZE
2023-04-05 15:09:42 +00:00
rules = fetch_robot(hostname)
2023-04-12 12:35:35 +00:00
start_link = "https://" + hostname
2023-04-05 15:09:42 +00:00
# renew front links
front_links = fetch_front_links(start_link,rules)
index_links(db,front_links)
# start crawling
# frontlinks first
links = sample_links(db,hostname,"frontlink",batch_size)
2023-04-11 11:41:28 +00:00
if start_link not in links:
links.insert(0,start_link)
print("sampled")
print(links)
2023-04-05 15:09:42 +00:00
# index results
2023-04-04 12:04:33 +00:00
print("Processing links")
2023-04-05 15:09:42 +00:00
responses = []
for link in links:
responses.append(fetch_page(link))
2023-04-13 14:11:19 +00:00
extracted_pages = []
for original_link,(final_link,html) in zip(links,responses):
doc = None
assert original_link is not None
doc = extract_page(final_link,html)
extracted_pages.append((original_link,final_link,html,doc))
2023-04-07 13:56:43 +00:00
extracted_links = extract_links(links,responses,hostname,rules,"frontlink")
2023-04-04 12:04:33 +00:00
index_links(db,extracted_links)
2023-04-13 14:11:19 +00:00
final_states = []
docs = []
for original_link,final_link,html,doc in extracted_pages:
2023-04-17 13:07:58 +00:00
status = index_page(db,original_link,final_link,html,doc,filter_content)
2023-04-13 14:11:19 +00:00
final_states.append(status)
docs.append(doc)
save_batch_info(db,hostname,final_states,docs)
2023-03-17 11:30:53 +00:00
link_summary(db,hostname)
2023-03-12 05:56:08 +00:00
2023-04-12 12:35:35 +00:00
def crawl_summary():
myclient = pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
2023-05-16 13:18:01 +00:00
contentcol = db["content"]
res = contentcol.aggregate([
{"$group":{"_id":None,"total_text_size":{"$sum":"$text_size"}}}
])
print(">>>>> Total text size in content")
for item in res:
print(item)
linkscol = db["links"]
# find counts of link statuses
res = linkscol.aggregate([
{"$group":{"_id":"$status","count":{"$sum":1}}}
])
print(">>>>> Link status counts")
for item in res:
print(item["_id"],item["count"])
2023-04-12 12:35:35 +00:00
batchcol = db["batches"]
yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
print(yesterday)
2023-04-12 12:50:18 +00:00
res = batchcol.aggregate([
{"$match":{"created_at":{"$lt": yesterday.utcnow()}}},
{"$group":{"_id":"$host",
2023-04-12 14:39:44 +00:00
"document_count":{"$sum":"$document_count"},
"good_document_count":{"$sum":"$good_document_count"},
2023-04-13 14:16:11 +00:00
"batch_size":{"$sum":"$batch_size"},
2023-04-12 14:39:44 +00:00
"original_text_size":{"$sum":"$original_text_size"},
2023-04-12 12:50:18 +00:00
}
},
2023-04-13 14:11:19 +00:00
{"$sort":{"original_text_size":-1}},
2023-05-16 13:18:01 +00:00
{"$limit":100},
2023-04-12 12:50:18 +00:00
])
2023-04-12 12:35:35 +00:00
print(">>>> Batches")
2023-04-17 12:32:52 +00:00
headers = ["_id","document_count","good_document_count","batch_size","original_text_size"]
2023-04-12 14:39:44 +00:00
print("\t".join(headers))
2023-04-12 12:35:35 +00:00
for item in res:
2023-04-12 14:39:44 +00:00
values = [str(item[x]) for x in headers]
print("\t".join(values))
2023-05-18 08:23:13 +00:00
def _extr(hdoc):
2023-05-16 13:18:01 +00:00
url = hdoc["url"]
html = binascii.a2b_qp(hdoc["quoted_html"])
doc = extract_page(url,html)
return doc
2023-04-13 14:11:19 +00:00
def import_html():
2023-04-13 14:37:32 +00:00
myclient= pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
2023-05-18 08:23:13 +00:00
linkscol = db["links"]
2023-05-16 13:18:01 +00:00
buffer = []
counter = 0
for i,l in enumerate(sys.stdin):
2023-04-13 14:11:19 +00:00
hdoc = json.loads(l)
url = hdoc["url"]
2023-05-18 08:23:13 +00:00
r = linkscol.find_one({"url":url})
if r is not None and r["status"] != "frontlink":
2023-05-16 13:18:01 +00:00
print(">>>>" + str(i) + " copy: " + url)
continue
buffer.append(hdoc)
if len(buffer) < 128:
continue
from multiprocessing import Pool
2023-05-18 08:23:13 +00:00
outs = []
2023-05-16 13:18:01 +00:00
with Pool(8) as p:
2023-05-18 08:23:13 +00:00
outs = p.map(_extr,buffer)
for hdoc,doc in zip(buffer,outs):
if doc is None:
print("bad html" + hdoc["url"])
continue
status = index_page(db,hdoc["url"],hdoc["url"], binascii.a2b_qp(hdoc["quoted_html"]),doc)
counter += 1
print( ">>> " + str(counter) + " " + str(i) + " " + hdoc["url"] + " " + status)
del buffer[:]
2023-05-16 13:18:01 +00:00
2023-04-13 14:11:19 +00:00
2023-04-12 14:39:44 +00:00
def sample_domains():
myclient = pymongo.MongoClient(CONNECTION)
db=myclient[DBNAME]
linkscol = db["links"]
# discover domains
domains = linkscol.distinct("host",filter={"status":"frontlink"})
2023-04-13 07:10:03 +00:00
all_domains = []
2023-04-12 14:39:44 +00:00
for domain in domains:
2023-04-13 07:10:03 +00:00
all_domains.append(domain)
2023-04-17 12:32:52 +00:00
sample_size = min(int(DISCOVER_LINK_RATIO* BATCH_SIZE), len(all_domains))
2023-04-13 07:10:03 +00:00
print(">>> Discover domains {}".format(sample_size))
sample_domains = random.sample(all_domains,sample_size)
2023-04-12 12:35:35 +00:00
domaincol = db["domains"]
2023-04-12 14:39:44 +00:00
# exploit domains
2023-04-13 07:10:03 +00:00
res = domaincol.find({"average_fetch_characters":{"$gt":1000}}).sort("average_fetch_characters",-1)
all_domains = []
2023-04-12 12:35:35 +00:00
for item in res:
2023-04-13 07:10:03 +00:00
all_domains.append(item["host"])
2023-04-17 12:32:52 +00:00
sample_size = min(int((1 - DISCOVER_LINK_RATIO) * BATCH_SIZE),len(all_domains))
2023-04-13 07:10:03 +00:00
print(">>>> Best domains {}".format(sample_size))
sample_domains += random.sample(all_domains,sample_size)
for domain in sample_domains:
print(domain)