File size: 17,213 Bytes
c836ca5
e791eef
c836ca5
f01c9d3
7e27968
 
 
01570e1
 
 
 
e791eef
c836ca5
 
 
 
01570e1
 
 
e791eef
c836ca5
f01c9d3
c836ca5
 
 
77b219c
 
 
c836ca5
 
f01c9d3
 
 
 
c836ca5
 
 
 
 
 
 
 
 
 
 
 
 
01570e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e791eef
01570e1
e791eef
77b219c
e791eef
77b219c
e791eef
 
 
c836ca5
 
 
e9a623f
e791eef
e9a623f
 
 
 
 
 
 
e791eef
e9a623f
e791eef
c836ca5
f01c9d3
c836ca5
 
 
f01c9d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c836ca5
f01c9d3
e791eef
 
 
 
01570e1
c836ca5
 
 
01570e1
e791eef
01570e1
e791eef
01570e1
7e27968
c836ca5
 
 
 
 
 
 
 
 
 
 
f01c9d3
 
 
 
 
 
 
 
 
 
 
c836ca5
 
 
 
 
 
ec858b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c836ca5
 
ec858b7
c836ca5
 
f01c9d3
 
c836ca5
 
 
 
 
ec858b7
 
 
 
 
 
f01c9d3
 
 
 
 
 
ec858b7
f01c9d3
 
 
 
 
c836ca5
ec858b7
c836ca5
 
ec858b7
c836ca5
 
 
 
 
 
 
 
 
 
 
a2409a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e27968
01570e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a623f
 
 
01570e1
 
 
e791eef
 
 
 
 
 
01570e1
 
 
 
 
c836ca5
f01c9d3
c836ca5
f01c9d3
 
 
c836ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01570e1
 
c836ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01570e1
 
a2409a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01570e1
a2409a8
 
 
 
 
 
 
 
01570e1
7e27968
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
import { useState, useRef, useEffect } from 'react'
import CLAPProcessor from './clapProcessor'
import UserFeedbackStore from './userFeedbackStore'
import LocalClassifier from './localClassifier'
import './App.css'

