Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

First implementation of crawler

Daoud Clarke246c90f75534
diff --git a/crawl.py b/crawl.py
new file mode 100644
index 0000000..cc98084
--- /dev/null
+++ b/crawl.py
@@ -0,0 +1,44 @@
+import logging
+import os
+import time
+from pathlib import Path
+
+import django
+from django.conf import settings
+
+os.environ["DJANGO_SETTINGS_MODULE"] = "mwmbl.settings_crawler"
+
+data_path = Path(settings.DATA_PATH)
+print("Data path", data_path)
+data_path.mkdir(exist_ok=True, parents=True)
+
+django.setup()
+
+
+from mwmbl.indexer.update_urls import record_urls_in_database
+from mwmbl.crawler.retrieve import crawl_batch
+from mwmbl.search_setup import queued_batches as url_queue
+from mwmbl.crawler.batch import HashedBatch
+from mwmbl.indexer.index_batches import index_batches
+
+
+logging.basicConfig(level=logging.INFO)
+
+
+def run():
+ user_id = "test"
+ urls = url_queue.get_batch(user_id)
+ results = crawl_batch(list(urls)[:10], 20)
+ for result in results:
+ print("Result", result)
+
+ js_timestamp = int(time.time() * 1000)
+ batch = HashedBatch.parse_obj({"user_id_hash": user_id, "timestamp": js_timestamp, "items": results})
+ record_urls_in_database([batch], url_queue)
+ index_path = data_path / settings.INDEX_NAME
+
+ index_batches([batch], index_path)
+
+
+if __name__ == "__main__":
+ run()
diff --git a/justext/__init__.py b/justext/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/justext/core.py b/justext/core.py
new file mode 100644
index 0000000..63a1eaa
--- /dev/null
+++ b/justext/core.py
@@ -0,0 +1,401 @@
+# -*- coding: utf-8 -*-
+
+"""
+Copyright (c) 2011 Jan Pomikalek
+
+This software is licensed as described in the file LICENSE.rst.
+"""
+
+from __future__ import absolute_import
+from __future__ import division, print_function, unicode_literals
+
+import re
+from contextlib import contextmanager
+
+import lxml.html
+import lxml.sax
+
+from functools import lru_cache
+
+from lxml.html.clean import Cleaner
+from xml.sax.handler import ContentHandler
+from .paragraph import Paragraph
+from .utils import is_blank
+
+unicode = str
+
+MAX_LINK_DENSITY_DEFAULT = 0.2
+LENGTH_LOW_DEFAULT = 70
+LENGTH_HIGH_DEFAULT = 200
+STOPWORDS_LOW_DEFAULT = 0.30
+STOPWORDS_HIGH_DEFAULT = 0.32
+NO_HEADINGS_DEFAULT = False
+# Short and near-good headings within MAX_HEADING_DISTANCE characters before
+# a good paragraph are classified as good unless --no-headings is specified.
+MAX_HEADING_DISTANCE_DEFAULT = 200
+PARAGRAPH_TAGS = frozenset({
+ 'body', 'blockquote', 'caption', 'center', 'col', 'colgroup', 'dd',
+ 'div', 'dl', 'dt', 'fieldset', 'form', 'legend', 'optgroup', 'option',
+ 'p', 'pre', 'table', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr',
+ 'ul', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
+})
+DEFAULT_ENCODING = 'utf8'
+DEFAULT_ENC_ERRORS = 'replace'
+CHARSET_META_TAG_PATTERN = re.compile(br"""<meta[^>]+charset=["']?([^'"/>\s]+)""", re.IGNORECASE)
+GOOD_OR_BAD = {'good', 'bad'}
+
+
+@contextmanager
+def ignored(*exceptions):
+ try:
+ yield
+ except tuple(exceptions):
+ pass
+
+class JustextError(Exception):
+ "Base class for jusText exceptions."
+
+
+class JustextInvalidOptions(JustextError):
+ pass
+
+
+def html_to_dom(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS):
+ """Converts HTML to DOM."""
+ if isinstance(html, unicode):
+ decoded_html = html
+ # encode HTML for case it's XML with encoding declaration
+ forced_encoding = encoding if encoding else default_encoding
+ html = html.encode(forced_encoding, errors)
+ else:
+ decoded_html = decode_html(html, default_encoding, encoding, errors)
+
+ try:
+ dom = lxml.html.fromstring(decoded_html, parser=lxml.html.HTMLParser())
+ except ValueError:
+ # Unicode strings with encoding declaration are not supported.
+ # for XHTML files with encoding declaration, use the declared encoding
+ dom = lxml.html.fromstring(html, parser=lxml.html.HTMLParser())
+
+ return dom
+
+
+def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS):
+ """
+ Converts a `html` containing an HTML page into Unicode.
+ Tries to guess character encoding from meta tag.
+ """
+ if isinstance(html, unicode):
+ return html
+
+ if encoding:
+ return html.decode(encoding, errors)
+
+ match = CHARSET_META_TAG_PATTERN.search(html)
+ if match:
+ declared_encoding = match.group(1).decode("ASCII")
+ # proceed unknown encoding as if it wasn't found at all
+ with ignored(LookupError):
+ return html.decode(declared_encoding, errors)
+
+ # unknown encoding
+ try:
+ # try UTF-8 first
+ return html.decode("utf8")
+ except UnicodeDecodeError:
+ # try lucky with default encoding
+ try:
+ return html.decode(default_encoding, errors)
+ except UnicodeDecodeError as e:
+ raise JustextError("Unable to decode the HTML to Unicode: " + unicode(e))
+
+
+def preprocessor(dom):
+ "Removes unwanted parts of DOM."
+ options = {
+ "processing_instructions": False,
+ "remove_unknown_tags": False,
+ "safe_attrs_only": False,
+ "page_structure": False,
+ "annoying_tags": False,
+ "frames": False,
+ "meta": False,
+ "links": False,
+ "javascript": False,
+ "scripts": True,
+ "comments": True,
+ "style": True,
+ "embedded": True,
+ "forms": True,
+ "kill_tags": ("head",),
+ }
+ cleaner = Cleaner(**options)
+
+ return cleaner.clean_html(dom)
+
+
+# super(...).__init__() breaks Python 2.7 - TypeError: super() argument 1 must be type, not classobj
+# noinspection PyMissingConstructor
+class ParagraphMaker(ContentHandler):
+ """
+ A class for converting a HTML page represented as a DOM object into a list
+ of paragraphs.
+ """
+
+ @classmethod
+ def make_paragraphs(cls, root):
+ """Converts DOM into paragraphs."""
+ handler = cls()
+ lxml.sax.saxify(root, handler)
+ return handler.paragraphs
+
+ def __init__(self):
+ self.path = PathInfo()
+ self.paragraphs = []
+ self.paragraph = None
+ self.link = False
+ self.br = False
+ self._start_new_pragraph()
+
+ def _start_new_pragraph(self):
+ if self.paragraph and self.paragraph.contains_text():
+ self.paragraphs.append(self.paragraph)
+
+ self.paragraph = Paragraph(self.path)
+
+ def startElementNS(self, name, qname, attrs):
+ name = name[1]
+ self.path.append(name)
+
+ if name in PARAGRAPH_TAGS or (name == "br" and self.br):
+ if name == "br":
+ # the <br><br> is a paragraph separator and should
+ # not be included in the number of tags within the
+ # paragraph
+ self.paragraph.tags_count -= 1
+ self._start_new_pragraph()
+ else:
+ self.br = bool(name == "br")
+ if self.br:
+ self.paragraph.append_text(' ')
+ elif name == 'a':
+ self.link = True
+ try:
+ self.paragraph.links.add(attrs.getValueByQName('href').strip())
+ except KeyError:
+ pass
+ self.paragraph.tags_count += 1
+
+ def endElementNS(self, name, qname):
+ name = name[1]
+ self.path.pop()
+
+ if name in PARAGRAPH_TAGS:
+ self._start_new_pragraph()
+ if name == 'a':
+ self.link = False
+
+ def endDocument(self):
+ self._start_new_pragraph()
+
+ def characters(self, content):
+ if is_blank(content):
+ return
+
+ text = self.paragraph.append_text(content)
+
+ if self.link:
+ self.paragraph.chars_count_in_links += len(text)
+ self.br = False
+
+
+class PathInfo(object):
+ def __init__(self):
+ # list of triples (tag name, order, children)
+ self._elements = []
+
+ @property
+ def dom(self):
+ return ".".join(e[0] for e in self._elements)
+
+ @property
+ def xpath(self):
+ return "/" + "/".join("%s[%d]" % e[:2] for e in self._elements)
+
+ def append(self, tag_name):
+ children = self._get_children()
+ order = children.get(tag_name, 0) + 1
+ children[tag_name] = order
+
+ xpath_part = (tag_name, order, {})
+ self._elements.append(xpath_part)
+
+ return self
+
+ def _get_children(self):
+ if not self._elements:
+ return {}
+
+ return self._elements[-1][2]
+
+ def pop(self):
+ self._elements.pop()
+ return self
+
+
+@lru_cache(maxsize=128) # 100 stoplists
+def define_stoplist(stoplist):
+ "Lower-case all words in stoplist and create frozen set."
+ stoplist = frozenset(w.lower() for w in stoplist)
+ return stoplist
+
+
+def classify_paragraphs(paragraphs, stoplist, length_low=LENGTH_LOW_DEFAULT,
+ length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT,
+ stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT,
+ no_headings=NO_HEADINGS_DEFAULT):
+ "Context-free paragraph classification."
+
+ stoplist = define_stoplist(stoplist)
+ for paragraph in paragraphs:
+ length = len(paragraph)
+ stopword_density = paragraph.stopwords_density(stoplist)
+ link_density = paragraph.links_density()
+ paragraph.heading = bool(not no_headings and paragraph.is_heading)
+
+ if link_density > max_link_density:
+ paragraph.cf_class = 'bad'
+ elif ('\xa9' in paragraph.text) or ('&copy' in paragraph.text):
+ paragraph.cf_class = 'bad'
+ elif 'select' in paragraph.dom_path:
+ paragraph.cf_class = 'bad'
+ elif length < length_low:
+ if paragraph.chars_count_in_links > 0:
+ paragraph.cf_class = 'bad'
+ else:
+ paragraph.cf_class = 'short'
+ elif stopword_density >= stopwords_high:
+ if length > length_high:
+ paragraph.cf_class = 'good'
+ else:
+ paragraph.cf_class = 'neargood'
+ elif stopword_density >= stopwords_low:
+ paragraph.cf_class = 'neargood'
+ else:
+ paragraph.cf_class = 'bad'
+
+
+def _get_neighbour(i, paragraphs, ignore_neargood, inc, boundary):
+ while i + inc != boundary:
+ i += inc
+ c = paragraphs[i].class_type
+ if c in GOOD_OR_BAD:
+ return c
+ if c == 'neargood' and not ignore_neargood:
+ return c
+ return 'bad'
+
+
+def get_prev_neighbour(i, paragraphs, ignore_neargood):
+ """
+ Return the class of the paragraph at the top end of the short/neargood
+ paragraphs block. If ignore_neargood is True, than only 'bad' or 'good'
+ can be returned, otherwise 'neargood' can be returned, too.
+ """
+ return _get_neighbour(i, paragraphs, ignore_neargood, -1, -1)
+
+
+def get_next_neighbour(i, paragraphs, ignore_neargood):
+ """
+ Return the class of the paragraph at the bottom end of the short/neargood
+ paragraphs block. If ignore_neargood is True, than only 'bad' or 'good'
+ can be returned, otherwise 'neargood' can be returned, too.
+ """
+ return _get_neighbour(i, paragraphs, ignore_neargood, 1, len(paragraphs))
+
+
+def revise_paragraph_classification(paragraphs, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT):
+ """
+ Context-sensitive paragraph classification. Assumes that classify_pragraphs
+ has already been called.
+ """
+
+ # good headings
+ for i, paragraph in enumerate(paragraphs):
+ # copy classes
+ paragraph.class_type = paragraph.cf_class
+ if not (paragraph.heading and paragraph.class_type == 'short'):
+ continue
+ j = i + 1
+ distance = 0
+ while j < len(paragraphs) and distance <= max_heading_distance:
+ if paragraphs[j].class_type == 'good':
+ paragraph.class_type = 'neargood'
+ break
+ distance += len(paragraphs[j].text)
+ j += 1
+
+ # classify short
+ new_classes = {}
+ for i, paragraph in enumerate(paragraphs):
+ if paragraph.class_type != 'short':
+ continue
+ prev_neighbour = get_prev_neighbour(i, paragraphs, ignore_neargood=True)
+ next_neighbour = get_next_neighbour(i, paragraphs, ignore_neargood=True)
+ if prev_neighbour == 'good' and next_neighbour == 'good':
+ new_classes[i] = 'good'
+ elif prev_neighbour == 'bad' and next_neighbour == 'bad':
+ new_classes[i] = 'bad'
+ # it must be set(['good', 'bad'])
+ elif (prev_neighbour == 'bad' and get_prev_neighbour(i, paragraphs, ignore_neargood=False) == 'neargood') or \
+ (next_neighbour == 'bad' and get_next_neighbour(i, paragraphs, ignore_neargood=False) == 'neargood'):
+ new_classes[i] = 'good'
+ else:
+ new_classes[i] = 'bad'
+
+ for i, c in new_classes.items():
+ paragraphs[i].class_type = c
+
+ # revise neargood
+ for i, paragraph in enumerate(paragraphs):
+ if paragraph.class_type != 'neargood':
+ continue
+ prev_neighbour = get_prev_neighbour(i, paragraphs, ignore_neargood=True)
+ next_neighbour = get_next_neighbour(i, paragraphs, ignore_neargood=True)
+ if (prev_neighbour, next_neighbour) == ('bad', 'bad'):
+ paragraph.class_type = 'bad'
+ else:
+ paragraph.class_type = 'good'
+
+ # more good headings
+ for i, paragraph in enumerate(paragraphs):
+ if not (paragraph.heading and paragraph.class_type == 'bad' and paragraph.cf_class != 'bad'):
+ continue
+ j = i + 1
+ distance = 0
+ while j < len(paragraphs) and distance <= max_heading_distance:
+ if paragraphs[j].class_type == 'good':
+ paragraph.class_type = 'good'
+ break
+ distance += len(paragraphs[j].text)
+ j += 1
+
+
+def justext_from_dom(dom, stoplist, length_low=LENGTH_LOW_DEFAULT,
+ length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT,
+ stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT,
+ max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT, no_headings=NO_HEADINGS_DEFAULT,
+ preprocessor=preprocessor):
+ """
+ Converts an HTML page into a list of classified paragraphs. Each paragraph
+ is represented as instance of class ˙˙justext.paragraph.Paragraph˙˙.
+ """
+ dom_preprocessed = preprocessor(dom)
+
+ paragraphs = ParagraphMaker.make_paragraphs(dom_preprocessed)
+
+ classify_paragraphs(paragraphs, stoplist, length_low, length_high,
+ stopwords_low, stopwords_high, max_link_density, no_headings)
+ revise_paragraph_classification(paragraphs, max_heading_distance)
+
+ return paragraphs
diff --git a/justext/paragraph.py b/justext/paragraph.py
new file mode 100644
index 0000000..9d5ebde
--- /dev/null
+++ b/justext/paragraph.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import
+from __future__ import division, print_function, unicode_literals
+
+import re
+
+from .utils import normalize_whitespace
+
+
+HEADINGS_PATTERN = re.compile(r"\bh\d\b")
+
+
+class Paragraph(object):
+ """Object representing one block of text in HTML."""
+ def __init__(self, path):
+ self.dom_path = path.dom
+ self.xpath = path.xpath
+ self.text_nodes = []
+ self.chars_count_in_links = 0
+ self.tags_count = 0
+ self.class_type = "" # short | neargood | good | bad
+ self.links: set[str] = set()
+
+ @property
+ def is_heading(self):
+ return bool(HEADINGS_PATTERN.search(self.dom_path))
+
+ @property
+ def is_boilerplate(self):
+ return self.class_type != "good"
+
+ @property
+ def text(self):
+ text = "".join(self.text_nodes)
+ return normalize_whitespace(text.strip())
+
+ def __len__(self):
+ return len(self.text)
+
+ @property
+ def words_count(self):
+ return len(self.text.split())
+
+ def contains_text(self):
+ return bool(self.text_nodes)
+
+ def append_text(self, text):
+ text = normalize_whitespace(text)
+ self.text_nodes.append(text)
+ return text
+
+ def stopwords_count(self, stopwords):
+ return sum(word.lower() in stopwords for word in self.text.split())
+
+ def stopwords_density(self, stopwords):
+ if self.words_count == 0:
+ return 0
+
+ return self.stopwords_count(stopwords) / self.words_count
+
+ def links_density(self):
+ text_length = len(self.text)
+ if text_length == 0:
+ return 0
+
+ return self.chars_count_in_links / text_length
diff --git a/justext/stoplists/English.txt b/justext/stoplists/English.txt
new file mode 100644
index 0000000..3a89da3
--- /dev/null
+++ b/justext/stoplists/English.txt
@@ -0,0 +1,503 @@
+the
+of
+and
+in
+to
+a
+was
+is
+The
+for
+as
+on
+with
+by
+that
+from
+at
+his
+an
+he
+In
+are
+were
+which
+be
+has
+He
+it
+or
+also
+had
+first
+It
+their
+not
+but
+have
+who
+its
+one
+this
+been
+her
+two
+they
+other
+into
+after
+all
+when
+more
+This
+only
+would
+A
+she
+New
+most
+can
+over
+during
+where
+new
+used
+such
+up
+between
+many
+made
+some
+than
+out
+United
+known
+about
+time
+then
+became
+under
+"The
+being
+part
+there
+him
+years
+three
+through
+On
+including
+later
+will
+American
+both
+After
+until
+before
+She
+well
+no
+against
+while
+called
+second
+As
+several
+University
+number
+name
+these
+played
+early
+may
+They
+World
+His
+located
+National
+same
+them
+released
+There
+de
+area
+use
+work
+any
+school
+since
+team
+age
+so
+John
+won
+people
+began
+each
+year
+population
+now
+family
+film
+found
+city
+British
+four
+album
+could
+very
+However,
+South
+named
+At
+around
+took
+former
+because
+series
+For
+States
+did
+within
+state
+end
+based
+May
+I
+local
+held
+September
+still
+often
+those
+member
+small
+town
+along
+back
+School
+large
+January
+June
+group
+served
+March
+high
+own
+During
+North
+July
+October
+if
+like
+following
+built
+August
+April
+music
+born
+village
+game
+due
+last
+place
+home
+State
+left
+major
+set
+include
+U.S.
+much
+December
+November
+received
+When
+York
+main
+War
+public
+band
+(born
+season
+published
+even
+different
+original
+members
+station
+single
+government
+another
+near
+what
+died
+moved
+become
+just
+February
+company
+included
+song
+came
+led
+late
+form
+national
+make
+went
+These
+off
+show
+French
+five
+system
+few
+various
+given
+best
+English
+City
+long
+third
+among
+every
+West
+German
+using
+do
+said
+started
+currently
+having
+down
+next
+order
+One
+final
+take
+species
+established
+created
+life
+play
+line
+building
+History.
+political
+without
+support
+written
+district
+per
+produced
+High
+popular
+League
+service
+football
+considered
+St.
+way
+returned
+International
+book
+again
+although
+important
+living
+role
+River
+students
+married
+son
+top
+worked
+San
+continued
+however,
+founded
+joined
+appeared
+total
+power
+By
+record
+College
+side
+William
+title
+death
+County,
+years.
+career
+never
+From
+north
+club
+County
+military
+version
+European
+According
+old
+While
+six
+day
+average
+television
+similar
+world
+general
+million
+With
+Some
+water
+formed
+international
+usually
+current
+though
+south
+General
+time,
+community
+East
+House
+land
+Although
+George
+making
+player
+playing
+President
+development
+James
+developed
+common
+should
+great
+century
+does
+further
+run
+working
+largest
+recorded
+All
+lost
+must
+elected
+history
+seen
+live
+opened
+short
+taken
+once
+professional
+production
+point
+head
+children
+throughout
+games
+period
+himself
+originally
+term
+control
+available
+less
+King
+Its
+modern
+position
+eventually
+across
+Royal
+works
+site
+young
+wrote
+income
+house
+David
+Other
+Since
+how
+able
+full
+war
+Australian
+Air
+London
+Army
+includes
+law
+designed
+sold
+featured
+appointed
+business
+An
+get
+either
+Japanese
+program
+US
+Canadian
+father
+lead
+approximately
+performed
+leading
+radio
+upon
+remained
+famous
+Indian
+we
+Robert
+First
+help
+west
+gave
+announced
+men
+result
+times
+field
+you
+right
+east
+almost
+country
+story
+Church
+followed
+good
+days
+signed
+features
+together
+described
+research
+sent
+open
+special
+close
+see
+To
+character
+social
+miles
+rather
+life.
+Council
+Western
+(the
+party
+official
+years,
+church
diff --git a/justext/utils.py b/justext/utils.py
new file mode 100644
index 0000000..42e5074
--- /dev/null
+++ b/justext/utils.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import
+from __future__ import division, print_function, unicode_literals
+
+import re
+import os
+import sys
+import pkgutil
+
+MULTIPLE_WHITESPACE_PATTERN = re.compile(r"\s+", re.UNICODE)
+
+
+def normalize_whitespace(text):
+ """
+ Translates multiple whitespace into single space character.
+ If there is at least one new line character chunk is replaced
+ by single LF (Unix new line) character.
+ """
+ return MULTIPLE_WHITESPACE_PATTERN.sub(_replace_whitespace, text)
+
+
+def _replace_whitespace(match):
+ """Normalize all spacing characters that aren't a newline to a space."""
+ text = match.group()
+ return "\n" if "\n" in text or "\r" in text else " "
+
+
+def is_blank(string):
+ """
+ Returns `True` if string contains only white-space characters
+ or is empty. Otherwise `False` is returned.
+ """
+ return not string or string.isspace()
+
+
+def get_stoplists():
+ """Returns a collection of built-in stop-lists."""
+ path_to_stoplists = os.path.dirname(sys.modules["justext"].__file__)
+ path_to_stoplists = os.path.join(path_to_stoplists, "stoplists")
+
+ stoplist_names = []
+ for filename in os.listdir(path_to_stoplists):
+ name, extension = os.path.splitext(filename)
+ if extension == ".txt":
+ stoplist_names.append(name)
+
+ return frozenset(stoplist_names)
+
+
+def get_stoplist(language):
+ """Returns an built-in stop-list for the language as a set of words."""
+ file_path = os.path.join("stoplists", "%s.txt" % language)
+ try:
+ stopwords = pkgutil.get_data("justext", file_path)
+ except IOError:
+ raise ValueError(
+ "Stoplist for language '%s' is missing. "
+ "Please use function 'get_stoplists' for complete list of stoplists "
+ "and feel free to contribute by your own stoplist." % language
+ )
+
+ return frozenset(w.decode("utf8").lower() for w in stopwords.splitlines())
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index 0b867c9..fe72ca1 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -8,25 +8,32 @@ from mwmbl.database import Database
from mwmbl.indexer.indexdb import IndexDatabase
+def create_index():
+ # Imports here to avoid AppRegistryNotReady exception
+ from mwmbl.tinysearchengine.indexer import TinyIndex, Document, PAGE_SIZE
+ index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME
+ try:
+ existing_index = TinyIndex(item_factory=Document, index_path=index_path)
+ if existing_index.page_size != PAGE_SIZE or existing_index.num_pages != settings.NUM_PAGES:
+ raise ValueError(f"Existing index page sizes ({existing_index.page_size}) or number of pages "
+ f"({existing_index.num_pages}) do not match")
+ except FileNotFoundError:
+ print("Creating a new index")
+ TinyIndex.create(item_factory=Document, index_path=index_path, num_pages=settings.NUM_PAGES,
+ page_size=PAGE_SIZE)
+
+
+def create_index_db():
+ with Database() as db:
+ index_db = IndexDatabase(db.connection)
+ index_db.create_tables()
+
+
class MwmblConfig(AppConfig):
name = "mwmbl"
verbose_name = "Mwmbl Application"
def ready(self):
- # Imports here to avoid AppRegistryNotReady exception
- from mwmbl.tinysearchengine.indexer import TinyIndex, Document, PAGE_SIZE
-
- index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME
- try:
- existing_index = TinyIndex(item_factory=Document, index_path=index_path)
- if existing_index.page_size != PAGE_SIZE or existing_index.num_pages != settings.NUM_PAGES:
- raise ValueError(f"Existing index page sizes ({existing_index.page_size}) or number of pages "
- f"({existing_index.num_pages}) do not match")
- except FileNotFoundError:
- print("Creating a new index")
- TinyIndex.create(item_factory=Document, index_path=index_path, num_pages=settings.NUM_PAGES,
- page_size=PAGE_SIZE)
-
- with Database() as db:
- index_db = IndexDatabase(db.connection)
- index_db.create_tables()
+ create_index()
+ if settings.SETUP_DATABASE:
+ create_index_db()
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.py
new file mode 100644
index 0000000..e8e7377
--- /dev/null
+++ b/mwmbl/crawler/retrieve.py
@@ -0,0 +1,267 @@
+import re
+import re
+import time
+from logging import getLogger
+from multiprocessing.pool import ThreadPool
+from ssl import SSLCertVerificationError
+from urllib.parse import urlparse, urlunsplit, urljoin
+from urllib.robotparser import RobotFileParser
+
+import requests
+from justext import core, utils
+from justext.core import html_to_dom
+from justext.paragraph import Paragraph
+from requests import ReadTimeout
+from urllib3.exceptions import NewConnectionError, MaxRetryError
+
+ALLOWED_EXCEPTIONS = (ValueError, ConnectionError, ReadTimeout, TimeoutError,
+ OSError, NewConnectionError, MaxRetryError, SSLCertVerificationError)
+
+POST_BATCH_URL = '/api/v1/crawler/batches/'
+POST_NEW_BATCH_URL = '/api/v1/crawler/batches/new'
+
+TIMEOUT_SECONDS = 3
+MAX_FETCH_SIZE = 1024*1024
+MAX_URL_LENGTH = 150
+BAD_URL_REGEX = re.compile(r'\/\/localhost\b|\.jpg$|\.png$|\.js$|\.gz$|\.zip$|\.pdf$|\.bz2$|\.ipynb$|\.py$')
+MAX_NEW_LINKS = 50
+MAX_EXTRA_LINKS = 50
+NUM_TITLE_CHARS = 65
+NUM_EXTRACT_CHARS = 155
+DEFAULT_ENCODING = 'utf8'
+DEFAULT_ENC_ERRORS = 'replace'
+MAX_SITE_URLS = 100
+
+
+logger = getLogger(__name__)
+
+
+def fetch(url):
+ """
+ Fetch with a maximum timeout and maximum fetch size to avoid big pages bringing us down.
+
+ https://stackoverflow.com/a/22347526
+ """
+
+ r = requests.get(url, stream=True, timeout=TIMEOUT_SECONDS)
+
+ size = 0
+ start = time.time()
+
+ content = b""
+ for chunk in r.iter_content(1024):
+ if time.time() - start > TIMEOUT_SECONDS:
+ raise ValueError('Timeout reached')
+
+ content += chunk
+
+ size += len(chunk)
+ if size > MAX_FETCH_SIZE:
+ logger.debug(f"Maximum size reached for URL {url}")
+ break
+
+ return r.status_code, content
+
+
+def robots_allowed(url):
+ try:
+ parsed_url = urlparse(url)
+ except ValueError:
+ logger.info(f"Unable to parse URL: {url}")
+ return False
+
+ if parsed_url.path.rstrip('/') == '' and parsed_url.query == '':
+ logger.debug(f"Allowing root domain for URL: {url}")
+ return True
+
+ robots_url = urlunsplit((parsed_url.scheme, parsed_url.netloc, 'robots.txt', '', ''))
+
+ parse_robots = RobotFileParser(robots_url)
+
+ try:
+ status_code, content = fetch(robots_url)
+ except ALLOWED_EXCEPTIONS as e:
+ logger.debug(f"Robots error: {robots_url}, {e}")
+ return True
+
+ if status_code != 200:
+ logger.debug(f"Robots status code: {status_code}")
+ return True
+
+ decoded = None
+ for encoding in ['utf-8', 'iso-8859-1']:
+ try:
+ decoded = content.decode(encoding).splitlines()
+ break
+ except UnicodeDecodeError:
+ pass
+
+ if decoded is None:
+ logger.info(f"Unable to decode robots file {robots_url}")
+ return True
+
+ parse_robots.parse(decoded)
+ allowed = parse_robots.can_fetch('Mwmbl', url)
+ logger.debug(f"Robots allowed for {url}: {allowed}")
+ return allowed
+
+
+def get_new_links(paragraphs: list[Paragraph], current_url):
+ new_links = set()
+ extra_links = set()
+ parsed_url = urlparse(current_url)
+ base_url = urlunsplit((parsed_url.scheme, parsed_url.netloc, "", "", ""))
+
+ for paragraph in paragraphs:
+ if len(paragraph.links) > 0:
+ logger.debug(f"Paragraph: {paragraph.text, paragraph.links}")
+ for link in paragraph.links:
+ if not link.startswith("http"):
+ if "://" in link:
+ logger.debug(f"Bad URL: {link}")
+ continue
+
+ # Relative link
+ if link.startswith("/"):
+ link = urljoin(base_url, link)
+ else:
+ link = urljoin(current_url, link)
+
+ if link.startswith('http') and len(link) <= MAX_URL_LENGTH:
+ if BAD_URL_REGEX.search(link):
+ logger.debug(f"Found bad URL: {link}")
+ continue
+ try:
+ parsed_url = urlparse(link)
+ except ValueError:
+ logger.info(f"Unable to parse link {link}")
+ continue
+ url_without_hash = urlunsplit((parsed_url.scheme, parsed_url.netloc, parsed_url.path, parsed_url.query, ''))
+ if paragraph.class_type == 'good':
+ if len(new_links) < MAX_NEW_LINKS:
+ new_links.add(url_without_hash)
+ else:
+ if len(extra_links) < MAX_EXTRA_LINKS and url_without_hash not in new_links:
+ extra_links.add(url_without_hash)
+ if len(new_links) >= MAX_NEW_LINKS and len(extra_links) >= MAX_EXTRA_LINKS:
+ return new_links, extra_links
+ return new_links, extra_links
+
+
+def crawl_url(url):
+ logger.info(f"Crawling URL {url}")
+ js_timestamp = int(time.time() * 1000)
+ allowed = robots_allowed(url)
+ if not allowed:
+ return {
+ 'url': url,
+ 'status': None,
+ 'timestamp': js_timestamp,
+ 'content': None,
+ 'error': {
+ 'name': 'RobotsDenied',
+ 'message': 'Robots do not allow this URL',
+ }
+ }
+
+ try:
+ status_code, content = fetch(url)
+ except ALLOWED_EXCEPTIONS as e:
+ logger.debug(f"Exception crawling URl {url}: {e}")
+ return {
+ 'url': url,
+ 'status': None,
+ 'timestamp': js_timestamp,
+ 'content': None,
+ 'error': {
+ 'name': 'AbortError',
+ 'message': str(e),
+ }
+ }
+
+ if len(content) == 0:
+ return {
+ 'url': url,
+ 'status': status_code,
+ 'timestamp': js_timestamp,
+ 'content': None,
+ 'error': {
+ 'name': 'NoResponseText',
+ 'message': 'No response found',
+ }
+ }
+
+ try:
+ dom = html_to_dom(content, DEFAULT_ENCODING, None, DEFAULT_ENC_ERRORS)
+ except Exception as e:
+ logger.exception(f"Error parsing dom: {url}")
+ return {
+ 'url': url,
+ 'status': status_code,
+ 'timestamp': js_timestamp,
+ 'content': None,
+ 'error': {
+ 'name': e.__class__.__name__,
+ 'message': str(e),
+ }
+ }
+
+ title_element = dom.xpath("//title")
+ title = ""
+ if len(title_element) > 0:
+ title_text = title_element[0].text
+ if title_text is not None:
+ title = title_text.strip()
+
+ if len(title) > NUM_TITLE_CHARS:
+ title = title[:NUM_TITLE_CHARS - 1] + '…'
+
+ try:
+ paragraphs = core.justext_from_dom(dom, utils.get_stoplist("English"))
+ except Exception as e:
+ logger.exception("Error parsing paragraphs")
+ return {
+ 'url': url,
+ 'status': status_code,
+ 'timestamp': js_timestamp,
+ 'content': None,
+ 'error': {
+ 'name': e.__class__.__name__,
+ 'message': str(e),
+ }
+ }
+
+ new_links, extra_links = get_new_links(paragraphs, url)
+ logger.debug(f"Got new links {new_links}")
+ logger.debug(f"Got extra links {extra_links}")
+
+ extract = ''
+ for paragraph in paragraphs:
+ if paragraph.class_type != 'good':
+ continue
+ extract += ' ' + paragraph.text.strip()
+ if len(extract) > NUM_EXTRACT_CHARS:
+ extract = extract[:NUM_EXTRACT_CHARS - 1] + '…'
+ break
+
+ return {
+ 'url': url,
+ 'status': status_code,
+ 'timestamp': js_timestamp,
+ 'content': {
+ 'title': title,
+ 'extract': extract,
+ 'links': sorted(new_links),
+ 'extra_links': sorted(extra_links),
+ },
+ 'error': None
+ }
+
+
+def crawl_batch(batch, num_threads):
+ with ThreadPool(num_threads) as pool:
+ result = pool.map(crawl_url, batch)
+ return result
+
+
+
diff --git a/mwmbl/crawler/urls.py b/mwmbl/crawler/urls.py
index 0ffa5b1..bae07e0 100644
--- a/mwmbl/crawler/urls.py
+++ b/mwmbl/crawler/urls.py
@@ -57,24 +57,29 @@ class URLDatabase:
def __enter__(self):
month_date = datetime.utcnow()
+
for i in range(3):
# Start from current month and go back two months
month_date = datetime(month_date.year, month_date.month, 1)
urls_path = settings.URLS_BLOOM_FILTER_PATH.format(month=month_date.month, year=month_date.year)
- try:
- self.urls[month_date] = BloomFilter.open(urls_path)
- except FileNotFoundError:
- if i == 0:
- logger.info("No existing bloom filter found, creating a new one")
- self.urls[month_date] = BloomFilter(settings.NUM_URLS_IN_BLOOM_FILTER, 1e-6, urls_path, perm=0o666)
- else:
- logger.info("No existing bloom filter found, using fallback")
- month_date -= timedelta(days=1)
-
- self.urls[datetime(2024, 1, 1)] = BloomFilter.open(settings.URLS_BLOOM_FILTER_FALLBACK_PATH)
+ month_date = self._construct_bloom_filter(i, month_date, urls_path)
+
+ self._construct_bloom_filter(3, datetime(2024, 1, 1), settings.URLS_BLOOM_FILTER_FALLBACK_PATH)
logger.info(f"Initialised URL crawled DB with dates {self.urls.keys()}")
return self
+ def _construct_bloom_filter(self, i, month_date, urls_path):
+ try:
+ self.urls[month_date] = BloomFilter.open(urls_path)
+ except FileNotFoundError:
+ if i == 0:
+ logger.info("No existing bloom filter found, creating a new one")
+ self.urls[month_date] = BloomFilter(settings.NUM_URLS_IN_BLOOM_FILTER, 1e-6, urls_path, perm=0o666)
+ else:
+ logger.info("No existing bloom filter found, using fallback")
+ month_date -= timedelta(days=1)
+ return month_date
+
def __exit__(self, exc_type, exc_val, exc_tb):
for month_date, bloom_filter in self.urls.items():
bloom_filter.close()
diff --git a/mwmbl/database.py b/mwmbl/database.py
index bafb786..c55cd11 100644
--- a/mwmbl/database.py
+++ b/mwmbl/database.py
@@ -1,14 +1,13 @@
+from django.conf import settings
from psycopg2 import connect
-from mwmbl.settings import DATABASE_URL
-
class Database:
def __init__(self):
self.connection = None
def __enter__(self):
- self.connection = connect(DATABASE_URL)
+ self.connection = connect(settings.DATABASE_URL)
self.connection.set_session(autocommit=True)
return self
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index 74e0fb8..e1c3621 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -2,6 +2,7 @@
Index batches that are stored locally.
"""
from collections import defaultdict
+from datetime import datetime
from logging import getLogger
from typing import Collection, Iterable
@@ -39,10 +40,13 @@ def get_url_score(url):
def index_batches(batch_data: Collection[HashedBatch], index_path: str):
+ start_time = datetime.utcnow()
document_tuples = list(get_documents_from_batches(batch_data))
documents = [Document(title, url, extract, get_url_score(url)) for title, url, extract in document_tuples]
page_documents = preprocess_documents(documents, index_path)
index_pages(index_path, page_documents)
+ end_time = datetime.utcnow()
+ logger.info(f"Indexing took {end_time - start_time}")
def index_pages(index_path: str, page_documents: dict[int, list[Document]]):
diff --git a/mwmbl/indexer/update_urls.py b/mwmbl/indexer/update_urls.py
index c17dc58..9c0bd34 100644
--- a/mwmbl/indexer/update_urls.py
+++ b/mwmbl/indexer/update_urls.py
@@ -40,9 +40,9 @@ def run(batch_cache: BatchCache, new_item_queue: RedisURLQueue, num_batches: int
def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: RedisURLQueue):
- start = datetime.now()
+ start = datetime.utcnow()
blacklist_domains = get_blacklist_domains()
- blacklist_retrieval_time = datetime.now() - start
+ blacklist_retrieval_time = datetime.utcnow() - start
logger.info(f"Recording URLs in database for {len(batches)} batches, with {len(blacklist_domains)} blacklist "
f"domains, retrieved in {blacklist_retrieval_time.total_seconds()} seconds")
@@ -79,6 +79,9 @@ def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Re
for source_domain, target_domains in domain_links.items():
domain_link_db.update_domain_links(source_domain, target_domains)
+ end = datetime.utcnow()
+ logger.info(f"Recorded URLs in database in {end - start}")
+
def _add_found_urls_to_db_and_queue(found_urls, new_item_queue):
with URLDatabase() as url_db:
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 547ec7b..7cb7cde 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -187,3 +187,5 @@ CACHES = {
"KEY_PREFIX": "c_",
}
}
+
+SETUP_DATABASE = True
diff --git a/mwmbl/settings_crawler.py b/mwmbl/settings_crawler.py
new file mode 100644
index 0000000..e20f053
--- /dev/null
+++ b/mwmbl/settings_crawler.py
@@ -0,0 +1,21 @@
+import os
+
+from mwmbl.settings_dev import *
+
+
+DATA_PATH = f"{os.environ['HOME']}/.mwmbl"
+INDEX_NAME = 'crawl-index.tinysearch'
+
+# Index of around 400Mb = 4096b * 100_000
+NUM_PAGES = 100_000
+
+URLS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "urls-{year}-{month}.bloom")
+URLS_BLOOM_FILTER_FALLBACK_PATH = str(Path(DATA_PATH) / "urls.bloom")
+NUM_URLS_IN_BLOOM_FILTER = 10_000_000
+
+DOMAIN_LINKS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "links_{domain_group}.bloom")
+NUM_DOMAINS_IN_BLOOM_FILTER = 100_000
+
+REQUEST_CACHE_PATH = f"{DATA_PATH}/request_cache.sqlite"
+
+SETUP_DATABASE = False
diff --git a/poetry.lock b/poetry.lock
index 0762427..06c979d 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -836,20 +836,6 @@ files = [
{file = "joblib-1.4.2.tar.gz", hash = "sha256:2382c5816b2636fbd20a09e0f4e9dad4736765fdfb7dca582943b9c1366b3f0e"},
]
-[[package]]
-name = "justext"
-version = "3.0.0"
-description = "Heuristic based boilerplate removal tool"
-optional = false
-python-versions = "*"
-files = [
- {file = "jusText-3.0.0-py2.py3-none-any.whl", hash = "sha256:86b48f5b1d99505acd072f5831def6cd3f1306043651c524a1c609e62e3544e4"},
- {file = "jusText-3.0.0.tar.gz", hash = "sha256:7640e248218795f6be65f6c35fe697325a3280fcb4675d1525bcdff2b86faadf"},
-]
-
-[package.dependencies]
-lxml = ">=4.4.2"
-
[[package]]
name = "langcodes"
version = "3.4.0"
@@ -3010,4 +2996,4 @@ indexer = ["Levenshtein", "beautifulsoup4", "idna", "langdetect", "pyarrow", "py
[metadata]
lock-version = "2.0"
python-versions = ">=3.10,<3.11"
-content-hash = "d44a4f54a5a5ee4fd70ce03c11bd761dc2e8af94de206fd0423dc1fb128f0783"
+content-hash = "5e727460fd3c6e62a73ab5c878da7c25e9d3ffdf9ad217861c8c312bf9b8a548"
diff --git a/pyproject.toml b/pyproject.toml
index 0e0c107..db56979 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -20,7 +20,6 @@ psycopg2-binary = "^2.9.3"
spacy = "==3.2.1"
pytest = "^7.2.1"
pytest-mock = "^3.10.0"
-jusText = "==3.0.0"
# Optional dependencies do not get installed by default. Look under tool.poetry.extras section
# to see which extras to use.