-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix bm25 & keyword search #564
Open
devxpy
wants to merge
1
commit into
master
Choose a base branch
from
bm25
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+223
−196
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,6 +8,7 @@ | |
import re | ||
import tempfile | ||
import typing | ||
import unicodedata | ||
from functools import partial | ||
from time import time | ||
|
||
|
@@ -56,6 +57,7 @@ | |
url_to_gdrive_file_id, | ||
gdrive_metadata, | ||
) | ||
from daras_ai_v2.office_utils_pptx import pptx_to_text_pages | ||
from daras_ai_v2.redis_cache import redis_lock | ||
from daras_ai_v2.scraping_proxy import ( | ||
get_scraping_proxy_cert_path, | ||
|
@@ -67,7 +69,6 @@ | |
remove_quotes, | ||
generate_text_fragment_url, | ||
) | ||
from daras_ai_v2.office_utils_pptx import pptx_to_text_pages | ||
from daras_ai_v2.text_splitter import text_splitter, Document | ||
from embeddings.models import EmbeddedFile, EmbeddingsReference | ||
from files.models import FileMetadata | ||
|
@@ -190,6 +191,7 @@ def get_top_k_references( | |
s = time() | ||
search_result = query_vespa( | ||
request.search_query, | ||
request.keyword_query, | ||
file_ids=vespa_file_ids, | ||
limit=request.max_references or 100, | ||
embedding_model=embedding_model, | ||
|
@@ -232,34 +234,63 @@ def vespa_search_results_to_refs( | |
|
||
def query_vespa( | ||
search_query: str, | ||
keyword_query: str | list[str] | None, | ||
file_ids: list[str], | ||
limit: int, | ||
embedding_model: EmbeddingModels, | ||
semantic_weight: float = 1.0, | ||
threshold: float = 0.7, | ||
rerank_count: float = 1000, | ||
) -> dict: | ||
query_embedding = create_embeddings_cached([search_query], model=embedding_model)[0] | ||
if query_embedding is None or not file_ids: | ||
if not file_ids: | ||
return {"root": {"children": []}} | ||
file_ids_str = ", ".join(map(repr, file_ids)) | ||
query = f"select * from {settings.VESPA_SCHEMA} where file_id in (@fileIds) and (userQuery() or ({{targetHits: {limit}}}nearestNeighbor(embedding, q))) limit {limit}" | ||
logger.debug(f"Vespa query: {'-'*80}\n{query}\n{'-'*80}") | ||
if semantic_weight == 1.0: | ||
ranking = "semantic" | ||
elif semantic_weight == 0.0: | ||
|
||
yql = "select * from %(schema)s where file_id in (@fileIds) and " % dict( | ||
schema=settings.VESPA_SCHEMA | ||
) | ||
bm25_yql = "( {targetHits: %(hits)i} userInput(@bm25Query) )" | ||
semantic_yql = "( {targetHits: %(hits)i, distanceThreshold: %(threshold)f} nearestNeighbor(embedding, queryEmbedding) )" | ||
|
||
if semantic_weight == 0.0: | ||
yql += bm25_yql % dict(hits=limit) | ||
ranking = "bm25" | ||
elif semantic_weight == 1.0: | ||
yql += semantic_yql % dict(hits=limit, threshold=threshold) | ||
ranking = "semantic" | ||
else: | ||
yql += ( | ||
"( " | ||
+ bm25_yql % dict(hits=rerank_count) | ||
+ " or " | ||
+ semantic_yql % dict(hits=rerank_count, threshold=threshold) | ||
+ " )" | ||
) | ||
ranking = "fusion" | ||
response = get_vespa_app().query( | ||
yql=query, | ||
query=search_query, | ||
ranking=ranking, | ||
body={ | ||
"ranking.features.query(q)": padded_embedding(query_embedding), | ||
"ranking.features.query(semanticWeight)": semantic_weight, | ||
"fileIds": file_ids_str, | ||
}, | ||
|
||
body = {"yql": yql, "ranking": ranking, "hits": limit} | ||
|
||
if ranking in ("bm25", "fusion"): | ||
if isinstance(keyword_query, list): | ||
keyword_query = " ".join(keyword_query) | ||
body["bm25Query"] = remove_control_characters(keyword_query or search_query) | ||
|
||
logger.debug( | ||
"vespa query " + " ".join(repr(f"{k}={v}") for k, v in body.items()) + " ..." | ||
) | ||
|
||
if ranking in ("semantic", "fusion"): | ||
query_embedding = create_embeddings_cached( | ||
[search_query], model=embedding_model | ||
)[0] | ||
if query_embedding is None: | ||
return {"root": {"children": []}} | ||
body["input.query(queryEmbedding)"] = padded_embedding(query_embedding) | ||
|
||
body["fileIds"] = ", ".join(map(repr, file_ids)) | ||
|
||
response = get_vespa_app().query(body) | ||
assert response.is_successful() | ||
|
||
return response.get_json() | ||
|
||
|
||
|
@@ -485,6 +516,23 @@ def create_embeddings_in_search_db( | |
return refs | ||
|
||
|
||
def format_embedding_row( | ||
doc_id: str, | ||
file_id: str, | ||
ref: SearchReference, | ||
embedding: np.ndarray, | ||
created_at: datetime.datetime, | ||
): | ||
return dict( | ||
id=doc_id, | ||
file_id=file_id, | ||
embedding=padded_embedding(embedding), | ||
created_at=int(created_at.timestamp() * 1000), | ||
title=remove_control_characters(ref["title"]), | ||
snippet=remove_control_characters(ref["snippet"]), | ||
) | ||
|
||
|
||
def get_embeds_for_doc( | ||
*, | ||
f_url: str, | ||
|
@@ -940,22 +988,9 @@ def render_sources_widget(refs: list[SearchReference]): | |
) | ||
|
||
|
||
def format_embedding_row( | ||
doc_id: str, | ||
file_id: str, | ||
ref: SearchReference, | ||
embedding: np.ndarray, | ||
created_at: datetime.datetime, | ||
): | ||
return dict( | ||
id=doc_id, | ||
file_id=file_id, | ||
embedding=padded_embedding(embedding), | ||
created_at=int(created_at.timestamp() * 1000), | ||
# url=ref["url"].encode("unicode-escape").decode(), | ||
# title=ref["title"].encode("unicode-escape").decode(), | ||
# snippet=ref["snippet"].encode("unicode-escape").decode(), | ||
) | ||
def remove_control_characters(s): | ||
# from https://docs.vespa.ai/en/troubleshooting-encoding.html | ||
return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C") | ||
Comment on lines
+991
to
+993
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. style: The remove_control_characters function could be more efficient using str.translate() with a translation table |
||
|
||
|
||
EMBEDDING_SIZE = 3072 | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
logic: The rerank_count parameter is defined as float but used for integer operations. Should be typed as int.