File size: 8,646 Bytes
d26ad91
bd85b1e
 
 
d26ad91
25e8265
bd85b1e
 
 
 
 
 
 
d26ad91
25e8265
 
 
bd85b1e
25e8265
 
 
 
 
 
 
 
 
 
 
 
 
bd85b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26ad91
bd85b1e
 
 
 
5b8fd7e
 
 
bd85b1e
 
 
dc5bfc8
 
 
 
 
 
 
 
 
 
bd85b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26ad91
bd85b1e
 
 
 
 
 
 
 
 
 
 
 
8d9b8a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd85b1e
 
8d9b8a5
bd85b1e
 
 
 
 
dc5bfc8
8d9b8a5
bd85b1e
 
d26ad91
 
 
 
 
 
 
8d9b8a5
d26ad91
 
dc5bfc8
8d9b8a5
 
 
 
 
 
 
 
 
 
 
 
 
d26ad91
 
8d9b8a5
 
 
 
 
 
 
 
 
 
d26ad91
 
 
 
 
 
8d9b8a5
d26ad91
 
 
bd85b1e
 
 
 
 
 
 
 
 
 
8d9b8a5
 
 
 
 
 
 
 
 
 
 
 
d26ad91
 
 
 
 
 
 
8d9b8a5
d26ad91
 
 
25e8265
d26ad91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25e8265
d26ad91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd85b1e
25e8265
 
 
 
 
 
 
 
d26ad91
 
 
 
 
 
bd85b1e
 
 
 
 
 
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
import { Copy, CopyCheck, ExternalLink, Link } from 'lucide-react'
import Modal from './Modal'
import MarkdownRenderer from './MarkdownRenderer'
import { useModel } from '@/contexts/ModelContext'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { useState, useEffect } from 'react'

interface ModelCodeProps {
  isCodeModalOpen: boolean
  setIsCodeModalOpen: (isOpen: boolean) => void
}

