Spaces:
Running
on
A100
Running
on
A100
File size: 8,305 Bytes
ae238b3 |
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 |
import React, { useMemo, useState, useEffect } from 'react';
import Select, { components, StylesConfig, type SingleValue } from 'react-select';
import { matchSorter } from 'match-sorter';
import { LANGUAGE_MAP, ACCURATE_LANGUAGES } from '../utils/languages';
import { getScriptName, getScriptDescription } from '../utils/scripts';
import { getSupportedLanguages } from '../services/transcriptionApi';
interface LanguageSelectorProps {
selectedLanguage: string | null;
selectedScript: string | null;
onLanguageAndScriptSelect: (language: string | null, script: string | null) => void;
disabled?: boolean;
}
interface OptionType {
value: string; // The full code_script combination
label: string;
languageName: string;
scriptName: string;
languageCode: string;
scriptCode: string;
}
const parseLanguage = (languageString: string): OptionType | null => {
const parts = languageString.split('_');
// Always expect format: "eng_Latn"
if (parts.length === 2) {
const [languageCode, scriptCode] = parts;
const languageName = (LANGUAGE_MAP as Record<string, string>)[languageCode] || languageCode;
const scriptName = getScriptName(scriptCode);
return {
value: languageString,
label: `${languageName} ${scriptName} (${languageString})`,
languageName,
scriptName,
languageCode,
scriptCode,
};
}
return null;
};
// Custom Option component to show language, script, and code with tooltip
const Option = (props: any) => {
const scriptDescription = getScriptDescription(props.data.scriptCode);
return (
<components.Option {...props}>
<div className="flex flex-col" title={scriptDescription || undefined}>
<div className="font-medium text-sm">{props.data.languageName}</div>
<div className="text-xs text-gray-400">{props.data.scriptName} ({props.data.value})</div>
</div>
</components.Option>
);
};
// Custom SingleValue component for selected value
const SingleValue = (props: any) => (
<components.SingleValue {...props}>
<div className="flex flex-col">
<div className="font-medium text-sm leading-tight">{props.data.languageName}</div>
<div className="text-xs text-gray-400 leading-tight">{props.data.scriptName} ({props.data.value})</div>
</div>
</components.SingleValue>
);
// Custom styles to match the dark theme
const customStyles: StylesConfig<OptionType> = {
control: (styles, { isDisabled, isFocused }) => ({
...styles,
backgroundColor: isDisabled ? '#374151' : '#374151', // gray-700
borderColor: isFocused ? '#3b82f6' : '#4b5563', // blue-500 : gray-600
borderRadius: '0.375rem',
minHeight: '40px',
boxShadow: isFocused ? '0 0 0 1px #3b82f6' : 'none',
'&:hover': {
borderColor: isDisabled ? '#4b5563' : '#6b7280', // gray-600 : gray-500
backgroundColor: isDisabled ? '#374151' : '#4b5563', // gray-700 : gray-600
},
cursor: isDisabled ? 'not-allowed' : 'pointer',
}),
singleValue: (styles) => ({
...styles,
color: '#f9fafb', // gray-50
}),
placeholder: (styles) => ({
...styles,
color: '#9ca3af', // gray-400
}),
input: (styles) => ({
...styles,
color: '#f9fafb', // gray-50
}),
menu: (styles) => ({
...styles,
backgroundColor: '#374151', // gray-700
border: '1px solid #4b5563', // gray-600
borderRadius: '0.5rem',
boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
zIndex: 50,
}),
menuList: (styles) => ({
...styles,
maxHeight: '200px',
padding: 0,
}),
option: (styles, { isFocused, isSelected }) => ({
...styles,
backgroundColor: isSelected
? '#2563eb' // blue-600
: isFocused
? '#4b5563' // gray-600
: 'transparent',
color: '#f9fafb', // gray-50
cursor: 'pointer',
padding: '8px 12px',
'&:hover': {
backgroundColor: isSelected ? '#2563eb' : '#4b5563', // blue-600 : gray-600
},
}),
indicatorSeparator: (styles) => ({
...styles,
backgroundColor: '#4b5563', // gray-600
}),
dropdownIndicator: (styles, { isDisabled }) => ({
...styles,
color: isDisabled ? '#6b7280' : '#9ca3af', // gray-500 : gray-400
'&:hover': {
color: isDisabled ? '#6b7280' : '#d1d5db', // gray-500 : gray-300
},
}),
clearIndicator: (styles) => ({
...styles,
color: '#9ca3af', // gray-400
'&:hover': {
color: '#d1d5db', // gray-300
},
}),
noOptionsMessage: (styles) => ({
...styles,
color: '#9ca3af', // gray-400
}),
};
const LanguageSelector: React.FC<LanguageSelectorProps> = ({
selectedLanguage,
selectedScript,
onLanguageAndScriptSelect,
disabled = false
}) => {
const [supportedLanguages, setSupportedLanguages] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Fetch supported languages from API
useEffect(() => {
const fetchSupportedLanguages = async () => {
try {
setIsLoading(true);
const languages = await getSupportedLanguages();
setSupportedLanguages(languages);
} catch (err) {
console.error('Failed to fetch supported languages:', err);
setError('Failed to load supported languages');
} finally {
setIsLoading(false);
}
};
fetchSupportedLanguages();
}, []);
// Convert supported languages to options
const languageOptions = useMemo(() => {
const allowAllLanguages = import.meta.env.VITE_ALLOW_ALL_LANGUAGES === 'true';
return supportedLanguages
.map(parseLanguage)
.filter((option): option is OptionType => option !== null)
.filter((option) => {
if (allowAllLanguages) {
return true;
}
return ACCURATE_LANGUAGES.includes(option.languageCode);
})
.sort((a, b) => a.languageName.localeCompare(b.languageName));
}, [supportedLanguages]);
// Find the selected option
const selectedOption = useMemo(() => {
if (!selectedLanguage || !selectedScript) return null;
const combinedValue = `${selectedLanguage}_${selectedScript}`;
return languageOptions.find(option => option.value === combinedValue) || null;
}, [selectedLanguage, selectedScript, languageOptions]);
const handleChange = (newValue: SingleValue<OptionType>) => {
if (newValue) {
onLanguageAndScriptSelect(newValue.languageCode, newValue.scriptCode);
} else {
onLanguageAndScriptSelect(null, null);
}
};
// Custom filterOption function using match-sorter
const filterOptions = useMemo(() => {
return (option: { label: string; value: string; data: OptionType }, inputValue: string) => {
if (!inputValue.trim()) return true;
// Use match-sorter to check if this individual option matches
const matches = matchSorter([option.data], inputValue, {
keys: [
'languageName', // Primary: language name
'scriptName', // Secondary: script name
'languageCode', // Tertiary: language code
'scriptCode', // Quaternary: script code
'label', // Fallback: full label
],
threshold: matchSorter.rankings.CONTAINS,
});
return matches.length > 0;
};
}, []);
if (error) {
return (
<div className="text-red-400 text-sm p-2 bg-red-900/20 rounded">
{error}
</div>
);
}
return (
<Select<OptionType>
value={selectedOption}
onChange={handleChange}
options={languageOptions}
placeholder={isLoading ? "Loading languages..." : "Select language..."}
isClearable
isDisabled={disabled || isLoading}
isSearchable
filterOption={(option, inputValue) => filterOptions(option, inputValue)}
components={{ Option, SingleValue }}
styles={customStyles}
menuPortalTarget={document.body}
menuPosition="fixed"
noOptionsMessage={({ inputValue }) =>
`No languages found matching "${inputValue}"`
}
// Performance optimizations
menuIsOpen={undefined} // Let react-select manage this
blurInputOnSelect={true}
closeMenuOnSelect={true}
hideSelectedOptions={false}
/>
);
};
export default LanguageSelector;
|