File size: 4,344 Bytes
22f8eb7
 
 
 
31283f8
22f8eb7
 
 
 
 
 
 
31283f8
 
 
22f8eb7
 
 
 
 
 
 
 
 
 
 
31283f8
 
 
22f8eb7
 
 
 
31283f8
 
 
22f8eb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31283f8
 
 
22f8eb7
31283f8
 
22f8eb7
 
 
 
 
 
 
 
 
 
 
 
 
31283f8
22f8eb7
 
31283f8
 
 
 
 
 
 
 
 
 
22f8eb7
31283f8
 
 
 
 
 
 
 
 
 
22f8eb7
31283f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22f8eb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import React, { createContext, useContext, useState, useCallback } from 'react'
import { EmbeddingExample, SimilarityResult } from '../types'

interface FeatureExtractionConfig {
  pooling: 'mean' | 'cls'
  normalize: boolean
}

interface FeatureExtractionContextType {
  examples: EmbeddingExample[]
  setExamples: React.Dispatch<React.SetStateAction<EmbeddingExample[]>>
  selectedExample: EmbeddingExample | null
  setSelectedExample: React.Dispatch<
    React.SetStateAction<EmbeddingExample | null>
  >
  similarities: SimilarityResult[]
  setSimilarities: React.Dispatch<React.SetStateAction<SimilarityResult[]>>
  config: FeatureExtractionConfig
  setConfig: React.Dispatch<React.SetStateAction<FeatureExtractionConfig>>
  addExample: (text: string) => void
  removeExample: (id: string) => void
  updateExample: (id: string, updates: Partial<EmbeddingExample>) => void
  calculateSimilarities: (targetExample: EmbeddingExample) => void
  clearExamples: () => void
}

const FeatureExtractionContext = createContext<
  FeatureExtractionContextType | undefined
>(undefined)

export const useFeatureExtraction = () => {
  const context = useContext(FeatureExtractionContext)
  if (!context) {
    throw new Error(
      'useFeatureExtraction must be used within a FeatureExtractionProvider'
    )
  }
  return context
}

// Cosine similarity calculation
const cosineSimilarity = (a: number[], b: number[]): number => {
  if (a.length !== b.length) {
    throw new Error('Vectors must have the same length')
  }

  let dotProduct = 0
  let normA = 0
  let normB = 0

  for (let i = 0; i < a.length; i++) {
    dotProduct += a[i] * b[i]
    normA += a[i] * a[i]
    normB += b[i] * b[i]
  }

  normA = Math.sqrt(normA)
  normB = Math.sqrt(normB)

  if (normA === 0 || normB === 0) {
    return 0
  }

  return dotProduct / (normA * normB)
}

export const FeatureExtractionProvider: React.FC<{
  children: React.ReactNode
}> = ({ children }) => {
  const [examples, setExamples] = useState<EmbeddingExample[]>([])
  const [selectedExample, setSelectedExample] =
    useState<EmbeddingExample | null>(null)
  const [similarities, setSimilarities] = useState<SimilarityResult[]>([])
  const [config, setConfig] = useState<FeatureExtractionConfig>({
    pooling: 'mean',
    normalize: true
  })

  const addExample = useCallback((text: string) => {
    const newExample: EmbeddingExample = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      text: text.trim(),
      embedding: undefined,
      isLoading: false
    }
    setExamples((prev) => [...prev, newExample])
  }, [])

  const removeExample = useCallback(
    (id: string) => {
      setExamples((prev) => prev.filter((example) => example.id !== id))
      if (selectedExample?.id === id) {
        setSelectedExample(null)
        setSimilarities([])
      }
    },
    [selectedExample]
  )

  const updateExample = useCallback(
    (id: string, updates: Partial<EmbeddingExample>) => {
      setExamples((prev) =>
        prev.map((example) =>
          example.id === id ? { ...example, ...updates } : example
        )
      )
    },
    []
  )

  const calculateSimilarities = useCallback(
    (targetExample: EmbeddingExample) => {
      if (!targetExample.embedding) {
        setSimilarities([])
        return
      }

      const newSimilarities: SimilarityResult[] = examples
        .filter(
          (example) => example.id !== targetExample.id && example.embedding
        )
        .map((example) => ({
          exampleId: example.id,
          similarity: cosineSimilarity(
            targetExample.embedding!,
            example.embedding!
          )
        }))
        .sort((a, b) => b.similarity - a.similarity)

      setSimilarities(newSimilarities)
    },
    [examples]
  )

  const clearExamples = useCallback(() => {
    setExamples([])
    setSelectedExample(null)
    setSimilarities([])
  }, [])

  const value: FeatureExtractionContextType = {
    examples,
    setExamples,
    selectedExample,
    setSelectedExample,
    similarities,
    setSimilarities,
    config,
    setConfig,
    addExample,
    removeExample,
    updateExample,
    calculateSimilarities,
    clearExamples
  }

  return (
    <FeatureExtractionContext.Provider value={value}>
      {children}
    </FeatureExtractionContext.Provider>
  )
}