Skip to content

Commit

Permalink
Make random query reproducible
Browse files Browse the repository at this point in the history
  • Loading branch information
hv0905 committed Jun 21, 2024
1 parent 9dba0fc commit 79b5fac
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
10 changes: 7 additions & 3 deletions app/Controllers/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,14 @@ async def combinedSearch(
@search_router.get("/random", description="Get random images")
async def randomPick(
filter_param: Annotated[FilterParams, Depends(FilterParams)],
paging: Annotated[SearchPagingParams, Depends(SearchPagingParams)]) -> SearchApiResponse:
paging: Annotated[SearchPagingParams, Depends(SearchPagingParams)],
seed: Annotated[int | None, Query(
description="The seed for random pick. This is helpful for generating a reproducible random pick.")] = None,
) -> SearchApiResponse:
logger.info("Random pick request received")
random_vector = services.transformers_service.get_random_vector()
result = await services.db_context.querySearch(random_vector, top_k=paging.count, filter_param=filter_param)
random_vector = services.transformers_service.get_random_vector(seed)
result = await services.db_context.querySearch(random_vector, top_k=paging.count, skip=paging.skip,
filter_param=filter_param)
return await result_postprocessing(
SearchApiResponse(result=result, message=f"Successfully get {len(result)} results.", query_id=uuid4()))

Expand Down
6 changes: 3 additions & 3 deletions app/Services/transformers_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def get_bert_vector(self, text: str) -> ndarray:
return vector.cpu().numpy()

@staticmethod
def get_random_vector() -> ndarray:
vec = np.random.rand(768)
vec -= vec.mean()
def get_random_vector(seed: int | None = None) -> ndarray:
generator = np.random.default_rng(seed)
vec = generator.uniform(-1, 1, 768)
return vec

0 comments on commit 79b5fac

Please sign in to comment.