class_docstr: Ranks Documents based on their similarity to the query.
  It uses a pre-trained cross-encoder model (from the Hugging Face Hub) to embed the query and the Documents.
  
  Usage example:
  ```
  from haystack import Document
  from haystack.components.rankers import TransformersSimilarityRanker
  
  ranker = TransformersSimilarityRanker()
  docs = [Document(content="Paris"), Document(content="Berlin")]
  query = "City in Germany"
  output = ranker.run(query=query, documents=docs)
  docs = output["documents"]
  assert len(docs) == 2
  assert docs[0].content == "Berlin"
  ```
class_docstr_tok: ["Ranks","Documents","based","on","their","similarity","to","the","query",".","It","uses","a","pre-trained","cross-encoder","model","(","from","the","Hugging","Face","Hub",")","to","embed","the","query","and","the","Documents",".","Usage","example",":","``","`","from","haystack","import","Document","from","haystack.components.rankers","import","TransformersSimilarityRanker","ranker","=","TransformersSimilarityRanker","(",")","docs","=","[","Document","(","content=","''","Paris","''",")",",","Document","(","content=","''","Berlin","''",")","]","query","=","``","City","in","Germany","''","output","=","ranker.run","(","query=query",",","documents=docs",")","docs","=","output","[","``","documents","''","]","assert","len","(","docs",")","==","2","assert","docs","[","0","]",".content","==","``","Berlin","''","``","`"]
docstr: Returns a list of Documents ranked by their similarity to the given query.
  
  :param query: Query string.
  :param documents: List of Documents.
  :param top_k: The maximum number of Documents you want the Ranker to return.
  :param scale_score: Whether the raw logit predictions will be scaled using a Sigmoid activation function.
      Set this to False if you do not want any scaling of the raw logit predictions.
  :param calibration_factor: Factor used for calibrating probabilities calculated by
      `sigmoid(logits * calibration_factor)`. This is only used if `scale_score` is set to True.
  :param score_threshold: If provided only returns documents with a score above this threshold.
  :return: List of Documents sorted by their similarity to the query with the most similar Documents appearing first.
docstr_tok: ["Returns","a","list","of","Documents","ranked","by","their","similarity","to","the","given","query",".",":","param","query",":","Query","string",".",":","param","documents",":","List","of","Documents",".",":","param","top_k",":","The","maximum","number","of","Documents","you","want","the","Ranker","to","return",".",":","param","scale_score",":","Whether","the","raw","logit","predictions","will","be","scaled","using","a","Sigmoid","activation","function",".","Set","this","to","False","if","you","do","not","want","any","scaling","of","the","raw","logit","predictions",".",":","param","calibration_factor",":","Factor","used","for","calibrating","probabilities","calculated","by","`","sigmoid","(","logits","*","calibration_factor",")","`",".","This","is","only","used","if","`","scale_score","`","is","set","to","True",".",":","param","score_threshold",":","If","provided","only","returns","documents","with","a","score","above","this","threshold",".",":","return",":","List","of","Documents","sorted","by","their","similarity","to","the","query","with","the","most","similar","Documents","appearing","first","."]
code: def run(
      self,
      query: str,
      documents: List[Document],
      top_k: Optional[int] = None,
      scale_score: Optional[bool] = None,
      calibration_factor: Optional[float] = None,
      score_threshold: Optional[float] = None,
  ):
      """
      Returns a list of Documents ranked by their similarity to the given query.
  
      :param query: Query string.
      :param documents: List of Documents.
      :param top_k: The maximum number of Documents you want the Ranker to return.
      :param scale_score: Whether the raw logit predictions will be scaled using a Sigmoid activation function.
          Set this to False if you do not want any scaling of the raw logit predictions.
      :param calibration_factor: Factor used for calibrating probabilities calculated by
          `sigmoid(logits * calibration_factor)`. This is only used if `scale_score` is set to True.
      :param score_threshold: If provided only returns documents with a score above this threshold.
      :return: List of Documents sorted by their similarity to the query with the most similar Documents appearing first.
      """
      if not documents:
          return {"documents": []}
  
      top_k = top_k or self.top_k
      if top_k <= 0:
          raise ValueError(f"top_k must be > 0, but got {top_k}")
  
      scale_score = scale_score or self.scale_score
      calibration_factor = calibration_factor or self.calibration_factor
  
      if scale_score and calibration_factor is None:
          raise ValueError(
              f"scale_score is True so calibration_factor must be provided, but got {calibration_factor}"
          )
  
      if score_threshold is None:
          score_threshold = self.score_threshold
  
      # If a model path is provided but the model isn't loaded
      if self.model and not self._model:
          raise ComponentError(
              f"The component {self.__class__.__name__} wasn't warmed up. Run 'warm_up()' before calling 'run()'."
          )
  
      query_doc_pairs = []
      for doc in documents:
          meta_values_to_embed = [
              str(doc.meta[key])
              for key in self.meta_fields_to_embed
              if key in doc.meta and doc.meta[key]
          ]
          text_to_embed = self.embedding_separator.join(
              meta_values_to_embed + [doc.content or ""]
          )
          query_doc_pairs.append([query, text_to_embed])
  
      features = self.tokenizer(
          query_doc_pairs,
          padding=True,
          truncation=True,
          return_tensors="pt",
      ).to(  # type: ignore
          self.device
      )
      with torch.inference_mode():
          similarity_scores = self._model(**features).logits.squeeze(dim=1)  # type: ignore
  
      if scale_score:
          similarity_scores = torch.sigmoid(
              similarity_scores * calibration_factor
          )
  
      _, sorted_indices = torch.sort(similarity_scores, descending=True)
  
      sorted_indices = sorted_indices.cpu().tolist()  # type: ignore
      similarity_scores = similarity_scores.cpu().tolist()
      ranked_docs = []
      for sorted_index in sorted_indices:
          i = sorted_index
          documents[i].score = similarity_scores[i]
          ranked_docs.append(documents[i])
  
      if score_threshold is not None:
          ranked_docs = [
              doc for doc in ranked_docs if doc.score >= score_threshold
          ]
  
      return {"documents": ranked_docs[:top_k]}
  
file_path: haystack/haystack/components/rankers/transformers_similarity.py
imports: import logging
  from pathlib import Path
  from typing import List, Union, Dict, Any, Optional
  from haystack import ComponentError, Document, component, default_to_dict, default_from_dict
  from haystack.lazy_imports import LazyImport
  from haystack.utils import get_device
label_desc: Use image node_id 6 for calling the TransformersSimilarityRanker obj's underlying member method code with example usage: obj.run(query, documents, top_k, scale_score, calibration_factor, score_threshold) and returns: dict, dict