const ModelCode = ({ isCodeModalOpen, setIsCodeModalOpen }: ModelCodeProps) => {
  const [isCopied, setIsCopied] = useState(false)
  const [showAlert, setShowAlert] = useState(false)
  const [animateAlert, setAnimateAlert] = useState(false)

  const { modelInfo, pipeline, selectedQuantization } = useModel()

  useEffect(() => {
    if (isCopied) {
      setShowAlert(true)
      const enterTimeout = setTimeout(() => setAnimateAlert(true), 20)
      return () => clearTimeout(enterTimeout)
    } else {
      setAnimateAlert(false)
      const exitTimeout = setTimeout(() => setShowAlert(false), 300) // Match duration-300
      return () => clearTimeout(exitTimeout)
    }
  }, [isCopied])

  if (!modelInfo) return null

  const title = (
    <div className="flex items-center space-x-2">
      <a
        className="truncate hover:underline"
        href={`https://huggingface.co/${modelInfo.name}`}
        target="_blank"
        rel="noopener noreferrer"
      >
        <ExternalLink className="w-3 h-3 inline-block mr-1" />
        {modelInfo.name}
      </a>
    </div>
  )

  let classType = 'classifier'
  let exampleData = 'I love this product!'
  let config = {}

  switch (pipeline) {
    case 'text-classification':
      classType = 'classifier'
      exampleData = 'I love this product!'
      config = {
        top_k: 1
      }
      break
    case 'text-generation':
      classType = 'generator'
      if (modelInfo.hasChatTemplate) {
        exampleData = JSON.stringify([
          {
            role: 'user',
            content: 'Hello!'
          }
        ])
      } else {
        exampleData = 'Once upon a time, there was'
      }
      config = {
        max_length: 50,
        do_sample: true,
        temperature: 0.7,
        top_p: 0.9,
        top_k: 50
      }
      break

    case 'zero-shot-classification':
      classType = 'classifier'
      exampleData = "I love this product!, ['positive', 'neutral', 'negative']"
      config = {
        threshold: 0.5
      }
      break
    case 'feature-extraction':
      classType = 'generator'
      exampleData = 'This is a simple test'
      config = {
        pooling: 'mean',
        normalize: true
      }
      break
    case 'image-classification':
      classType = 'classifier'
      exampleData = 'https://example.com/image.jpg'
      config = {
        top_k: 5
      }
      break
    case 'text-to-speech':
      classType = 'synthesizer'
      exampleData =
        "Life is like a box of chocolates. You never know what you're gonna get."
      if (modelInfo.isStyleTTS2) {
        config = {
          voice: 'af_heart'
        }
      } else {
        config = {
          speaker_embeddings:
            'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin'
        }
      }
      break
  }

  let jsCode = `import { pipeline } from '@huggingface/transformers';

const ${classType} = pipeline('${pipeline}', '${modelInfo.name}', {
  dtype: '${selectedQuantization}',
  device: 'webgpu' // 'wasm'
});
const result = await ${classType}(${modelInfo.hasChatTemplate ? exampleData : "'" + exampleData + "'"}, ${JSON.stringify(config, null, 2)});
${pipeline === 'text-to-speech' ? "result.save('audio.wav')" : 'console.log(result);'}
`

  const configPython = Object.entries(config)
    .map(
      ([key, value]) =>
        `${key}=${value === true ? 'True' : typeof value === 'string' ? "'" + value + "'" : value}`
    )
    .join(', ')

  let pythonCode = `from transformers import pipeline

${classType} = pipeline("${pipeline}", model="${modelInfo.name}")
result = ${classType}(${modelInfo.hasChatTemplate ? exampleData : '"' + exampleData + '"'}, ${configPython})
${pipeline === 'text-to-speech' ? 'audio = result["audio"]' : 'print(result)'}
`

  if (modelInfo.isStyleTTS2) {
    jsCode = `
import { KokoroTTS } from "kokoro-js";
const tts = await KokoroTTS.from_pretrained('${modelInfo.name}', {
  dtype: '${selectedQuantization}',
  device: 'webgpu' // 'wasm'
});

const audio = await tts.generate("${exampleData}", ${JSON.stringify(config, null, 2)});
audio.save("audio.wav");
`

    pythonCode = `!pip install -q kokoro>=0.9.4 soundfile
from kokoro import KPipeline

pipeline = KPipeline(lang_code='a')
generator = pipeline("${exampleData}", voice='af_heart')
for i, (gs, ps, audio) in enumerate(generator):
    print(i, gs, ps)
`
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    setIsCopied(true)
    setTimeout(() => setIsCopied(false), 2000)
  }
  const pipelineName = pipeline
    .replace('speech', 'audio')
    .split('-')
    .map((word, index) => word.charAt(0).toUpperCase() + word.slice(1))
    .join('')

  return (
    <>
      <Modal
        isOpen={isCodeModalOpen}
        onClose={() => setIsCodeModalOpen(false)}
        title={title}
        maxWidth="5xl"
      >
        <div className="text-sm max-w-none px-4">
          {modelInfo.isStyleTTS2 && (
            <div className="flex flex-row items-center text-sm hover:underline text-foreground/60 mb-4">
              <a
                href={`https://github.com/hexgrad/kokoro`}
                target="_blank"
                rel="noopener noreferrer"
              >
                Check Kokoro github for more info about Style TTS2 models
              </a>
            </div>
          )}

          <div className="flex flex-row">
            <img src="/javascript-logo.svg" className="w-6 h-6 mr-1 rounded" />
            <h2 className="text-lg font-medium mb-2">Javascript</h2>
          </div>
          <div className="flex flex-row items-center text-sm hover:underline text-foreground/60">
            <Link className="h-3 w-3 mr-2" />
            <a
              href={`https://huggingface.co/docs/transformers.js/api/pipelines#pipelines${pipeline.replace(/-/g, '').replace('speech', 'audio')}pipeline`}
              target="_blank"
              rel="noopener noreferrer"
            >
              Read about {pipeline} in Transformers.js documentation
            </a>
          </div>
          <div className="relative">
            <div className="absolute right-0 top-0 mt-2 mr-2">
              <button
                onClick={() => copyToClipboard(jsCode)}
                className="text-gray-500 hover:text-gray-700 p-1 text-xs"
              >
                <Copy className="w-4 h-4" />
              </button>
            </div>
            <MarkdownRenderer content={`\`\`\`javascript\n${jsCode}\n\`\`\``} />
          </div>

          <div className="mt-6">
            <div className="flex flex-row">
              <img src="/python-logo.svg" className="w-6 h-6 mr-1" />
              <h2 className="text-lg font-medium mb-2">Python</h2>
            </div>
            <a
              className="text-sm hover:underline text-foreground/60"
              href={`https://huggingface.co/docs/transformers/en/main_classes/pipelines#transformers.${pipelineName}Pipeline`}
              target="_blank"
              rel="noopener noreferrer"
            >
              Read about {pipeline} in Transformers documentation
            </a>
            <div className="relative">
              <div className="absolute right-0 top-0 mt-2 mr-2">
                <button
                  onClick={() => copyToClipboard(pythonCode)}
                  className="text-gray-500 hover:text-gray-700 p-1 text-xs"
                >
                  <Copy className="w-4 h-4" />
                </button>
              </div>
              <MarkdownRenderer
                content={`\`\`\`python\n${pythonCode}\n\`\`\``}
              />
            </div>
          </div>
        </div>
        {showAlert && (
          <div
            className={`absolute top-4 left-1/2 -translate-x-1/2 transition-all duration-300 ease-in-out ${
              animateAlert
                ? 'opacity-100 translate-y-0'
                : 'opacity-0 -translate-y-4'
            }`}
          >
            <Alert>
              <CopyCheck className="w-4 h-4 opacity-60" />
              <AlertDescription>Copied!</AlertDescription>
            </Alert>
          </div>
        )}
      </Modal>
    </>
  )
}

export default ModelCode