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 = (
{modelInfo.name}
) 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 ( <> setIsCodeModalOpen(false)} title={title} maxWidth="5xl" >
{modelInfo.isStyleTTS2 && (
Check Kokoro github for more info about Style TTS2 models
)}

Javascript

Read about {pipeline} in Transformers.js documentation

Python

Read about {pipeline} in Transformers documentation
{showAlert && (
Copied!
)}
) } export default ModelCode