Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add a script to count document frequencies

Daoud Clarke544f4b73d6dc
diff --git a/analyse/tfidf.py b/analyse/tfidf.py
new file mode 100644
index 0000000..9838a3a
--- /dev/null
+++ b/analyse/tfidf.py
@@ -0,0 +1,38 @@
+"""
+Estimate word and document frequencies from a sample of the index.
+"""
+import json
+import os
+from collections import Counter
+from pathlib import Path
+from urllib.parse import unquote
+
+from mwmbl.indexer.index import prepare_url_for_tokenizing
+from mwmbl.tinysearchengine.indexer import Document, TinyIndex
+from mwmbl.tokenizer import tokenize
+
+INDEX_SAMPLE_PATH = Path(os.environ["HOME"]) / "index-sample.tinysearch"
+DOCUMENT_COUNTS_PATH = Path(__file__).parent.parent / "mwmbl" / "resources" / "document_counts.json"
+
+
+def get_frequencies():
+ document_counts = Counter()
+ with TinyIndex(item_factory=Document, index_path=INDEX_SAMPLE_PATH) as tiny_index:
+ for i in range(9999):
+ page = tiny_index.get_page(i)
+ for document in page:
+ prepared_url = prepare_url_for_tokenizing(unquote(document.url))
+ for s in [document.title, prepared_url, document.extract]:
+ tokens = tokenize(s)
+ document_counts.update(set(tokens))
+
+ print("\nDocument frequencies")
+ for term, count in document_counts.most_common(200):
+ print(f"{term}: {count}")
+
+ with open(DOCUMENT_COUNTS_PATH, 'w') as f:
+ json.dump(document_counts, f, indent=2)
+
+
+if __name__ == '__main__':
+ get_frequencies()
diff --git a/devdata/rankeval-2024-06/model.pickle b/devdata/rankeval-2024-06/model.pickle
index c3f0d5a..6ae056d 100644
Binary files a/devdata/rankeval-2024-06/model.pickle and b/devdata/rankeval-2024-06/model.pickle differ
diff --git a/mwmbl/rankeval/evaluation/evaluate_remote.py b/mwmbl/rankeval/evaluation/evaluate_remote.py
index 1a2b96f..93fd532 100644
--- a/mwmbl/rankeval/evaluation/evaluate_remote.py
+++ b/mwmbl/rankeval/evaluation/evaluate_remote.py
@@ -44,5 +44,5 @@ def single_query(query: str):
if __name__ == '__main__':
- run()
- # single_query("beethoven - wikipedia")
+ # run()
+ single_query("beethoven - wikipedia")
diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.py
index f2ba59e..6b8b343 100644
--- a/mwmbl/tinysearchengine/rank.py
+++ b/mwmbl/tinysearchengine/rank.py
@@ -4,6 +4,7 @@ import math
import re
import urllib
from abc import abstractmethod
+from collections import defaultdict
from datetime import timedelta
from logging import getLogger
from operator import itemgetter
@@ -37,9 +38,7 @@ def score_result(terms: list[str], result: Document, is_complete: bool):
match_score = (4 * features['match_score_title'] + features['match_score_extract'] + 2 * features[
'match_score_domain'] + 2 * features['match_score_domain_tokenized'] + features['match_score_path'])
- max_match_terms = max(features[f'match_terms_{name}']
- for name in ['title', 'extract', 'domain', 'domain_tokenized', 'path'])
- if max_match_terms <= len(terms) / 2 and result.state is None:
+ if features[f'match_terms'] <= len(terms) / 2 and result.state is None:
return 0.0
if match_score > MATCH_SCORE_THRESHOLD:
@@ -63,12 +62,14 @@ def get_features(terms, title, url, extract, score, is_complete):
parsed_url = urlparse(url)
domain = parsed_url.netloc
path = parsed_url.path
+ query = parsed_url.query
for part, name, is_url in [(title, 'title', False),
(extract, 'extract', False),
(domain, 'domain', True),
(domain, 'domain_tokenized', False),
- (path, 'path', True)]:
- last_match_char, match_length, total_possible_match_length, match_terms = \
+ (path, 'path', True),
+ (query, 'query', False)]:
+ last_match_char, match_length, total_possible_match_length, match_terms, match_counts = \
get_match_features(terms, part, is_complete, is_url)
features[f'last_match_char_{name}'] = last_match_char
features[f'match_length_{name}'] = match_length
@@ -82,6 +83,9 @@ def get_features(terms, title, url, extract, score, is_complete):
features['domain_length'] = len(domain)
features['wiki_score'] = get_wiki_score(url)
features['item_score'] = score
+ features['match_terms'] = max(features[f'match_terms_{name}']
+ for name in ['title', 'extract', 'domain', 'domain_tokenized', 'path'])
+
return features
@@ -108,15 +112,17 @@ def get_match_features(terms, result_string, is_complete, is_url):
last_match_char = 1
seen_matches = set()
match_length = 0
+ match_counts = defaultdict(int)
for match in matches:
value = match.group(0).lower()
+ match_counts[value] += 1
if value not in seen_matches:
last_match_char = match.span()[1]
seen_matches.add(value)
match_length += len(value)
total_possible_match_length = sum(len(x) for x in terms)
- return last_match_char, match_length, total_possible_match_length, len(seen_matches)
+ return last_match_char, match_length, total_possible_match_length, len(seen_matches), match_counts
def get_wiki_score(url):