11 Commits
1.7.8 ... 1.8.0

Author SHA1 Message Date
IndieKKY
e66f85ff9f chore: release 1.8.0 2024-01-20 13:35:42 +08:00
IndieKKY
d97af83c9e 支持gemini 2024-01-20 13:35:26 +08:00
IndieKKY
c70fa81482 chore: release 1.7.11 2024-01-20 13:31:00 +08:00
IndieKKY
4dbce345c2 chore: release 1.7.10 2024-01-20 13:21:55 +08:00
IndieKKY
aa098df6a5 支持gemini 2024-01-20 13:21:44 +08:00
IndieKKY
fa99fa8b3d chore: release 1.7.9 2024-01-20 13:19:03 +08:00
IndieKKY
5078baca1b 支持gemini 2024-01-20 13:18:39 +08:00
IndieKKY
771a802728 支持gemini 2024-01-20 11:39:21 +08:00
IndieKKY
9038bf7128 文章视图加逗号 2024-01-20 10:31:59 +08:00
IndieKKY
f01e175b4e 保存下载类型选择 2024-01-20 10:21:27 +08:00
IndieKKY
8098d7cf9b 保存列表/文章视图选择 2024-01-20 10:19:47 +08:00
15 changed files with 271 additions and 68 deletions

View File

