An open source, non-profit web search engine
Store curations to index
Daoud Clarke05157d674833
diff --git a/devdata/index-v2.tinysearch b/devdata/index-v2.tinysearchindex bbb2c83..b0e3cee 100644Binary files a/devdata/index-v2.tinysearch and b/devdata/index-v2.tinysearch differdiff --git a/mwmbl/templates/result.html b/mwmbl/templates/result.htmlindex 840b878..8445c11 100644--- a/mwmbl/templates/result.html+++ b/mwmbl/templates/result.html@@ -20,10 +20,10 @@hx-include=".result"hx-vals='{"approve_url": "{{ result.url }}", "query": "{{ query }}"{% if curation_id %}, "curation_id": {{ curation_id }}{% endif %}}'hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>✓</button>- {% if result.state.value >= 7 %}- <button class="button move-up">↑</button>- <button class="button move-down">↓</button>- {% endif %}+{# {% if result.state.value >= 7 %}#}+{# <button class="button move-up">↑</button>#}+{# <button class="button move-down">↓</button>#}+{# {% endif %}#}</div></div></li>diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.pyindex c99a7e8..32ce088 100644--- a/mwmbl/tinysearchengine/rank.py+++ b/mwmbl/tinysearchengine/rank.py@@ -186,24 +186,20 @@ class Ranker:curated_items = [d for d in curation_items if d.state is not Noneand d.term == curation_term]- if len(curated_items) > 0:- deduplicated_additional = deduplicate(additional_results, {item.title for item in curated_items})- deduplicated_results = curated_items + deduplicated_additional- else:- bigrams = set(get_bigrams(len(terms), terms))-- pages = []- for term in retrieval_terms | bigrams:- # An optimisation - we have already retrieved this, so make use of it- if term == curation_term:- items = curation_items- else:- items = self.tiny_index.retrieve(term)- if items is not None:- pages += items-- ordered_results = self.order_results(terms, pages + additional_results, is_complete)- deduplicated_results = deduplicate(ordered_results, set())+ bigrams = set(get_bigrams(len(terms), terms))++ pages = []+ for term in retrieval_terms | bigrams:+ # An optimisation - we have already retrieved this, so make use of it+ if term == curation_term:+ items = curation_items+ else:+ items = self.tiny_index.retrieve(term)+ if items is not None:+ pages += items++ ordered_results = self.order_results(terms, pages + additional_results, is_complete)+ deduplicated_results = deduplicate(curated_items + ordered_results, set())state_fixed = [fix_document_state(result) for result in deduplicated_results]return state_fixed, terms, completionsdiff --git a/mwmbl/views.py b/mwmbl/views.pyindex 6779a2a..30f27a7 100644--- a/mwmbl/views.py+++ b/mwmbl/views.py@@ -1,6 +1,7 @@from dataclasses import dataclass, asdictfrom datetime import datetimefrom itertools import groupby+from logging import getLoggerfrom typing import Optionalfrom urllib.parse import urlparse, parse_qs, urlencode, urlunparse, ParseResult@@ -13,16 +14,24 @@ from django_htmx.http import push_urlfrom mwmbl.format import format_resultfrom mwmbl.models import UserCuration, MwmblUser, Curation-from mwmbl.search_setup import ranker+from mwmbl.search_setup import ranker, index_pathfrom justext.core import html_to_dom, ParagraphMaker, classify_paragraphs, revise_paragraph_classification, \LENGTH_LOW_DEFAULT, STOPWORDS_LOW_DEFAULT, MAX_LINK_DENSITY_DEFAULT, NO_HEADINGS_DEFAULT, LENGTH_HIGH_DEFAULT, \STOPWORDS_HIGH_DEFAULT, MAX_HEADING_DISTANCE_DEFAULT, DEFAULT_ENCODING, DEFAULT_ENC_ERRORS, preprocessorfrom mwmbl.settings import NUM_EXTRACT_CHARS-from mwmbl.tinysearchengine.indexer import Document, DocumentState+from mwmbl.tinysearchengine.indexer import Document, DocumentState, TinyIndexfrom django.conf import settings+from mwmbl.tokenizer import tokenize+from mwmbl.utils import add_term_infos++MAX_CURATED_SCORE = 1_111_111.0+++logger = getLogger(__name__)+def justext_with_dom(html_text, stoplist, length_low=LENGTH_LOW_DEFAULT,length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT,@@ -228,6 +237,7 @@ def approve(request):)curation.save()+ _save_to_index(query, reranked_documents)response = render(request, "home.html", {"results": reranked_documents,@@ -237,3 +247,57 @@ def approve(request):})return response+++def _save_to_index(query: str, new_results: list[Document]):+ with TinyIndex(Document, index_path, 'w') as indexer:+ tokens = tokenize(query)+ term = " ".join(tokens)++ documents = [+ Document(+ title=result.title,+ url=result.url,+ extract=result.extract,+ score=MAX_CURATED_SCORE - i,+ term=term,+ state=result.state,+ )+ for i, result in enumerate(new_results)+ if result.state is not None and result.state >= DocumentState.ORGANIC_APPROVED+ ]++ page_index = indexer.get_key_page_index(term)+ existing_documents_no_terms = indexer.get_page(page_index)+ existing_documents = add_term_infos(existing_documents_no_terms, indexer, page_index)+ new_urls = {doc.url for doc in documents}+ other_documents = [doc for doc in existing_documents if doc.url not in new_urls]+ logger.info(f"Found {len(other_documents)} other documents for term {term} at page {page_index} "+ f"with terms { {doc.term for doc in other_documents} }")++ # Update state for other documents+ states = {doc.url: doc.state for doc in new_results}+ for doc in other_documents:+ doc.state = states.get(doc.url, doc.state)++ all_documents = documents + other_documents+ logger.info(f"Storing {len(all_documents)} documents at page {page_index}")+ indexer.store_in_page(page_index, all_documents)++ return {"curation": "ok"}+++def _get_document_state(validated: bool, source: str) -> Optional[DocumentState]:+ if validated:+ if source.lower() == "user":+ return DocumentState.FROM_USER_APPROVED+ elif source.lower() == "google":+ return DocumentState.FROM_GOOGLE_APPROVED+ else:+ return DocumentState.ORGANIC_APPROVED+ elif source.lower() == "user":+ return DocumentState.FROM_USER+ elif source.lower() == "google":+ return DocumentState.FROM_GOOGLE+ else:+ return None