function App() {
  const [audioFile, setAudioFile] = useState(null)
  const [isRecording, setIsRecording] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [tags, setTags] = useState([])
  const [error, setError] = useState(null)
  const [customTags, setCustomTags] = useState([])
  const [newTag, setNewTag] = useState('')
  const [audioHash, setAudioHash] = useState(null)
  const [audioFeatures, setAudioFeatures] = useState(null)
  const fileInputRef = useRef(null)
  const mediaRecorderRef = useRef(null)
  const chunksRef = useRef([])
  const clapProcessorRef = useRef(null)
  const feedbackStoreRef = useRef(null)
  const localClassifierRef = useRef(null)

  useEffect(() => {
    const initializeStore = async () => {
      // Initialize CLAP processor once and reuse
      clapProcessorRef.current = new CLAPProcessor()
      
      feedbackStoreRef.current = new UserFeedbackStore()
      await feedbackStoreRef.current.initialize()
      
      localClassifierRef.current = new LocalClassifier()
      localClassifierRef.current.loadModel()
      
      loadCustomTags()
    }
    initializeStore()
  }, [])

  const loadCustomTags = async () => {
    try {
      const stored = await feedbackStoreRef.current.getCustomTags()
      setCustomTags(stored.map(item => item.tag))
    } catch (error) {
      console.error('Error loading custom tags:', error)
    }
  }

  const handleFileUpload = (event) => {
    const file = event.target.files[0]
    if (file && file.type.startsWith('audio/')) {
      setAudioFile(file)
      processAudio(file)
    }
  }

  const handleDrop = (event) => {
    event.preventDefault()
    const file = event.dataTransfer.files[0]
    if (file && file.type.startsWith('audio/')) {
      setAudioFile(file)
      processAudio(file)
    }
  }

  const handleDragOver = (event) => {
    event.preventDefault()
  }

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      mediaRecorderRef.current = new MediaRecorder(stream)
      chunksRef.current = []

      mediaRecorderRef.current.ondataavailable = (event) => {
        chunksRef.current.push(event.data)
      }

      mediaRecorderRef.current.onstop = () => {
        const blob = new Blob(chunksRef.current, { type: 'audio/wav' })
        const file = new File([blob], 'recording.wav', { type: 'audio/wav' })
        setAudioFile(file)
        processAudio(file)
        stream.getTracks().forEach(track => track.stop())
      }

      mediaRecorderRef.current.start()
      setIsRecording(true)
    } catch (error) {
      console.error('Error accessing microphone:', error)
    }
  }

  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop()
      setIsRecording(false)
    }
  }

  const processAudio = async (file) => {
    setIsLoading(true)
    setTags([])
    setError(null)
    
    try {
      // CLAP processor should already be initialized in useEffect
      if (!clapProcessorRef.current) {
        console.warn('CLAP processor not initialized, creating new instance')
        clapProcessorRef.current = new CLAPProcessor()
      }
      
      const hash = await feedbackStoreRef.current.hashAudioFile(file)
      setAudioHash(hash)
      
      console.log('Converting file to audio buffer...')
      const audioBuffer = await clapProcessorRef.current.fileToAudioBuffer(file)
      console.log('Audio buffer created:', {
        duration: audioBuffer.duration,
        sampleRate: audioBuffer.sampleRate,
        channels: audioBuffer.numberOfChannels
      })
      
      console.log('Processing audio with CLAP...')
      const generatedTags = await clapProcessorRef.current.processAudio(audioBuffer)
      console.log('Generated tags:', generatedTags)
      
      // Store basic audio info for later use
      const features = {
        sampleRate: audioBuffer.sampleRate,
        duration: audioBuffer.duration,
        numberOfChannels: audioBuffer.numberOfChannels
      }
      setAudioFeatures(features)
      
      // Apply local classifier adjustments
      let finalTags = generatedTags.map(tag => ({ ...tag, userFeedback: null }))
      
      if (localClassifierRef.current) {
        const simpleFeatures = localClassifierRef.current.extractSimpleFeatures(features)
        const allPossibleTags = [...generatedTags.map(t => t.label), ...customTags]
        const localPredictions = localClassifierRef.current.predictAll(simpleFeatures, allPossibleTags)
        
        // Merge CLAP predictions with local classifier predictions
        const mergedTags = new Map()
        
        // Add CLAP tags
        for (const tag of generatedTags) {
          mergedTags.set(tag.label, { ...tag, source: 'clap' })
        }
        
        // Add or adjust with local predictions
        for (const pred of localPredictions) {
          if (mergedTags.has(pred.tag)) {
            // Blend CLAP and local predictions
            const existing = mergedTags.get(pred.tag)
            existing.confidence = (existing.confidence + pred.confidence) / 2
            existing.source = 'blended'
          } else if (pred.confidence > 0.6) {
            // Add high-confidence local predictions
            mergedTags.set(pred.tag, {
              label: pred.tag,
              confidence: pred.confidence,
              source: 'local',
              userFeedback: null
            })
          }
        }
        
        finalTags = Array.from(mergedTags.values())
          .sort((a, b) => b.confidence - a.confidence)
          .slice(0, 8) // Keep top 8 tags
      }
      
      setTags(finalTags)
    } catch (err) {
      console.error('Error processing audio:', err)
      setError('Failed to process audio. Using fallback tags.')
      // Fallback tags
      setTags([
        { label: 'audio', confidence: 0.9, userFeedback: null },
        { label: 'sound', confidence: 0.8, userFeedback: null },
        { label: 'recording', confidence: 0.7, userFeedback: null }
      ])
    } finally {
      setIsLoading(false)
    }
  }

  const handleTagFeedback = async (tagIndex, feedback) => {
    const updatedTags = [...tags]
    updatedTags[tagIndex].userFeedback = feedback
    setTags(updatedTags)

    try {
      await feedbackStoreRef.current.saveTagFeedback(
        updatedTags[tagIndex].label,
        feedback,
        audioHash
      )

      // Train local classifier on this feedback
      if (localClassifierRef.current && audioFeatures) {
        const simpleFeatures = localClassifierRef.current.extractSimpleFeatures(audioFeatures)
        localClassifierRef.current.trainOnFeedback(
          simpleFeatures,
          updatedTags[tagIndex].label,
          feedback
        )
        localClassifierRef.current.saveModel()
      }
    } catch (error) {
      console.error('Error saving tag feedback:', error)
    }
  }

  const handleAddCustomTag = async () => {
    const trimmedTag = newTag.trim().toLowerCase()
    
    // Validation
    if (!trimmedTag) {
      setError('Please enter a tag name')
      return
    }
    
    if (trimmedTag.length < 2) {
      setError('Tag must be at least 2 characters long')
      return
    }
    
    // Check if tag already exists
    const existingTag = tags.find(tag => tag.label.toLowerCase() === trimmedTag)
    if (existingTag) {
      setError(`Tag "${trimmedTag}" already exists`)
      return
    }
    
    // Clear any previous errors
    setError(null)

    const customTag = { 
      label: trimmedTag, 
      confidence: 1.0, 
      userFeedback: 'custom',
      isCustom: true,
      source: 'custom'
    }

    setTags(prev => [...prev, customTag])
    
    try {
      if (feedbackStoreRef.current) {
        await feedbackStoreRef.current.saveCustomTag(trimmedTag)
        if (audioHash) {
          await feedbackStoreRef.current.saveTagFeedback(trimmedTag, 'custom', audioHash)
        }
      }
      
      // Train local classifier on custom tag
      if (localClassifierRef.current && audioFeatures) {
        const simpleFeatures = localClassifierRef.current.extractSimpleFeatures(audioFeatures)
        localClassifierRef.current.trainOnFeedback(
          simpleFeatures,
          trimmedTag,
          'custom'
        )
        localClassifierRef.current.saveModel()
      }
      
      loadCustomTags()
      console.log(`βœ… Added custom tag: "${trimmedTag}"`)
    } catch (error) {
      console.error('Error saving custom tag:', error)
      setError('Failed to save custom tag')
    }

    setNewTag('')
  }

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleAddCustomTag()
    }
  }

  const exportModel = async () => {
    try {
      const modelStats = localClassifierRef.current?.getModelStats()
      const feedbackData = await feedbackStoreRef.current.getAudioFeedback()
      const customTagsData = await feedbackStoreRef.current.getCustomTags()
      
      const exportData = {
        modelStats,
        feedbackData: feedbackData.slice(0, 50), // Limit for size
        customTags: customTagsData,
        exportDate: new Date().toISOString(),
        version: '1.0'
      }

      const blob = new Blob([JSON.stringify(exportData, null, 2)], {
        type: 'application/json'
      })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `clip-tagger-model-${Date.now()}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    } catch (error) {
      console.error('Error exporting model:', error)
      setError('Failed to export model')
    }
  }

  const exportTags = () => {
    if (tags.length === 0) return

    const tagData = {
      audioFile: audioFile?.name || 'recorded-audio',
      audioHash,
      timestamp: new Date().toISOString(),
      tags: tags.map(tag => ({
        label: tag.label,
        confidence: tag.confidence,
        source: tag.source || 'clap',
        userFeedback: tag.userFeedback
      }))
    }

    const blob = new Blob([JSON.stringify(tagData, null, 2)], {
      type: 'application/json'
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `tags-${audioFile?.name || 'audio'}-${Date.now()}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const clearAllData = async () => {
    if (confirm('Are you sure you want to clear all training data? This cannot be undone.')) {
      try {
        await feedbackStoreRef.current.clearAllData()
        localClassifierRef.current?.clearModel()
        setCustomTags([])
        setTags([])
        setAudioFile(null)
        setError(null)
      } catch (error) {
        console.error('Error clearing data:', error)
        setError('Failed to clear data')
      }
    }
  }

  return (
    <div className="app">
      <header>
        <h1>🎡 clip-tagger</h1>
        <p>Custom audio tagging in the browser</p>
      </header>

      <main>
        <div 
          className="upload-area"
          onDrop={handleDrop}
          onDragOver={handleDragOver}
          onClick={() => fileInputRef.current?.click()}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept="audio/*"
            onChange={handleFileUpload}
            hidden
          />
          <div className="upload-content">
            {audioFile ? (
              <div>
                <p>πŸ“ {audioFile.name}</p>
                <audio controls src={URL.createObjectURL(audioFile)} />
              </div>
            ) : (
              <div>
                <p>🎡 Drop an audio file here or click to upload</p>
                <p>Supports WAV, MP3, and other audio formats</p>
              </div>
            )}
          </div>
        </div>

        <div className="controls">
          <button 
            onClick={isRecording ? stopRecording : startRecording}
            className={isRecording ? 'recording' : ''}
          >
            {isRecording ? '⏹️ Stop Recording' : '🎀 Record Audio'}
          </button>
        </div>

        {isLoading && (
          <div className="loading">
            <p>🧠 Analyzing audio with CLAP model...</p>
            <p style={{fontSize: '0.9em', opacity: 0.8}}>
              {tags.length === 0 ? 'Loading model (~45MB)...' : 'Processing audio...'}
            </p>
          </div>
        )}

        {error && (
          <div className="error">
            <p>⚠️ {error}</p>
          </div>
        )}

        {tags.length > 0 && (
          <div className="tags-section">
            <h3>Generated Tags</h3>
            <div className="tags">
              {tags.map((tag, index) => (
                <div key={index} className={`tag-item ${tag.userFeedback ? 'has-feedback' : ''}`}>
                  <span className={`tag ${tag.isCustom ? 'custom' : ''} ${tag.userFeedback === 'negative' ? 'negative' : ''} ${tag.source || 'clap'}`}>
                    {tag.label} ({Math.round(tag.confidence * 100)}%)
                    {tag.source === 'local' && <span className="source-indicator">🧠</span>}
                    {tag.source === 'blended' && <span className="source-indicator">⚑</span>}
                    {tag.source === 'custom' && <span className="source-indicator">✨</span>}
                  </span>
                  {!tag.isCustom && (
                    <div className="tag-controls">
                      <button 
                        onClick={() => handleTagFeedback(index, 'positive')}
                        className={`feedback-btn ${tag.userFeedback === 'positive' ? 'active' : ''}`}
                        title="Good tag"
                      >
                        βœ“
                      </button>
                      <button 
                        onClick={() => handleTagFeedback(index, 'negative')}
                        className={`feedback-btn ${tag.userFeedback === 'negative' ? 'active' : ''}`}
                        title="Bad tag"
                      >
                        βœ—
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
            
            <div className="add-tag">
              <input
                type="text"
                value={newTag}
                onChange={(e) => setNewTag(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="Add custom tag..."
                className="tag-input"
              />
              <button onClick={handleAddCustomTag} className="add-tag-btn">
                Add Tag
              </button>
            </div>

            {customTags.length > 0 && (
              <div className="frequent-tags">
                <h4>Frequent Tags:</h4>
                <div className="frequent-tag-list">
                  {customTags.slice(0, 10).map((tag, index) => (
                    <button
                      key={index}
                      onClick={() => setNewTag(tag)}
                      className="frequent-tag"
                    >
                      {tag}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {(tags.length > 0 || customTags.length > 0) && (
          <div className="export-section">
            <h3>Export & Management</h3>
            <div className="export-controls">
              {tags.length > 0 && (
                <button onClick={exportTags} className="export-btn">
                  πŸ“ Export Current Tags
                </button>
              )}
              {localClassifierRef.current?.getModelStats().trainedTags > 0 && (
                <button onClick={exportModel} className="export-btn">
                  🧠 Export Trained Model
                </button>
              )}
              <button onClick={clearAllData} className="clear-btn">
                πŸ—‘οΈ Clear All Data
              </button>
            </div>
            
            {localClassifierRef.current && (
              <div className="model-stats">
                <p>Trained tags: {localClassifierRef.current.getModelStats().trainedTags}</p>
                <p>Custom tags: {customTags.length}</p>
              </div>
            )}
          </div>
        )}
      </main>
      
      <footer>
        <p>
          Powered by <a href="https://github.com/xenova/transformers.js" target="_blank" rel="noopener">Transformers.js</a> 
          {' '} β€’ CLAP model: <a href="https://huggingface.co/Xenova/clap-htsat-unfused" target="_blank" rel="noopener">Xenova/clap-htsat-unfused</a>
          {' '} β€’ Everything runs locally in your browser
        </p>
      </footer>
    </div>
  )
}

export default App