@@ -1,7 +1,7 @@
{ {
"name": "哔哩哔哩字幕列表", "name": "哔哩哔哩字幕列表",
"description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!", "description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!",
"version": "1.7.8", "version": "1.8.0",
"manifest_version": 3, "manifest_version": 3,
"permissions": [ "permissions": [
"storage" "storage"

View File

@@ -1,7 +1,7 @@
{ {
"private": true, "private": true,
"name": "bilibili-subtitle", "name": "bilibili-subtitle",
"version": "1.7.8", "version": "1.8.0",
"type": "module", "type": "module",
"description": "哔哩哔哩字幕列表", "description": "哔哩哔哩字幕列表",
"main": "index.js", "main": "index.js",

View File

@@ -3,12 +3,12 @@ import {
setAutoScroll, setAutoScroll,
setAutoTranslate, setAutoTranslate,
setCheckAutoScroll, setCheckAutoScroll,
setCompact,
setFoldAll, setFoldAll,
setNeedScroll, setNeedScroll,
setPage, setPage,
setSearchText, setSearchText,
setSegmentFold setSegmentFold,
setTempData
} from '../redux/envReducer' } from '../redux/envReducer'
import {useAppDispatch, useAppSelector} from '../hooks/redux' import {useAppDispatch, useAppSelector} from '../hooks/redux'
import { import {
@@ -44,8 +44,7 @@ const Body = () => {
const segments = useAppSelector(state => state.env.segments) const segments = useAppSelector(state => state.env.segments)
const foldAll = useAppSelector(state => state.env.foldAll) const foldAll = useAppSelector(state => state.env.foldAll)
const envData = useAppSelector(state => state.env.envData) const envData = useAppSelector(state => state.env.envData)
const compact = useAppSelector(state => state.env.compact) const compact = useAppSelector(state => state.env.tempData.compact)
const apiKey = useAppSelector(state => state.env.envData.apiKey)
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx) const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
const translateEnable = useAppSelector(state => state.env.envData.translateEnable) const translateEnable = useAppSelector(state => state.env.envData.translateEnable)
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable) const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
@@ -60,11 +59,15 @@ const Body = () => {
const searchText = useAppSelector(state => state.env.searchText) const searchText = useAppSelector(state => state.env.searchText)
const normalCallback = useCallback(() => { const normalCallback = useCallback(() => {
dispatch(setCompact(false)) dispatch(setTempData({
compact: false
}))
}, [dispatch]) }, [dispatch])
const compactCallback = useCallback(() => { const compactCallback = useCallback(() => {
dispatch(setCompact(true)) dispatch(setTempData({
compact: true
}))
}, [dispatch]) }, [dispatch])
const posCallback = useCallback(() => { const posCallback = useCallback(() => {
@@ -72,6 +75,7 @@ const Body = () => {
}, [dispatch]) }, [dispatch])
const onSummarizeAll = useCallback(() => { const onSummarizeAll = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (!apiKey) { if (!apiKey) {
dispatch(setPage(PAGE_SETTINGS)) dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!') toast.error('需要先设置ApiKey!')
@@ -94,7 +98,7 @@ const Body = () => {
} }
toast.success(`已添加${segments_.length}个总结任务!`) toast.success(`已添加${segments_.length}个总结任务!`)
} }
}, [addSummarizeTask, apiKey, curSummaryType, dispatch, segments]) }, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
const onFoldAll = useCallback(() => { const onFoldAll = useCallback(() => {
dispatch(setFoldAll(!foldAll)) dispatch(setFoldAll(!foldAll))
@@ -107,13 +111,14 @@ const Body = () => {
}, [dispatch, foldAll, segments]) }, [dispatch, foldAll, segments])
const toggleAutoTranslateCallback = useCallback(() => { const toggleAutoTranslateCallback = useCallback(() => {
if (envData.apiKey) { const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (apiKey) {
dispatch(setAutoTranslate(!autoTranslate)) dispatch(setAutoTranslate(!autoTranslate))
} else { } else {
dispatch(setPage(PAGE_SETTINGS)) dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!') toast.error('需要先设置ApiKey!')
} }
}, [autoTranslate, dispatch, envData.apiKey]) }, [autoTranslate, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey])
const onEnableAutoScroll = useCallback(() => { const onEnableAutoScroll = useCallback(() => {
dispatch(setAutoScroll(true)) dispatch(setAutoScroll(true))

View File

@@ -22,7 +22,7 @@ const CompactSegmentItem = (props: {
<span className={'pl-1 pr-0.5 py-0.5 cursor-pointer rounded-sm hover:bg-base-200'} onClick={moveCallback}> <span className={'pl-1 pr-0.5 py-0.5 cursor-pointer rounded-sm hover:bg-base-200'} onClick={moveCallback}>
<text className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</text> <text className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</text>
{display.sub && <text className='desc'>({display.sub})</text>}</span> {display.sub && <text className='desc'>({display.sub})</text>}</span>
<span>{!last && ' '}</span> <span className='text-base-content/75'>{!last && ','}</span>
</div> </div>
} }

View File

@@ -11,7 +11,7 @@ import {
import Popover from '../components/Popover' import Popover from '../components/Popover'
import {Placement} from '@popperjs/core/lib/enums' import {Placement} from '@popperjs/core/lib/enums'
import {useAppDispatch, useAppSelector} from '../hooks/redux' import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {setDownloadType, setEnvData, setPage} from '../redux/envReducer' import {setEnvData, setPage, setTempData} from '../redux/envReducer'
import {EventBusContext} from '../Router' import {EventBusContext} from '../Router'
import {EVENT_EXPAND, PAGE_SETTINGS} from '../const' import {EVENT_EXPAND, PAGE_SETTINGS} from '../const'
import {formatSrtTime, formatTime, formatVttTime} from '../util/util' import {formatSrtTime, formatTime, formatVttTime} from '../util/util'
@@ -62,7 +62,7 @@ const MoreBtn = (props: Props) => {
const data = useAppSelector(state => state.env.data) const data = useAppSelector(state => state.env.data)
const envReady = useAppSelector(state => state.env.envReady) const envReady = useAppSelector(state => state.env.envReady)
const envData = useAppSelector(state => state.env.envData) const envData = useAppSelector(state => state.env.envData)
const downloadType = useAppSelector(state => state.env.downloadType) const downloadType = useAppSelector(state => state.env.tempData.downloadType)
const [moreVisible, setMoreVisible] = useState(false) const [moreVisible, setMoreVisible] = useState(false)
const eventBus = useContext(EventBusContext) const eventBus = useContext(EventBusContext)
const segments = useAppSelector(state => state.env.segments) const segments = useAppSelector(state => state.env.segments)
@@ -162,7 +162,9 @@ const MoreBtn = (props: Props) => {
}, []) }, [])
const selectCallback = useCallback((e: any) => { const selectCallback = useCallback((e: any) => {
dispatch(setDownloadType(e.target.value)) dispatch(setTempData({
downloadType: e.target.value,
}))
}, [dispatch]) }, [dispatch])
const preventCallback = useCallback((e: any) => { const preventCallback = useCallback((e: any) => {

View File

@@ -66,19 +66,20 @@ const Summarize = (props: {
const {segment, segmentIdx, summary, float} = props const {segment, segmentIdx, summary, float} = props
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const apiKey = useAppSelector(state => state.env.envData.apiKey) const envData = useAppSelector(state => state.env.envData)
const fontSize = useAppSelector(state => state.env.envData.fontSize) const fontSize = useAppSelector(state => state.env.envData.fontSize)
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType) const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
const {addSummarizeTask} = useTranslate() const {addSummarizeTask} = useTranslate()
const onGenerate = useCallback(() => { const onGenerate = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (apiKey) { if (apiKey) {
addSummarizeTask(curSummaryType, segment).catch(console.error) addSummarizeTask(curSummaryType, segment).catch(console.error)
} else { } else {
dispatch(setPage(PAGE_SETTINGS)) dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!') toast.error('需要先设置ApiKey!')
} }
}, [addSummarizeTask, apiKey, curSummaryType, dispatch, segment]) }, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segment])
const onCopy = useCallback(() => { const onCopy = useCallback(() => {
if (summary != null) { if (summary != null) {
@@ -138,7 +139,7 @@ const SegmentCard = (props: {
const summarizeFloat = useAppSelector(state => state.env.envData.summarizeFloat) const summarizeFloat = useAppSelector(state => state.env.envData.summarizeFloat)
const fold = useAppSelector(state => state.env.fold) const fold = useAppSelector(state => state.env.fold)
const page = useAppSelector(state => state.env.page) const page = useAppSelector(state => state.env.page)
const compact = useAppSelector(state => state.env.compact) const compact = useAppSelector(state => state.env.tempData.compact)
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx) const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
const showCurrent = useMemo(() => curIdx != null && segment.startIdx <= curIdx && curIdx <= segment.endIdx, [curIdx, segment.endIdx, segment.startIdx]) const showCurrent = useMemo(() => curIdx != null && segment.startIdx <= curIdx && curIdx <= segment.endIdx, [curIdx, segment.endIdx, segment.startIdx])
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType) const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)

View File

@@ -18,7 +18,7 @@ const SegmentItem = (props: {
const ref = useRef<any>() const ref = useRef<any>()
const {move} = useSubtitle() const {move} = useSubtitle()
const compact = useAppSelector(state => state.env.compact) const compact = useAppSelector(state => state.env.tempData.compact)
const searchText = useAppSelector(state => state.env.searchText) const searchText = useAppSelector(state => state.env.searchText)
const searchResult = useAppSelector(state => state.env.searchResult) const searchResult = useAppSelector(state => state.env.searchResult)
const display = useMemo(() => { const display = useMemo(() => {

View File

@@ -63,12 +63,14 @@ const Settings = () => {
const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat) const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat)
const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''}) const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''})
const [serverUrlValue, setServerUrlValue] = useState(envData.serverUrl) const [serverUrlValue, setServerUrlValue] = useState(envData.serverUrl)
const [geminiApiKeyValue, { onChange: onChangeGeminiApiKeyValue }] = useEventTarget({initialValue: envData.geminiApiKey??''})
const [languageValue, { onChange: onChangeLanguageValue }] = useEventTarget({initialValue: envData.language??LANGUAGE_DEFAULT}) const [languageValue, { onChange: onChangeLanguageValue }] = useEventTarget({initialValue: envData.language??LANGUAGE_DEFAULT})
const [modelValue, { onChange: onChangeModelValue }] = useEventTarget({initialValue: envData.model??MODEL_DEFAULT}) const [modelValue, { onChange: onChangeModelValue }] = useEventTarget({initialValue: envData.model??MODEL_DEFAULT})
const [summarizeLanguageValue, { onChange: onChangeSummarizeLanguageValue }] = useEventTarget({initialValue: envData.summarizeLanguage??SUMMARIZE_LANGUAGE_DEFAULT}) const [summarizeLanguageValue, { onChange: onChangeSummarizeLanguageValue }] = useEventTarget({initialValue: envData.summarizeLanguage??SUMMARIZE_LANGUAGE_DEFAULT})
const [hideOnDisableAutoTranslateValue, setHideOnDisableAutoTranslateValue] = useState(envData.hideOnDisableAutoTranslate) const [hideOnDisableAutoTranslateValue, setHideOnDisableAutoTranslateValue] = useState(envData.hideOnDisableAutoTranslate)
const [themeValue, setThemeValue] = useState(envData.theme) const [themeValue, setThemeValue] = useState(envData.theme)
const [fontSizeValue, setFontSizeValue] = useState(envData.fontSize) const [fontSizeValue, setFontSizeValue] = useState(envData.fontSize)
const [aiTypeValue, setAiTypeValue] = useState(envData.aiType)
const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay) const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay)
const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words??WORDS_DEFAULT) const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words??WORDS_DEFAULT)
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT) const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
@@ -91,6 +93,12 @@ const Settings = () => {
} }
return list return list
}, []) }, [])
const apiKeySetted = useMemo(() => {
if (aiTypeValue === 'gemini') {
return !!geminiApiKeyValue
}
return !!apiKeyValue
}, [aiTypeValue, apiKeyValue, geminiApiKeyValue])
const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => { const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => {
setHideOnDisableAutoTranslateValue(e.target.checked) setHideOnDisableAutoTranslateValue(e.target.checked)
@@ -99,9 +107,11 @@ const Settings = () => {
const onSave = useCallback(() => { const onSave = useCallback(() => {
dispatch(setEnvData({ dispatch(setEnvData({
autoExpand: autoExpandValue, autoExpand: autoExpandValue,
aiType: aiTypeValue,
apiKey: apiKeyValue, apiKey: apiKeyValue,
serverUrl: serverUrlValue, serverUrl: serverUrlValue,
model: modelValue, model: modelValue,
geminiApiKey: geminiApiKeyValue,
translateEnable: translateEnableValue, translateEnable: translateEnableValue,
language: languageValue, language: languageValue,
hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue, hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue,
@@ -119,7 +129,7 @@ const Settings = () => {
})) }))
dispatch(setPage(PAGE_MAIN)) dispatch(setPage(PAGE_MAIN))
toast.success('保存成功') toast.success('保存成功')
}, [dispatch, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue]) }, [dispatch, aiTypeValue, geminiApiKeyValue, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue])
const onCancel = useCallback(() => { const onCancel = useCallback(() => {
dispatch(setPage(PAGE_MAIN)) dispatch(setPage(PAGE_MAIN))
@@ -165,6 +175,14 @@ const Settings = () => {
setFontSizeValue('large') setFontSizeValue('large')
}, []) }, [])
const onSelOpenai = useCallback(() => {
setAiTypeValue('openai')
}, [])
const onSelGemini = useCallback(() => {
setAiTypeValue('gemini')
}, [])
return <div className='text-sm overflow-y-auto' style={{ return <div className='text-sm overflow-y-auto' style={{
height: fold?undefined:`${totalHeight-HEADER_HEIGHT}px`, height: fold?undefined:`${totalHeight-HEADER_HEIGHT}px`,
}}> }}>
@@ -187,8 +205,15 @@ const Settings = () => {
<button onClick={onSelFontSize2} className={classNames('btn btn-xs no-animation', fontSizeValue === 'large'?'btn-active':'')}></button> <button onClick={onSelFontSize2} className={classNames('btn btn-xs no-animation', fontSizeValue === 'large'?'btn-active':'')}></button>
</div> </div>
</FormItem> </FormItem>
<FormItem title='AI类型' tip='不同AI质量可能有差异'>
<div className="btn-group">
<button onClick={onSelOpenai} className={classNames('btn btn-xs no-animation', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
<button onClick={onSelGemini} className={classNames('btn btn-xs no-animation', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
</div>
</FormItem>
</Section> </Section>
<Section title='openai配置'>
{(!aiTypeValue || aiTypeValue === 'openai') && <Section title='openai配置'>
<FormItem title='ApiKey' htmlFor='apiKey'> <FormItem title='ApiKey' htmlFor='apiKey'>
<input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx' value={apiKeyValue} onChange={onChangeApiKeyValue}/> <input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx' value={apiKeyValue} onChange={onChangeApiKeyValue}/>
</FormItem> </FormItem>
@@ -239,10 +264,52 @@ const Settings = () => {
}}/> }}/>
</FormItem>)} </FormItem>)}
</div>} </div>}
</Section> </Section>}
{aiTypeValue === 'gemini' && <Section title='gemini配置'>
<FormItem title='ApiKey' htmlFor='geminiApiKey'>
<input id='geminiApiKey' type='text' className='input input-sm input-bordered w-full' placeholder='xxx'
value={geminiApiKeyValue} onChange={onChangeGeminiApiKeyValue}/>
</FormItem>
<div className='flex justify-center'>
<a className='link text-xs' onClick={toggleMoreFold}>{moreFold ? '点击查看说明' : '点击折叠说明'}</a>
</div>
{!moreFold && <div>
<ul className='pl-3 list-decimal desc text-xs'>
<li><a className='link' href='https://makersuite.google.com/app/apikey' target='_blank'
rel="noreferrer">Google AI Studio</a> ()</li>
</ul>
</div>}
<div className='flex justify-center'>
<a className='link text-xs'
onClick={togglePromptsFold}>{promptsFold ? '点击查看提示词' : '点击折叠提示词'}</a>
</div>
{!promptsFold && <div>
{PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
<div>{item.name}</div>
<div className='link text-xs' onClick={() => {
setPromptsValue({
...promptsValue,
// @ts-expect-error
[item.type]: PROMPT_DEFAULTS[item.type] ?? ''
})
}}>
</div>
</div>} htmlFor={`prompt-${item.type}`}>
<textarea id={`prompt-${item.type}`} className='mt-2 textarea input-bordered w-full'
placeholder='留空使用默认提示词' value={promptsValue[item.type] ?? ''} onChange={(e) => {
setPromptsValue({
...promptsValue,
[item.type]: e.target.value
})
}}/>
</FormItem>)}
</div>}
</Section>}
<Section title={<div className='flex items-center'> <Section title={<div className='flex items-center'>
{!apiKeyValue && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'> {!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/> <IoWarning className='text-sm text-warning'/>
</div>} </div>}
</div>}> </div>}>
@@ -277,7 +344,7 @@ const Settings = () => {
</Section> </Section>
<Section title={<div className='flex items-center'> <Section title={<div className='flex items-center'>
{!apiKeyValue && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'> {!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/> <IoWarning className='text-sm text-warning'/>
</div>} </div>}
</div>}> </div>}>

View File

@@ -18,3 +18,16 @@ export const handleChatCompleteTask = async (task: Task) => {
throw new Error(`${task.resp.error.code as string??''} ${task.resp.error.message as string ??''}`) throw new Error(`${task.resp.error.code as string??''} ${task.resp.error.message as string ??''}`)
} }
} }
export const handleGeminiChatCompleteTask = async (task: Task) => {
const data = task.def.data
const resp = await fetch('https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': task.def.extra.geminiApiKey,
},
body: JSON.stringify(data),
})
task.resp = await resp.json()
}

View File

@@ -1,5 +1,5 @@
import {TASK_EXPIRE_TIME} from '../const' import {TASK_EXPIRE_TIME} from '../const'
import {handleChatCompleteTask} from './openaiService' import {handleChatCompleteTask, handleGeminiChatCompleteTask} from './openaiService'
export const tasksMap = new Map<string, Task>() export const tasksMap = new Map<string, Task>()
@@ -11,6 +11,9 @@ export const handleTask = async (task: Task) => {
case 'chatComplete': case 'chatComplete':
await handleChatCompleteTask(task) await handleChatCompleteTask(task)
break break
case 'geminiChatComplete':
await handleGeminiChatCompleteTask(task)
break
default: default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`任务类型不支持: ${task.def.type}`) throw new Error(`任务类型不支持: ${task.def.type}`)

View File

@@ -82,23 +82,39 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{subtitles}}', lineStr) prompt = prompt.replaceAll('{{subtitles}}', lineStr)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: 'chatComplete', type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: { data: envData.aiType === 'gemini'
model: envData.model??MODEL_DEFAULT, ?{
messages: [ contents: [
{ {
role: 'user', parts: [
content: prompt, {
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
} }
], :{
temperature: 0, model: envData.model??MODEL_DEFAULT,
n: 1, messages: [
stream: false, {
}, role: 'user',
content: prompt,
}
],
temperature: 0,
n: 1,
stream: false,
},
extra: { extra: {
type: 'translate', type: 'translate',
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
startIdx, startIdx,
size: lines.length, size: lines.length,
} }
@@ -117,10 +133,10 @@ const useTranslate = () => {
dispatch(addTaskId(task.id)) dispatch(addTaskId(task.id))
} }
} }
}, [data?.body, dispatch, envData.apiKey, envData.fetchAmount, envData.serverUrl, envData.prompts, title, language.name]) }, [data?.body, envData.fetchAmount, envData.prompts, envData.aiType, envData.serverUrl, envData.model, envData.apiKey, envData.geminiApiKey, language.name, title, dispatch])
const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => { const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => {
if (segment.text.length >= SUMMARIZE_THRESHOLD && envData.apiKey) { if (segment.text.length >= SUMMARIZE_THRESHOLD) {
let subtitles = '' let subtitles = ''
for (const item of segment.items) { for (const item of segment.items) {
subtitles += formatTime(item.from) + ' ' + item.content + '\n' subtitles += formatTime(item.from) + ' ' + item.content + '\n'
@@ -135,25 +151,41 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{segment}}', segment.text) prompt = prompt.replaceAll('{{segment}}', segment.text)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: 'chatComplete', type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: { data: envData.aiType === 'gemini'
model: envData.model??MODEL_DEFAULT, ?{
messages: [ contents: [
{ {
role: 'user', parts: [
content: prompt, {
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
} }
], :{
temperature: 0, model: envData.model??MODEL_DEFAULT,
n: 1, messages: [
stream: false, {
}, role: 'user',
content: prompt,
}
],
temperature: 0,
n: 1,
stream: false,
},
extra: { extra: {
type: 'summarize', type: 'summarize',
summaryType: type, summaryType: type,
startIdx: segment.startIdx, startIdx: segment.startIdx,
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
} }
} }
console.debug('addSummarizeTask', taskDef) console.debug('addSummarizeTask', taskDef)
@@ -162,7 +194,7 @@ const useTranslate = () => {
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef}) const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
dispatch(addTaskId(task.id)) dispatch(addTaskId(task.id))
} }
}, [dispatch, envData.apiKey, envData.prompts, envData.serverUrl, summarizeLanguage.name, title]) }, [dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, envData.model, envData.prompts, envData.serverUrl, summarizeLanguage.name, title])
const handleTranslate = useMemoizedFn((task: Task, content: string) => { const handleTranslate = useMemoizedFn((task: Task, content: string) => {
let map: {[key: string]: string} = {} let map: {[key: string]: string} = {}
@@ -221,7 +253,7 @@ const useTranslate = () => {
console.debug('getTask', taskResp.task) console.debug('getTask', taskResp.task)
const task: Task = taskResp.task const task: Task = taskResp.task
const taskType: string | undefined = task.def.extra?.type const taskType: string | undefined = task.def.extra?.type
const content = task.resp?.choices?.[0]?.message?.content?.trim() const content = envData.aiType === 'gemini'?task.resp?.candidates[0]?.content?.parts[0]?.text?.trim():task.resp?.choices?.[0]?.message?.content?.trim()
if (task.status === 'done') { if (task.status === 'done') {
// 异常提示 // 异常提示
if (task.error) { if (task.error) {
@@ -239,7 +271,7 @@ const useTranslate = () => {
} else { } else {
dispatch(delTaskId(taskId)) dispatch(delTaskId(taskId))
} }
}, [dispatch, handleSummarize, handleTranslate]) }, [dispatch, envData.aiType, handleSummarize, handleTranslate])
return {getFetch, getTask, addTask, addSummarizeTask} return {getFetch, getTask, addTask, addSummarizeTask}
} }

View File

@@ -17,7 +17,6 @@ interface EnvState {
autoScroll?: boolean autoScroll?: boolean
checkAutoScroll?: boolean checkAutoScroll?: boolean
curOffsetTop?: number curOffsetTop?: number
compact?: boolean // 是否紧凑视图
floatKeyPointsSegIdx?: number // segment的startIdx floatKeyPointsSegIdx?: number // segment的startIdx
noVideo?: boolean noVideo?: boolean
@@ -25,7 +24,6 @@ interface EnvState {
curIdx?: number // 从0开始 curIdx?: number // 从0开始
needScroll?: boolean needScroll?: boolean
currentTime?: number currentTime?: number
downloadType?: string
infos?: any[] infos?: any[]
curInfo?: any curInfo?: any
curFetched?: boolean curFetched?: boolean
@@ -81,7 +79,7 @@ export const slice = createSlice({
setEnvReady: (state) => { setEnvReady: (state) => {
state.envReady = true state.envReady = true
}, },
setTempData: (state, action: PayloadAction<TempData>) => { setTempData: (state, action: PayloadAction<Partial<TempData>>) => {
state.tempData = { state.tempData = {
...state.tempData, ...state.tempData,
...action.payload, ...action.payload,
@@ -102,9 +100,6 @@ export const slice = createSlice({
setFoldAll: (state, action: PayloadAction<boolean>) => { setFoldAll: (state, action: PayloadAction<boolean>) => {
state.foldAll = action.payload state.foldAll = action.payload
}, },
setCompact: (state, action: PayloadAction<boolean>) => {
state.compact = action.payload
},
setPage: (state, action: PayloadAction<string | undefined>) => { setPage: (state, action: PayloadAction<string | undefined>) => {
state.page = action.payload state.page = action.payload
}, },
@@ -230,9 +225,6 @@ export const slice = createSlice({
setNoVideo: (state, action: PayloadAction<boolean>) => { setNoVideo: (state, action: PayloadAction<boolean>) => {
state.noVideo = action.payload state.noVideo = action.payload
}, },
setDownloadType: (state, action: PayloadAction<string>) => {
state.downloadType = action.payload
},
setNeedScroll: (state, action: PayloadAction<boolean>) => { setNeedScroll: (state, action: PayloadAction<boolean>) => {
state.needScroll = action.payload state.needScroll = action.payload
}, },
@@ -275,7 +267,6 @@ export const {
setCurOffsetTop, setCurOffsetTop,
setFloatKeyPointsSegIdx, setFloatKeyPointsSegIdx,
setFoldAll, setFoldAll,
setCompact,
setSegmentFold, setSegmentFold,
setSummaryContent, setSummaryContent,
setSummaryStatus, setSummaryStatus,
@@ -290,7 +281,6 @@ export const {
addTaskId, addTaskId,
delTaskId, delTaskId,
setTaskIds, setTaskIds,
setDownloadType,
setAutoTranslate, setAutoTranslate,
setAutoScroll, setAutoScroll,
setNoVideo, setNoVideo,

10
src/typings.d.ts vendored
View File

@@ -1,9 +1,15 @@
interface EnvData { interface EnvData {
autoExpand?: boolean autoExpand?: boolean
flagDot?: boolean flagDot?: boolean
aiType?: 'openai' | 'gemini'
// openai
apiKey?: string apiKey?: string
serverUrl?: string serverUrl?: string
model?: string model?: string
// gemini
geminiApiKey?: string
translateEnable?: boolean translateEnable?: boolean
language?: string language?: string
hideOnDisableAutoTranslate?: boolean hideOnDisableAutoTranslate?: boolean
@@ -27,10 +33,12 @@ interface EnvData {
interface TempData { interface TempData {
curSummaryType: SummaryType curSummaryType: SummaryType
downloadType?: string
compact?: boolean // 是否紧凑视图
} }
interface TaskDef { interface TaskDef {
type: 'chatComplete' type: 'chatComplete' | 'geminiChatComplete'
serverUrl?: string serverUrl?: string
data: any data: any
extra?: any extra?: any

View File

@@ -253,7 +253,15 @@ export const extractJsonObject = (content: string) => {
const start = content.indexOf('```') const start = content.indexOf('```')
const end = content.lastIndexOf('```') const end = content.lastIndexOf('```')
if (start >= 0 && end >= 0) { if (start >= 0 && end >= 0) {
content = content.slice(start + 3, end) if (start === end) { // 异常情况
if (content.startsWith('```')) {
content = content.slice(3)
} else {
content = content.slice(0, -3)
}
} else {
content = content.slice(start + 3, end)
}
} }
// get content between { and } // get content between { and }
const start2 = content.indexOf('{') const start2 = content.indexOf('{')
@@ -269,7 +277,15 @@ export const extractJsonArray = (content: string) => {
const start = content.indexOf('```') const start = content.indexOf('```')
const end = content.lastIndexOf('```') const end = content.lastIndexOf('```')
if (start >= 0 && end >= 0) { if (start >= 0 && end >= 0) {
content = content.slice(start + 3, end) if (start === end) { // 异常情况
if (content.startsWith('```')) {
content = content.slice(3)
} else {
content = content.slice(0, -3)
}
} else {
content = content.slice(start + 3, end)
}
} }
// get content between [ and ] // get content between [ and ]
const start3 = content.indexOf('[') const start3 = content.indexOf('[')

View File

@@ -0,0 +1,66 @@
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { visualizer } from "rollup-plugin-visualizer";
import { crx } from "@crxjs/vite-plugin";
// manifest.json
var manifest_default = {
name: "\u54D4\u54E9\u54D4\u54E9\u5B57\u5E55\u5217\u8868",
description: "\u663E\u793AB\u7AD9\u89C6\u9891\u7684\u5B57\u5E55\u5217\u8868,\u53EF\u70B9\u51FB\u8DF3\u8F6C\u4E0E\u4E0B\u8F7D\u5B57\u5E55,\u5E76\u652F\u6301\u7FFB\u8BD1\u548C\u603B\u7ED3\u5B57\u5E55!",
version: "1.7.11",
manifest_version: 3,
permissions: [
"storage"
],
background: {
service_worker: "src/chrome/background.ts"
},
content_scripts: [
{
matches: ["https://www.bilibili.com/video/*", "https://www.bilibili.com/list/*"],
js: ["src/chrome/content-script.cjs"]
}
],
icons: {
"16": "favicon-16x16.png",
"32": "favicon-32x32.png",
"48": "favicon-48x48.png",
"128": "favicon-128x128.png"
},
action: {
default_popup: "index.html",
default_icon: {
"16": "favicon-16x16.png",
"32": "favicon-32x32.png",
"48": "favicon-48x48.png",
"128": "favicon-128x128.png"
}
}
};
// vite.config.ts
var vite_config_default = ({ mode }) => {
const plugins = [
react(),
visualizer()
];
if (mode === "production_chrome") {
plugins.push(crx({
manifest: manifest_default
}));
}
return defineConfig({
base: "/",
plugins,
css: {
modules: {
localsConvention: "camelCase"
}
}
});
};
export {
vite_config_default as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvZmVuZ3l1ZXhpYW5nL2RhdGEvcHJvamVjdC9iaWxpYmlsaS1zdWJ0aXRsZVwiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9maWxlbmFtZSA9IFwiL1VzZXJzL2Zlbmd5dWV4aWFuZy9kYXRhL3Byb2plY3QvYmlsaWJpbGktc3VidGl0bGUvdml0ZS5jb25maWcudHNcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfaW1wb3J0X21ldGFfdXJsID0gXCJmaWxlOi8vL1VzZXJzL2Zlbmd5dWV4aWFuZy9kYXRhL3Byb2plY3QvYmlsaWJpbGktc3VidGl0bGUvdml0ZS5jb25maWcudHNcIjtpbXBvcnQge2RlZmluZUNvbmZpZywgUGx1Z2luT3B0aW9ufSBmcm9tICd2aXRlJ1xuaW1wb3J0IHJlYWN0IGZyb20gJ0B2aXRlanMvcGx1Z2luLXJlYWN0J1xuaW1wb3J0IHt2aXN1YWxpemVyfSBmcm9tIFwicm9sbHVwLXBsdWdpbi12aXN1YWxpemVyXCI7XG5pbXBvcnQge2NyeH0gZnJvbSAnQGNyeGpzL3ZpdGUtcGx1Z2luJ1xuLy8gQHRzLWlnbm9yZVxuaW1wb3J0IG1hbmlmZXN0IGZyb20gJy4vbWFuaWZlc3QuanNvbidcblxuLy8gaHR0cHM6Ly92aXRlanMuZGV2L2NvbmZpZy9cbmV4cG9ydCBkZWZhdWx0ICh7bW9kZX0pID0+IHtcbiAgY29uc3QgcGx1Z2lucyA9IFtcbiAgICByZWFjdCgpLFxuICAgIHZpc3VhbGl6ZXIoKSBhcyBQbHVnaW5PcHRpb24sXG4gIF1cbiAgLy8gQHRzLWlnbm9yZVxuICBpZiAobW9kZSA9PT0gJ3Byb2R1Y3Rpb25fY2hyb21lJykge1xuICAgIHBsdWdpbnMucHVzaChjcngoe1xuICAgICAgbWFuaWZlc3QsXG4gICAgfSkpXG4gIH1cbiAgcmV0dXJuIGRlZmluZUNvbmZpZyh7XG4gICAgYmFzZTogJy8nLFxuICAgIHBsdWdpbnMsXG4gICAgY3NzOiB7XG4gICAgICBtb2R1bGVzOiB7XG4gICAgICAgIGxvY2Fsc0NvbnZlbnRpb246IFwiY2FtZWxDYXNlXCJcbiAgICAgIH1cbiAgICB9XG4gIH0pXG59XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQXdVLFNBQVEsb0JBQWlDO0FBQ2pYLE9BQU8sV0FBVztBQUNsQixTQUFRLGtCQUFpQjtBQUN6QixTQUFRLFdBQVU7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBS2xCLElBQU8sc0JBQVEsQ0FBQyxFQUFDLEtBQUksTUFBTTtBQUN6QixRQUFNLFVBQVU7QUFBQSxJQUNkLE1BQU07QUFBQSxJQUNOLFdBQVc7QUFBQSxFQUNiO0FBRUEsTUFBSSxTQUFTLHFCQUFxQjtBQUNoQyxZQUFRLEtBQUssSUFBSTtBQUFBLE1BQ2Y7QUFBQSxJQUNGLENBQUMsQ0FBQztBQUFBLEVBQ0o7QUFDQSxTQUFPLGFBQWE7QUFBQSxJQUNsQixNQUFNO0FBQUEsSUFDTjtBQUFBLElBQ0EsS0FBSztBQUFBLE1BQ0gsU0FBUztBQUFBLFFBQ1Asa0JBQWtCO0FBQUEsTUFDcEI7QUFBQSxJQUNGO0FBQUEsRUFDRixDQUFDO0FBQ0g7IiwKICAibmFtZXMiOiBbXQp9Cg==