Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Keep track of source

Daoud Clarke650a62fe89cc
diff --git a/mwmbl/format.py b/mwmbl/format.py
index 6ea0521..dbd646e 100644
--- a/mwmbl/format.py
+++ b/mwmbl/format.py
@@ -7,11 +7,16 @@ from mwmbl.tokenizer import tokenize, clean_unicode
DOCUMENT_SOURCES = {
DocumentState.FROM_GOOGLE: 'google',
DocumentState.FROM_USER: 'user',
- DocumentState.VALIDATED: 'mwmbl',
- DocumentState.CURATED: 'mwmbl',
+ DocumentState.ORGANIC_APPROVED: 'mwmbl',
+ DocumentState.FROM_GOOGLE_APPROVED: 'google',
+ DocumentState.FROM_USER_APPROVED: 'user',
}
+def get_document_source(state: DocumentState):
+ return DOCUMENT_SOURCES.get(state, 'mwmbl')
+
+
def format_result_with_pattern(pattern, result):
formatted_result = {}
for content_type, content_raw in [('title', result.title), ('extract', result.extract)]:
@@ -26,7 +31,7 @@ def format_result_with_pattern(pattern, result):
content_result.append({'value': content[start:end], 'is_bold': is_bold})
formatted_result[content_type] = content_result
formatted_result['url'] = result.url
- formatted_result['source'] = DOCUMENT_SOURCES[result.state] if result.state else 'mwmbl'
+ formatted_result['source'] = get_document_source(result.state)
return formatted_result
diff --git a/mwmbl/platform/curate.py b/mwmbl/platform/curate.py
index 16ffa86..95049d8 100644
--- a/mwmbl/platform/curate.py
+++ b/mwmbl/platform/curate.py
@@ -96,10 +96,15 @@ def create_router(index_path: str, version: str) -> NinjaAPI:
def _get_document_state(validated: bool, source: str) -> Optional[DocumentState]:
if validated:
- return DocumentState.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 DocumentState.CURATED
+ return None
diff --git a/mwmbl/templates/result.html b/mwmbl/templates/result.html
index c0056e4..b496a08 100644
--- a/mwmbl/templates/result.html
+++ b/mwmbl/templates/result.html
@@ -1,5 +1,10 @@
{% load result_filters %}
<li class="result" is="mwmbl-result">
+ <input type="hidden" name="url" value="{{result.url}}" />
+ <input type="hidden" name="title" value="{{result.title}}" />
+ <input type="hidden" name="extract" value="{{result.extract}}" />
+ <input type="hidden" name="score" value="{{result.score}}" />
+ <input type="hidden" name="state" value="{{result.state.value}}" />
<div class="result-container">
<div class="result-link">
<a href="{{result.url}}">
@@ -7,24 +12,19 @@
<p class='title'>{{result.title|format_for_query:query}}</p>
</a>
<p class='extract'>{{result.extract|format_for_query:query}}</p>
- <input type="hidden" name="url" value="{{result.url}}" />
- <input type="hidden" name="title" value="{{result.title}}" />
- <input type="hidden" name="extract" value="{{result.extract}}" />
- <input type="hidden" name="score" value="{{result.score}}" />
- <input type="hidden" name="state" value="{{result.state.value}}" />
</div>
<div class="curation-buttons">
- {% if result.state.name == 'VALIDATED' %}
+ {% if result.state.value >= 7 %}
<button class="button move-up">↑</button>
<button class="button move-down">↓</button>
{% endif %}
- <button class="button curate-approve{% if result.state > 0 %} validated{% endif %}"
+ <button class="button curate-approve{% if result.state >= 7 %} validated{% endif %}"
hx-post="/app/approve/"
hx-target=".main"
hx-include=".result"
hx-vals='{"approveUrl": "{{ result.url }}", "query": "{{ query }}"}'
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
- {% if result.state.value > 0 %}
+ {% if result.state.value >= 7 %}
✓ Approved
{% else %}
✓ Approve
diff --git a/mwmbl/templatetags/result_filters.py b/mwmbl/templatetags/result_filters.py
index 62aeba9..7d04fd7 100644
--- a/mwmbl/templatetags/result_filters.py
+++ b/mwmbl/templatetags/result_filters.py
@@ -4,7 +4,8 @@ from django.template import Library
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
-from mwmbl.format import get_query_regex, DOCUMENT_SOURCES
+from mwmbl.format import get_query_regex, DOCUMENT_SOURCES, get_document_source
+from mwmbl.tinysearchengine.indexer import DocumentState
from mwmbl.tokenizer import tokenize
register = Library()
@@ -27,6 +28,6 @@ def format_for_query(text: str, query: str, autoescape=True):
@register.filter(needs_autoescape=True)
-def convert_state_to_source(state: str, autoescape=True):
+def convert_state_to_source(state: DocumentState, autoescape=True):
escape = conditional_escape if autoescape else lambda x: x
- return escape(DOCUMENT_SOURCES[state] if state else 'mwmbl')
+ return escape(get_document_source(state))
diff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.py
index 156c519..e859638 100644
--- a/mwmbl/tinysearchengine/indexer.py
+++ b/mwmbl/tinysearchengine/indexer.py
@@ -32,12 +32,16 @@ def astuple(dc):
class DocumentState(IntEnum):
"""
- The state of the document in the index. A value of None indicates a document from our normal crawling procedure.
+ The state of the document in the index. A value of None indicates an organic search result.
"""
- CURATED = 0
- VALIDATED = 1
+ # Needed to prevent Django from mangling the values
+ do_not_call_in_templates = True
+ DELETED = -1
FROM_USER = 2
FROM_GOOGLE = 3
+ ORGANIC_APPROVED = 7
+ FROM_USER_APPROVED = 8
+ FROM_GOOGLE_APPROVED = 9
@dataclass
diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.py
index ac4a657..c99a7e8 100644
--- a/mwmbl/tinysearchengine/rank.py
+++ b/mwmbl/tinysearchengine/rank.py
@@ -119,6 +119,16 @@ def deduplicate(results, seen_titles):
return deduplicated_results
+def fix_document_state(result: Document):
+
+ try:
+ fixed_state = DocumentState(result.state)
+ except ValueError:
+ fixed_state = None
+ fixed_document = Document(result.title, result.url, result.extract, result.score, result.term, fixed_state)
+ return fixed_document
+
+
class Ranker:
def __init__(self, tiny_index: TinyIndex, completer: Completer):
self.tiny_index = tiny_index
@@ -131,8 +141,6 @@ class Ranker:
def search(self, s: str, additional_results: list[Document]) -> list[Document]:
results, terms, _ = self.get_results(s, additional_results)
- is_complete = s.endswith(' ')
- pattern = get_query_regex(terms, is_complete, False)
ranked_results = []
seen_urls = set()
for result in results:
@@ -196,7 +204,8 @@ class Ranker:
ordered_results = self.order_results(terms, pages + additional_results, is_complete)
deduplicated_results = deduplicate(ordered_results, set())
- return deduplicated_results, terms, completions
+ state_fixed = [fix_document_state(result) for result in deduplicated_results]
+ return state_fixed, terms, completions
class HeuristicRanker(Ranker):
diff --git a/mwmbl/views.py b/mwmbl/views.py
index 1a2af97..fe95e4b 100644
--- a/mwmbl/views.py
+++ b/mwmbl/views.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass
from datetime import datetime
from itertools import groupby
+from typing import Optional
from urllib.parse import urlparse, parse_qs, urlencode, urlunparse, ParseResult
import justext
@@ -144,6 +145,21 @@ def fetch_url(request):
})
+def switch_state(state: Optional[DocumentState]) -> Optional[DocumentState]:
+ if state is None:
+ return DocumentState.ORGANIC_APPROVED
+ if state == DocumentState.FROM_GOOGLE:
+ return DocumentState.FROM_GOOGLE_APPROVED
+ if state == DocumentState.FROM_USER:
+ return DocumentState.FROM_USER_APPROVED
+ if state == DocumentState.FROM_GOOGLE_APPROVED:
+ return DocumentState.FROM_GOOGLE
+ if state == DocumentState.FROM_USER_APPROVED:
+ return DocumentState.FROM_USER
+ if state == DocumentState.ORGANIC_APPROVED:
+ return None
+
+
@require_http_methods(["POST"])
def approve(request):
approve_url = request.POST.get("approveUrl")
@@ -155,9 +171,16 @@ def approve(request):
states = request.POST.getlist("state")
scores = request.POST.getlist("score")
+ assert len(urls) == len(titles) == len(extracts) == len(states) == len(scores)
+
+ print("Got approve request", approve_url, urls, titles, extracts, states, scores)
+
documents = {}
for url, title, extract, state, score in zip(urls, titles, extracts, states, scores):
- state_enum = DocumentState(int(state)) if state else None
+ try:
+ state_enum = DocumentState(int(state))
+ except ValueError:
+ state_enum = None
documents[url] = Document(
title=title, url=url, extract=extract, score=float(score), state=state_enum)
@@ -165,10 +188,7 @@ def approve(request):
# If there are no such documents, push it to the top
approved_document = documents[approve_url]
- if approved_document.state is None:
- approved_document.state = DocumentState.VALIDATED
- else:
- approved_document.state = None
+ approved_document.state = switch_state(approved_document.state)
reranked_documents = []
inserted_approved = False
@@ -176,10 +196,9 @@ def approve(request):
if document.url == approve_url:
continue
- if document.state is None:
- if not inserted_approved:
- reranked_documents.append(approved_document)
- inserted_approved = True
+ if (document.state is None or document.state < DocumentState.ORGANIC_APPROVED) and not inserted_approved:
+ reranked_documents.append(approved_document)
+ inserted_approved = True
reranked_documents.append(document)