Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Score documents properly

Daoud Clarkeb0eb9b7c5460
diff --git a/crawl.py b/crawl.py
index 9b3ca9c..8b01074 100644
--- a/crawl.py
+++ b/crawl.py
@@ -25,17 +25,19 @@ from mwmbl.indexer.index_batches import index_batches
logger = logging.getLogger(__name__)
-logging.basicConfig(level=logging.INFO)
+FORMAT = "%(process)d:%(levelname)s:%(name)s:%(message)s"
+logging.basicConfig(level=logging.INFO, format=FORMAT)
BATCH_QUEUE_KEY = "batch-queue"
def run():
- for i in range(10):
- process = Process(target=process_batch_continuously())
- process.start()
+ # for i in range(10):
+ # process = Process(target=process_batch_continuously)
+ # process.start()
+ # time.sleep(1)
- index_process = Process(target=run_indexing)
+ index_process = Process(target=run_indexing_continuously)
index_process.start()
@@ -51,7 +53,7 @@ def process_batch_continuously():
def process_batch():
user_id = "test"
urls = url_queue.get_batch(user_id)
- results = crawl_batch(list(urls)[:10], 20)
+ results = crawl_batch(urls, 20)
for result in results:
print("Result", result)
js_timestamp = int(time.time() * 1000)
@@ -64,18 +66,26 @@ def process_batch():
redis.rpush(BATCH_QUEUE_KEY, batch_json)
+def run_indexing_continuously():
+ while True:
+ try:
+ run_indexing()
+ except Exception:
+ logger.exception("Error running indexing")
+ time.sleep(10)
+
+
def run_indexing():
redis = Redis(host='localhost', port=6379, decode_responses=True)
index_path = data_path / settings.INDEX_NAME
- while True:
- batch_jsons = redis.lpop(BATCH_QUEUE_KEY, 1000)
- logger.info(f"Got {len(batch_jsons)} batches to index")
- if batch_jsons is None:
- logger.info("No more batches to index. Sleeping for 10 seconds.")
- time.sleep(10)
- continue
- batches = [HashedBatch.parse_raw(b) for b in batch_jsons]
- index_batches(batches, index_path)
+ batch_jsons = redis.lpop(BATCH_QUEUE_KEY, 1)
+ if batch_jsons is None:
+ logger.info("No more batches to index. Sleeping for 10 seconds.")
+ time.sleep(10)
+ return
+ logger.info(f"Got {len(batch_jsons)} batches to index")
+ batches = [HashedBatch.parse_raw(b) for b in batch_jsons]
+ index_batches(batches, index_path)
if __name__ == "__main__":
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.py
index e8e7377..303fcfb 100644
--- a/mwmbl/crawler/retrieve.py
+++ b/mwmbl/crawler/retrieve.py
@@ -114,7 +114,6 @@ def get_new_links(paragraphs: list[Paragraph], current_url):
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:
diff --git a/mwmbl/indexer/index.py b/mwmbl/indexer/index.py
index ce94c5c..dc7a00c 100644
--- a/mwmbl/indexer/index.py
+++ b/mwmbl/indexer/index.py
@@ -11,9 +11,8 @@ DEFAULT_SCORE = 0
HTTP_START = 'http://'
HTTPS_START = 'https://'
-BATCH_SIZE = 100
-NUM_FIRST_TOKENS = 3
-NUM_BIGRAMS = 5
+NUM_FIRST_TOKENS = 10
+NUM_BIGRAMS = 10
STOPWORDS = set("0,1,2,3,4,5,6,7,8,9,a,A,about,above,across,after,again,against,all,almost,alone,along,already,also," \
@@ -46,15 +45,6 @@ def prepare_url_for_tokenizing(url: str):
return url
-def get_pages(nlp, titles_urls_and_extracts, link_counts) -> Iterable[TokenizedDocument]:
- for i, (title_cleaned, url, extract) in enumerate(titles_urls_and_extracts):
- score = link_counts.get(url, DEFAULT_SCORE)
- yield tokenize_document(url, title_cleaned, extract, score)
-
- if i % 1000 == 0:
- print("Processed", i)
-
-
def get_index_tokens(tokens):
first_tokens = tokens[:NUM_FIRST_TOKENS]
bigrams = get_bigrams(NUM_BIGRAMS, tokens)
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index e1c3621..0029acb 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -1,8 +1,10 @@
"""
Index batches that are stored locally.
"""
+import math
from collections import defaultdict
from datetime import datetime
+from functools import reduce
from logging import getLogger
from typing import Collection, Iterable
@@ -13,6 +15,7 @@ from mwmbl.indexer.batch_cache import BatchCache
from mwmbl.indexer.index import tokenize_document
from mwmbl.indexer.indexdb import BatchStatus
from mwmbl.tinysearchengine.indexer import Document, TinyIndex
+from mwmbl.tinysearchengine.rank import score_result, DOCUMENT_FREQUENCIES, N_DOCUMENTS
from mwmbl.utils import add_term_infos
logger = getLogger(__name__)
@@ -42,7 +45,7 @@ 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]
+ documents = [Document(title, url, extract, 0.0) for title, url, extract in document_tuples]
page_documents = preprocess_documents(documents, index_path)
index_pages(index_path, page_documents)
end_time = datetime.utcnow()
@@ -78,13 +81,44 @@ def preprocess_documents(documents, index_path):
tokenized = tokenize_document(document.url, document.title, document.extract, document.score)
for token in tokenized.tokens:
+ score = score_document(token, document)
+ logger.info(f"Score for {repr(token)} in {document.url} with title {document.title}: {score}")
page = indexer.get_key_page_index(token)
- term_document = Document(document.title, document.url, document.extract, document.score, token)
+ term_document = Document(document.title, document.url, document.extract, score, token)
page_documents[page].append(term_document)
print(f"Preprocessed for {len(page_documents)} pages")
return page_documents
+DOCUMENT_FREQ_DENOMINATOR = sum(DOCUMENT_FREQUENCIES.values()) / len(DOCUMENT_FREQUENCIES)
+
+
+def round_sig(x, sig=2):
+ """
+ https://stackoverflow.com/a/3413529/660902
+ """
+ return round(x, sig - int(math.floor(math.log10(abs(x)))) - 1)
+
+
+def score_document(token, document):
+ doc_score = score_result(token.split(), document, True) * 1000 + 1
+ # TODO: are we emphasising common words too much?
+ # It feels like we need something more like TF-IDF rather than just DF
+ token_score = get_token_score(token)
+ score = doc_score * token_score
+ rounded_score = round_sig(score)
+ if score > 10:
+ return int(rounded_score)
+ return rounded_score
+
+
+def get_token_score(token):
+ terms = token.split()
+ doc_frequencies = [DOCUMENT_FREQUENCIES.get(term, 1) for term in terms]
+ doc_probs = [doc_freq/DOCUMENT_FREQ_DENOMINATOR for doc_freq in doc_frequencies]
+ return reduce(lambda x, y: x * y, doc_probs)
+
+
def get_url_error_status(item: Item):
if item.status == 404:
return URLStatus.ERROR_404