File size: 1,648 Bytes
b01bac2
609a959
 
 
b01bac2
609a959
aaa724e
ea91b21
b01bac2
 
 
 
609a959
b01bac2
9aeba4b
b01bac2
 
609a959
b01bac2
 
aaa724e
9aeba4b
 
 
 
 
 
ea91b21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b01bac2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
defmodule MedicalTranscription.Feedback do
  @moduledoc """
  Context for managing user feedback on transcribed text and codes.
  """
  alias MedicalTranscription.Feedback.CodeFeedback
  alias MedicalTranscription.Repo
  import Ecto.Query, only: [from: 2]
  import Pgvector.Ecto.Query, only: [cosine_distance: 2]

  def track_response(params) do
    changeset = CodeFeedback.changeset(%CodeFeedback{}, params)

    case Repo.insert(changeset) do
      {:ok, _code_feedback} ->
        {:ok, message_for_response(params)}

      {:error, changeset} ->
        {:error, Repo.collect_errors(changeset)}
    end
  end

  defp message_for_response(params) do
    action = if params["response"] == "true", do: "upvoted", else: "downvoted"

    "Successfully #{action} code"
  end

  @doc """
  Given a portion of transcribed text, finds the most-relevant previous feedback for that transcribed text.

  The response from this previous feedback can then be used to modify the weight for the associated code when
  classifying this `text`.
  """
  def find_related_feedback(search_vector, opts \\ []) do
    k = Keyword.get(opts, :num_results, 5)
    similarity_threshold = Keyword.get(opts, :similarity_threshold, 0.80)

    query =
      from f in CodeFeedback,
        order_by: cosine_distance(f.text_vector, ^search_vector),
        where: 1 - cosine_distance(f.text_vector, ^search_vector) > ^similarity_threshold,
        limit: ^k,
        select: %{
          code_vector_id: f.code_vector_id,
          response: f.response,
          cosine_similarity: 1 - cosine_distance(f.text_vector, ^search_vector)
        }

    Repo.all(query)
  end
end