Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Update local index for remote one

Daoud Clarkeaf0cf1823ecb
diff --git a/crawl.py b/crawl.py
index 39d7a9a..d9ad556 100644
--- a/crawl.py
+++ b/crawl.py
@@ -26,8 +26,7 @@ django.setup()
from mwmbl.indexer.update_urls import record_urls_in_database
from mwmbl.crawler.retrieve import crawl_batch
from mwmbl.crawler.batch import HashedBatch, Result, Results
-from mwmbl.indexer.index_batches import index_batches
-
+from mwmbl.indexer.index_batches import index_batches, index_documents, index_pages
logger = logging.getLogger(__name__)
FORMAT = "%(process)d:%(levelname)s:%(name)s:%(message)s"
@@ -93,30 +92,34 @@ def run_indexing():
return
logger.info(f"Got {len(batch_jsons)} batches to index")
batches = [HashedBatch.parse_raw(b) for b in batch_jsons]
- term_new_docs = index_batches(batches, index_path)
- term_new_doc_count = Counter({term: len(docs) for term, docs in term_new_docs.items()})
+ 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:
+ with TinyIndex(Document, index_path, 'w') 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}")
-
result_items = [Result(url=doc.url, title=doc.title, extract=doc.extract,
score=doc.score, term=doc.term, state=doc.state) for doc in new_items]
results = Results(api_key=API_KEY, results=result_items)
+ logger.info(f"Posting {len(result_items)} results")
response = requests.post("https://beta.mwmbl.org/api/v1/crawler/results", json=results.dict())
print("Response", response.text)
response.raise_for_status()
+ new_remote_items = remote_index.retrieve(term)
+ # Check how many of our items were indexed
+ new_remote_item_urls = {item.url for item in new_remote_items}
+ indexed_items = sum(1 for item in new_items if item.url in new_remote_item_urls)
+ logger.info(f"Indexed items: {indexed_items}/{len(new_items)} for term {term}")
-
+ page_index = local_index.get_key_page_index(term)
+ index_pages(index_path, {page_index: new_remote_items}, mark_synced=True)
+ logger.info(f"Completed indexing for term {term}")
if __name__ == "__main__":
diff --git a/mwmbl/count_urls.py b/mwmbl/count_urls.py
index e52ac91..abed08e 100644
--- a/mwmbl/count_urls.py
+++ b/mwmbl/count_urls.py
@@ -7,7 +7,6 @@ from random import Random
from time import sleep
from django.conf import settings
-from pydistinct.ensemble_estimators import median_estimator
from pydistinct.stats_estimators import smoothed_jackknife_estimator
from redis import Redis
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index 480856a..d3c19b8 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -58,7 +58,7 @@ def index_documents(documents, index_path):
return end_time, new_page_doc_counts
-def index_pages(index_path: str, page_documents: dict[int, list[Document]]) -> Counter:
+def index_pages(index_path: str, page_documents: dict[int, list[Document]], mark_synced: bool = False) -> Counter:
term_new_doc_counts = Counter()
with TinyIndex(Document, index_path, 'w') as indexer:
ranker = HeuristicRanker(indexer, None, score_threshold=float('-inf'))
@@ -68,17 +68,19 @@ def index_pages(index_path: str, page_documents: dict[int, list[Document]]) -> C
seen_urls = set()
seen_titles = set()
- new_documents = []
+ combined_documents = []
for document in sorted_documents:
if document.title in seen_titles or document.url in seen_urls:
continue
- new_documents.append(document)
+ if mark_synced:
+ document.state = DocumentState.SYNCED_WITH_MAIN_INDEX.value
+ combined_documents.append(document)
seen_urls.add(document.url)
seen_titles.add(document.title)
- logger.info(f"Storing {len(new_documents)} documents for page {page}, originally {len(existing_documents)}")
- indexer.store_in_page(page, new_documents)
+ logger.info(f"Storing {len(combined_documents)} documents for page {page}, originally {len(existing_documents)}")
+ indexer.store_in_page(page, combined_documents)
- term_new_doc_counts.update(document.term for document in new_documents
+ term_new_doc_counts.update(document.term for document in combined_documents
if document.state != DocumentState.SYNCED_WITH_MAIN_INDEX.value)
return term_new_doc_counts
diff --git a/mwmbl/settings_crawler.py b/mwmbl/settings_crawler.py
index e20f053..5892ae1 100644
--- a/mwmbl/settings_crawler.py
+++ b/mwmbl/settings_crawler.py
@@ -16,6 +16,4 @@ 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/mwmbl/settings_dev.py b/mwmbl/settings_dev.py
index bc67f0a..1301e18 100644
--- a/mwmbl/settings_dev.py
+++ b/mwmbl/settings_dev.py
@@ -36,5 +36,3 @@ NUM_URLS_IN_BLOOM_FILTER = 100_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"
diff --git a/mwmbl/settings_prod.py b/mwmbl/settings_prod.py
index 9fad002..445e43b 100644
--- a/mwmbl/settings_prod.py
+++ b/mwmbl/settings_prod.py
@@ -41,5 +41,3 @@ NUM_URLS_IN_BLOOM_FILTER = 200_000_000
DOMAIN_LINKS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "links_{domain_group}.bloom")
NUM_DOMAINS_IN_BLOOM_FILTER = 100_000_000
-
-REQUEST_CACHE_PATH = f"{DATA_PATH}/request_cache.sqlite"
diff --git a/mwmbl/utils.py b/mwmbl/utils.py
index cf6d268..d36bcd9 100644
--- a/mwmbl/utils.py
+++ b/mwmbl/utils.py
@@ -1,3 +1,4 @@
+import os
import re
from dataclasses import dataclass
from datetime import timedelta
@@ -5,7 +6,8 @@ from typing import Sequence, Optional
from django.conf import settings
from django.core.exceptions import ValidationError
-from requests_cache import CachedSession
+from redis import Redis
+from requests_cache import CachedSession, RedisCache
from requests.adapters import Retry, HTTPAdapter
from mwmbl.indexer.index import tokenize_document
@@ -87,4 +89,6 @@ def validate_domain(domain_or_url: str):
def request_cache(expire_after: Optional[timedelta] = None) -> CachedSession:
- return CachedSession(expire_after=expire_after, backend="sqlite", cache_name=settings.REQUEST_CACHE_PATH)
+ redis = Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"))
+ redis_cache = RedisCache(connection=redis)
+ return CachedSession(expire_after=expire_after, backend=redis_cache)