Class: SmartCsvImport::Strategies::Vector

Inherits:
SmartCsvImport::Strategy show all
Includes:
Logging
Defined in:
lib/smart_csv_import/strategies/vector.rb

Instance Method Summary collapse

Instance Method Details

#match(csv_headers:, form_class:, sample_rows: []) ⇒ Object



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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/smart_csv_import/strategies/vector.rb', line 14

def match(csv_headers:, form_class:, sample_rows: [])
  field_definitions = form_class.csv_fields
  return {} if field_definitions.empty?

  field_names = field_definitions.keys
  humanized_names = field_names.map { |name| name.to_s.tr("_", " ") }

  # Index humanized names for O(1) exact-match lookup
  humanized_index = humanized_names.each_with_index.to_h { |name, i| [name.downcase, field_names[i]] }

  results = {}
  needs_embedding = []

  csv_headers.each do |header|
    normalized = HeaderNormalizer.normalize(header)
    if (field = humanized_index[normalized.downcase])
      log_info("Exact match: '#{header}' → :#{field} (normalized: '#{normalized}')")
      results[header] = MatchResult.matched(
        target_field: field,
        confidence: 1.0,
        strategy_name: "vector"
      )
    else
      needs_embedding << header
    end
  end

  return results if needs_embedding.empty?

  field_embeddings = fetch_field_embeddings(humanized_names, field_names)

  normalized_remaining = needs_embedding.map { |h| HeaderNormalizer.normalize(h) }
  raw_header_embeddings = compute_embeddings(normalized_remaining.uniq)
  header_embeddings = needs_embedding.zip(normalized_remaining).to_h do |orig, norm|
    [orig, raw_header_embeddings[norm]]
  end

  # Build full score matrix so we can check both directions
  score_matrix = needs_embedding.each_with_object({}) do |header, matrix|
    header_vec = header_embeddings[header]
    next unless header_vec

    matrix[header] = field_names.each_with_object({}) do |field_name, scores|
      field_vec = field_embeddings[field_name]
      scores[field_name] = CosineSimilarity.call(header_vec, field_vec) if field_vec
    end
  end

  # Best field for each header
  best_field_for = score_matrix.transform_values { |scores| scores.max_by { |_, s| s }&.first }

  # Best header for each field (among headers needing embedding)
  best_header_for = field_names.each_with_object({}) do |field_name, bh|
    bh[field_name] = score_matrix.max_by { |_, scores| scores[field_name] || -1 }&.first
  end

  needs_embedding.each do |header|
    best_field = best_field_for[header]
    next unless best_field

    score = score_matrix[header][best_field]

    unless best_header_for[best_field] == header
      log_info("Non-mutual: '#{header}' → :#{best_field} (#{score.round(4)}) — field's best header is '#{best_header_for[best_field]}'")
      next
    end

    results[header] = MatchResult.matched(
      target_field: best_field,
      confidence: score.round(4),
      strategy_name: "vector"
    )
  end

  results
rescue RubyLLM::Error, Faraday::Error => e
  log_error("Vector strategy errored (#{e.class}): #{e.message}")
  StrategyFailure.new(strategy_name: "vector", error: e)
end