An open source, non-profit web search engine
Get top terms currently indexed
Daoud Clarkec865368b9a1c
diff --git a/crawl.py b/crawl.pyindex 9767ef5..ecf655e 100644--- a/crawl.py+++ b/crawl.py@@ -8,6 +8,9 @@ import djangofrom django.conf import settingsfrom redis import Redis+from mwmbl.rankeval.evaluation.remote_index import RemoteIndex+from mwmbl.tinysearchengine.indexer import TinyIndex, Document+os.environ["DJANGO_SETTINGS_MODULE"] = "mwmbl.settings_crawler"data_path = Path(settings.DATA_PATH)@@ -78,14 +81,30 @@ def run_indexing_continuously():def run_indexing():redis = Redis(host='localhost', port=6379, decode_responses=True)index_path = data_path / settings.INDEX_NAME- batch_jsons = redis.lpop(BATCH_QUEUE_KEY, 1000)+ batch_jsons = redis.lpop(BATCH_QUEUE_KEY, 100)if batch_jsons is None:logger.info("No more batches to index. Sleeping for 10 seconds.")time.sleep(10)returnlogger.info(f"Got {len(batch_jsons)} batches to index")batches = [HashedBatch.parse_raw(b) for b in batch_jsons]- index_batches(batches, index_path)+ term_new_doc_count = index_batches(batches, index_path)+ logger.info(f"Indexed, top terms to sync: {term_new_doc_count.most_common(10)}")++ remote_index = RemoteIndex()+ with TinyIndex(Document, index_path, 'r') as local_index:+ for term, count in term_new_doc_count.most_common(10):+ remote_items = remote_index.retrieve(term)+ remote_item_urls = {item.url for item in remote_items}+ local_items = local_index.retrieve(term)+ new_items = [item for item in local_items if item.url not in remote_item_urls]+ logger.info(f"Found {len(new_items)} new items for term {term}")+ for item in new_items:+ logger.info(f"New item: {item}")++++if __name__ == "__main__":diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex 55ea1d5..c564722 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -125,8 +125,6 @@ def create_router(batch_cache: BatchCache, queued_batches: RedisURLQueue, versiourls = queued_batches.get_batch(user_id_hash)except Empty:return []- # TODO: track which URLs are currently being crawled-return urls@router.get('/batches/{date_str}/users/{public_user_id}')diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.pyindex 0289016..c221ade 100644--- a/mwmbl/indexer/index_batches.py+++ b/mwmbl/indexer/index_batches.py@@ -2,7 +2,7 @@Index batches that are stored locally."""import math-from collections import defaultdict+from collections import defaultdict, Counterfrom datetime import datetimefrom functools import reducefrom logging import getLogger@@ -14,7 +14,7 @@ from mwmbl.indexer import process_batchfrom mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.index import tokenize_documentfrom mwmbl.indexer.indexdb import BatchStatus-from mwmbl.tinysearchengine.indexer import Document, TinyIndex+from mwmbl.tinysearchengine.indexer import Document, TinyIndex, DocumentStatefrom mwmbl.tinysearchengine.rank import score_result, DOCUMENT_FREQUENCIES, N_DOCUMENTS, HeuristicRankerfrom mwmbl.utils import add_term_infos@@ -42,27 +42,28 @@ def get_url_score(url):return 1/len(url)-def index_batches(batch_data: Collection[HashedBatch], index_path: str):+def index_batches(batch_data: Collection[HashedBatch], index_path: str) -> Counter:start_time = datetime.utcnow()document_tuples = list(get_documents_from_batches(batch_data))documents = [Document(title, url, extract) for title, url, extract in document_tuples]page_documents = preprocess_documents(documents, index_path)- index_pages(index_path, page_documents)+ new_page_doc_counts = index_pages(index_path, page_documents)end_time = datetime.utcnow()logger.info(f"Indexing took {end_time - start_time}")+ return new_page_doc_counts-def index_pages(index_path: str, page_documents: dict[int, list[Document]]):+def index_pages(index_path: str, page_documents: dict[int, list[Document]]) -> Counter:+ term_new_doc_counts = Counter()with TinyIndex(Document, index_path, 'w') as indexer:ranker = HeuristicRanker(indexer, None, score_threshold=float('-inf'))for page, documents in page_documents.items():- new_documents = []existing_documents = indexer.get_page(page)- seen_urls = set()- seen_titles = set()-sorted_documents = sort_documents(documents, existing_documents, ranker)+ seen_urls = set()+ seen_titles = set()+ new_documents = []for document in sorted_documents:if document.title in seen_titles or document.url in seen_urls:continue@@ -72,6 +73,10 @@ def index_pages(index_path: str, page_documents: dict[int, list[Document]]):logger.info(f"Storing {len(new_documents)} documents for page {page}, originally {len(existing_documents)}")indexer.store_in_page(page, new_documents)+ term_new_doc_counts.update(document.term for document in new_documents+ if document.state != DocumentState.SYNCED_WITH_MAIN_INDEX.value)+ return term_new_doc_counts+def sort_documents(documents, all_existing_documents, ranker):curated_documents = [doc for doc in all_existing_documents if doc.state is not None]diff --git a/mwmbl/rankeval/evaluation/remote_index.py b/mwmbl/rankeval/evaluation/remote_index.pyindex 33a840b..c72c3aa 100644--- a/mwmbl/rankeval/evaluation/remote_index.py+++ b/mwmbl/rankeval/evaluation/remote_index.py@@ -10,7 +10,7 @@ from mwmbl.utils import request_cacheclass RemoteIndex:- url = "https://mwmbl.org/api/v1/search/raw?s="+ url = "https://beta.mwmbl.org/api/v1/search/raw?s="def retrieve(self, query: str):url = self.url + querydiff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.pyindex 49a60eb..cd5b4cb 100644--- a/mwmbl/tinysearchengine/indexer.py+++ b/mwmbl/tinysearchengine/indexer.py@@ -34,6 +34,7 @@ class DocumentState(IntEnum):"""The state of the document in the index. A value of None indicates an organic search result."""+ SYNCED_WITH_MAIN_INDEX = -2DELETED = -1FROM_USER = 2FROM_GOOGLE = 3