You've already forked bilibili-subtitle
Compare commits
19 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
1a475d1f13 | ||
![]() |
4a1ea0dbbe | ||
![]() |
af80b8a51c | ||
![]() |
404ab904cc | ||
![]() |
d53884269a | ||
![]() |
e4693cde6a | ||
![]() |
fea22fae61 | ||
![]() |
d5b5b5d374 | ||
![]() |
17d4e60de0 | ||
![]() |
2cd633cbd4 | ||
![]() |
3ad198948f | ||
![]() |
774cc2726d | ||
![]() |
4765244638 | ||
![]() |
b0107c4959 | ||
![]() |
e900b11f05 | ||
![]() |
194df8525c | ||
![]() |
28bb3dbb96 | ||
![]() |
640f6d89fd | ||
![]() |
338e3145f2 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "bilibili-subtitle",
|
||||
"version": "1.12.0",
|
||||
"version": "1.14.1",
|
||||
"type": "module",
|
||||
"description": "哔哩哔哩字幕列表",
|
||||
"main": "index.js",
|
||||
@@ -15,7 +15,7 @@
|
||||
"dependencies": {
|
||||
"@crxjs/vite-plugin": "^1.0.14",
|
||||
"@kky002/kky-hooks": "^1.2.1",
|
||||
"@kky002/kky-message": "^0.2.0",
|
||||
"@kky002/kky-message": "^0.2.1",
|
||||
"@kky002/kky-ui": "^1.0.9",
|
||||
"@kky002/kky-util": "^1.13.13",
|
||||
"@logto/react": "1.0.0-beta.13",
|
||||
|
10
pnpm-lock.yaml
generated
10
pnpm-lock.yaml
generated
@@ -15,8 +15,8 @@ importers:
|
||||
specifier: ^1.2.1
|
||||
version: 1.2.1
|
||||
'@kky002/kky-message':
|
||||
specifier: ^0.2.0
|
||||
version: 0.2.0
|
||||
specifier: ^0.2.1
|
||||
version: 0.2.1
|
||||
'@kky002/kky-ui':
|
||||
specifier: ^1.0.9
|
||||
version: 1.0.9
|
||||
@@ -397,8 +397,8 @@ packages:
|
||||
'@kky002/kky-hooks@1.2.1':
|
||||
resolution: {integrity: sha512-AJM2gm75TtkZqOPd/WX0+4h/dfjSb8HlDQLwAJsYIHRNw8MQUKu32Ih6OxhKL2l9pdPsuj+S9/lBc4Cwu4tP+Q==}
|
||||
|
||||
'@kky002/kky-message@0.2.0':
|
||||
resolution: {integrity: sha512-bquH4+79xHYLgVGxfDHAHQgmkbJ8Wbx6U3vBR6fA6piheMATwVPW7c2scS0BMbB9F4w23I4fZj30nRWgZrcEig==}
|
||||
'@kky002/kky-message@0.2.1':
|
||||
resolution: {integrity: sha512-LIg4T89t3TmjflepZeOPH/OMN3xxwLE0AxnfDycTlCpjHAiuvm/Aj3IIHLfzqbz5azRaGNu2ZcUsrUdb2jAtiQ==}
|
||||
|
||||
'@kky002/kky-ui@1.0.9':
|
||||
resolution: {integrity: sha512-pepfRcLfC1eIQ1lsSJLWNr4PgdLqFLuvQMlitJy7W668yZ7qu8yAHSjg8A20R7HB4mFkJ+B96WETalOar1e/kA==}
|
||||
@@ -2846,7 +2846,7 @@ snapshots:
|
||||
lodash-es: 4.17.21
|
||||
react: 18.2.0
|
||||
|
||||
'@kky002/kky-message@0.2.0':
|
||||
'@kky002/kky-message@0.2.1':
|
||||
dependencies:
|
||||
'@kky002/kky-util': 1.13.13
|
||||
ahooks: 3.8.4(react@18.2.0)
|
||||
|
@@ -7,13 +7,21 @@ const getServerUrl = (serverUrl?: string) => {
|
||||
if (serverUrl.endsWith('/')) {
|
||||
serverUrl = serverUrl.slice(0, -1)
|
||||
}
|
||||
//如果serverUrl以https://generativelanguage.googleapis.com开头,则直接返回
|
||||
if (serverUrl.toLowerCase().startsWith('https://generativelanguage.googleapis.com')) {
|
||||
return serverUrl
|
||||
}
|
||||
//如果serverUrl不以/vxxx结尾,则添加/v1
|
||||
if (!/\/v\d+$/.test(serverUrl.toLowerCase())) {
|
||||
serverUrl += '/v1'
|
||||
}
|
||||
return serverUrl
|
||||
}
|
||||
|
||||
export const handleChatCompleteTask = async (task: Task) => {
|
||||
const data = task.def.data
|
||||
const serverUrl = getServerUrl(task.def.serverUrl)
|
||||
const resp = await fetch(`${serverUrl}/v1/chat/completions`, {
|
||||
const resp = await fetch(`${serverUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -28,16 +36,3 @@ export const handleChatCompleteTask = async (task: Task) => {
|
||||
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()
|
||||
}
|
||||
|
@@ -1,5 +1,5 @@
|
||||
import {TASK_EXPIRE_TIME} from '../consts/const'
|
||||
import {handleChatCompleteTask, handleGeminiChatCompleteTask} from './openaiService'
|
||||
import {handleChatCompleteTask} from './openaiService'
|
||||
|
||||
export const tasksMap = new Map<string, Task>()
|
||||
|
||||
@@ -11,9 +11,6 @@ export const handleTask = async (task: Task) => {
|
||||
case 'chatComplete':
|
||||
await handleChatCompleteTask(task)
|
||||
break
|
||||
case 'geminiChatComplete':
|
||||
await handleGeminiChatCompleteTask(task)
|
||||
break
|
||||
default:
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
throw new Error(`任务类型不支持: ${task.def.type}`)
|
||||
|
@@ -4,10 +4,8 @@ import { openOptionsPage } from '../utils/chromeUtils'
|
||||
|
||||
const ApiKeyReminder: React.FC = () => {
|
||||
const apiKey = useAppSelector(state => state.env.envData.apiKey)
|
||||
const geminiApiKey = useAppSelector(state => state.env.envData.geminiApiKey)
|
||||
const aiType = useAppSelector(state => state.env.envData.aiType)
|
||||
|
||||
if ((aiType === 'gemini' && geminiApiKey) || (aiType !== 'gemini' && apiKey)) {
|
||||
if (apiKey) {
|
||||
return null
|
||||
}
|
||||
|
||||
|
@@ -18,7 +18,7 @@ const Ask = (props: {
|
||||
const {addAskTask} = useTranslate()
|
||||
|
||||
const onRegenerate = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
if (segments != null && segments.length > 0) {
|
||||
addAskTask(ask.id, segments[0], ask.question).catch(console.error)
|
||||
@@ -26,7 +26,7 @@ const Ask = (props: {
|
||||
} else {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}, [addAskTask, ask.id, ask.question, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
|
||||
}, [addAskTask, ask.id, ask.question, envData.apiKey, segments])
|
||||
|
||||
const onAskFold = useCallback(() => {
|
||||
dispatch(mergeAskInfo({
|
||||
|
@@ -105,7 +105,7 @@ const Body = () => {
|
||||
}, [dispatch])
|
||||
|
||||
const onSummarizeAll = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (!apiKey) {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
return
|
||||
@@ -127,7 +127,7 @@ const Body = () => {
|
||||
}
|
||||
toast.success(`已添加${segments_.length}个总结任务!`)
|
||||
}
|
||||
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
|
||||
}, [addSummarizeTask, curSummaryType, envData.apiKey, segments])
|
||||
|
||||
const onFoldAll = useCallback(() => {
|
||||
dispatch(setFoldAll(!foldAll))
|
||||
@@ -146,13 +146,13 @@ const Body = () => {
|
||||
}, [asks, dispatch, foldAll, segments])
|
||||
|
||||
const toggleAutoTranslateCallback = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
dispatch(setAutoTranslate(!autoTranslate))
|
||||
} else {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}, [autoTranslate, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey])
|
||||
}, [autoTranslate, dispatch, envData.apiKey])
|
||||
|
||||
const onEnableAutoScroll = useCallback(() => {
|
||||
dispatch(setAutoScroll(true))
|
||||
@@ -185,7 +185,7 @@ const Body = () => {
|
||||
|
||||
const onAsk = useCallback(() => {
|
||||
if ((envData.askEnabled ?? ASK_ENABLED_DEFAULT) && searchText) {
|
||||
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
if (segments != null && segments.length > 0) {
|
||||
const id = v4()
|
||||
@@ -201,7 +201,7 @@ const Body = () => {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}
|
||||
}, [addAskTask, dispatch, envData.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, searchText, segments])
|
||||
}, [addAskTask, dispatch, envData.apiKey, envData.askEnabled, searchText, segments])
|
||||
|
||||
// service
|
||||
useKeyService()
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
|
||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {setFloatKeyPointsSegIdx, setSegmentFold, setTempData} from '../redux/envReducer'
|
||||
import {setFloatKeyPointsSegIdx, setNeedScroll, setSegmentFold, setTempData} from '../redux/envReducer'
|
||||
import classNames from 'classnames'
|
||||
import {FaClipboardList, FaComments} from 'react-icons/fa'
|
||||
import {SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
|
||||
@@ -13,6 +13,7 @@ import SegmentItem from './SegmentItem'
|
||||
import {stopPopFunc} from '../utils/util'
|
||||
import useSubtitle from '../hooks/useSubtitle'
|
||||
import DebateChat from './DebateChat'
|
||||
import { RootState } from '../store'
|
||||
|
||||
const SummarizeItemOverview = (props: {
|
||||
segment: Segment
|
||||
@@ -25,7 +26,7 @@ const SummarizeItemOverview = (props: {
|
||||
|
||||
const {move} = useSubtitle()
|
||||
const time = parseStrTimeToSeconds(overviewItem.time)
|
||||
const currentTime = useAppSelector(state => state.env.currentTime)
|
||||
const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
|
||||
const isIn = useMemo(() => {
|
||||
if (currentTime != null) {
|
||||
// check in current segment
|
||||
@@ -73,13 +74,13 @@ const Summarize = (props: {
|
||||
const {addSummarizeTask} = useTranslate()
|
||||
|
||||
const onGenerate = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
addSummarizeTask(curSummaryType, segment).catch(console.error)
|
||||
} else {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segment])
|
||||
}, [addSummarizeTask, curSummaryType, envData.apiKey, segment])
|
||||
|
||||
const onCopy = useCallback(() => {
|
||||
if (summary != null) {
|
||||
@@ -158,6 +159,7 @@ const SegmentCard = (props: {
|
||||
}
|
||||
return undefined
|
||||
}, [curSummaryType, segment.summaries])
|
||||
const {move} = useSubtitle()
|
||||
|
||||
const onFold = useCallback(() => {
|
||||
dispatch(setSegmentFold({
|
||||
@@ -166,6 +168,21 @@ const SegmentCard = (props: {
|
||||
}))
|
||||
}, [dispatch, segment.fold, segment.startIdx])
|
||||
|
||||
const onChapterClick = useCallback(() => {
|
||||
if (segment.items && segment.items.length > 0) {
|
||||
// 展开当前segment
|
||||
if (segment.fold) {
|
||||
dispatch(setSegmentFold({
|
||||
segmentStartIdx: segment.startIdx,
|
||||
fold: false
|
||||
}))
|
||||
}
|
||||
|
||||
const firstItem = segment.items[0]
|
||||
move(firstItem.from, false)
|
||||
}
|
||||
}, [dispatch, move, segment.fold, segment.items, segment.startIdx])
|
||||
|
||||
// 检测设置floatKeyPointsSegIdx
|
||||
useEffect(() => {
|
||||
if (summarizeFloat) { // 已启用
|
||||
@@ -211,6 +228,10 @@ const SegmentCard = (props: {
|
||||
|
||||
return <div
|
||||
className={classNames('border border-base-300 bg-base-200/25 rounded flex flex-col m-1.5 p-1.5 gap-1', showCurrent && 'shadow shadow-md')}>
|
||||
{/* 章节标题 */}
|
||||
{segment.chapterTitle && <div className='text-center py-1 px-2 bg-primary/10 rounded text-sm font-semibold text-primary border-b border-primary/20 cursor-pointer hover:bg-primary/20 transition-colors' onClick={onChapterClick}>
|
||||
{segment.chapterTitle}
|
||||
</div>}
|
||||
<div className='relative flex justify-center min-h-[20px]'>
|
||||
{segments != null && segments.length > 0 &&
|
||||
<div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'>
|
||||
|
@@ -268,6 +268,7 @@ export const SUMMARIZE_LANGUAGE_DEFAULT = 'cn'
|
||||
export const SUMMARIZE_ALL_THRESHOLD = 5
|
||||
export const ASK_ENABLED_DEFAULT = true
|
||||
export const DEFAULT_SERVER_URL_OPENAI = 'https://api.openai.com'
|
||||
export const DEFAULT_SERVER_URL_GEMINI = 'https://generativelanguage.googleapis.com/v1beta/openai/'
|
||||
export const CUSTOM_MODEL_TOKENS = 16385
|
||||
|
||||
export const MODEL_TIP = '推荐gpt-4o-mini,能力强,价格低,token上限大'
|
||||
@@ -283,7 +284,6 @@ export const MODELS = [{
|
||||
code: 'custom',
|
||||
name: '自定义',
|
||||
}]
|
||||
export const GEMINI_TOKENS = 32768
|
||||
export const MODEL_DEFAULT = MODELS[0].code
|
||||
export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {}
|
||||
for (const model of MODELS) {
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import { setAuthor, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
|
||||
import { setAuthor, setChapters, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
|
||||
import { useAppDispatch, useAppSelector } from './redux'
|
||||
import { AllAPPMessages, AllExtensionMessages, AllInjectMessages } from '@/message-typings'
|
||||
import { useMessaging, useMessagingService } from '@kky002/kky-message'
|
||||
@@ -19,6 +19,7 @@ const useMessageService = () => {
|
||||
dispatch(setData(undefined))
|
||||
},
|
||||
SET_VIDEO_INFO: async (params, context: MethodContext) => {
|
||||
dispatch(setChapters(params.chapters))
|
||||
dispatch(setInfos(params.infos))
|
||||
dispatch(setUrl(params.url))
|
||||
dispatch(setTitle(params.title))
|
||||
|
@@ -4,22 +4,20 @@ import {
|
||||
setCurFetched,
|
||||
setCurIdx,
|
||||
setCurInfo,
|
||||
setCurrentTime,
|
||||
setData,
|
||||
setInfos,
|
||||
setNoVideo,
|
||||
setSegmentFold,
|
||||
setSegments,
|
||||
setTitle,
|
||||
setTotalHeight,
|
||||
setUrl,
|
||||
setTempData,
|
||||
} from '../redux/envReducer'
|
||||
import {EventBusContext} from '../Router'
|
||||
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
|
||||
import {EVENT_EXPAND, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
|
||||
import {useAsyncEffect, useInterval} from 'ahooks'
|
||||
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
|
||||
import { useMessage } from './useMessageService'
|
||||
import { setCurrentTime } from '../redux/currentTimeReducer'
|
||||
import { RootState } from '../store'
|
||||
|
||||
/**
|
||||
* Service是单例,类似后端的服务概念
|
||||
@@ -31,10 +29,11 @@ const useSubtitleService = () => {
|
||||
const curFetched = useAppSelector(state => state.env.curFetched)
|
||||
const fold = useAppSelector(state => state.env.fold)
|
||||
const envReady = useAppSelector(state => state.env.envReady)
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const data = useAppSelector(state => state.env.data)
|
||||
const currentTime = useAppSelector(state => state.env.currentTime)
|
||||
const curIdx = useAppSelector(state => state.env.curIdx)
|
||||
const envData = useAppSelector((state: RootState) => state.env.envData)
|
||||
const data = useAppSelector((state: RootState) => state.env.data)
|
||||
const chapters = useAppSelector((state: RootState) => state.env.chapters)
|
||||
const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
|
||||
const curIdx = useAppSelector((state: RootState) => state.env.curIdx)
|
||||
const eventBus = useContext(EventBusContext)
|
||||
const needScroll = useAppSelector(state => state.env.needScroll)
|
||||
const segments = useAppSelector(state => state.env.segments)
|
||||
@@ -113,19 +112,22 @@ const useSubtitleService = () => {
|
||||
|
||||
// 更新当前位置
|
||||
useEffect(() => {
|
||||
let curIdx
|
||||
let newCurIdx
|
||||
if (((data?.body) != null) && currentTime) {
|
||||
for (let i=0; i<data.body.length; i++) {
|
||||
const item = data.body[i]
|
||||
if (item.from && currentTime < item.from) {
|
||||
break
|
||||
} else {
|
||||
curIdx = i
|
||||
newCurIdx = i
|
||||
}
|
||||
}
|
||||
}
|
||||
dispatch(setCurIdx(curIdx))
|
||||
}, [currentTime, data?.body, dispatch])
|
||||
// 只有当索引发生变化时才更新状态
|
||||
if (newCurIdx !== curIdx) {
|
||||
dispatch(setCurIdx(newCurIdx))
|
||||
}
|
||||
}, [currentTime, data?.body, dispatch, curIdx])
|
||||
|
||||
// 需要滚动 => segment自动展开
|
||||
useEffect(() => {
|
||||
@@ -152,33 +154,83 @@ const useSubtitleService = () => {
|
||||
if (envData.summarizeEnable) { // 分段
|
||||
let size = envData.words
|
||||
if (!size) { // 默认
|
||||
if (envData.aiType === 'gemini') {
|
||||
size = GEMINI_TOKENS*WORDS_RATE
|
||||
} else {
|
||||
size = getModelMaxTokens(envData)*WORDS_RATE
|
||||
}
|
||||
size = getModelMaxTokens(envData)*WORDS_RATE
|
||||
}
|
||||
size = Math.max(size, WORDS_MIN)
|
||||
|
||||
segments = []
|
||||
let transcriptItems: TranscriptItem[] = []
|
||||
let totalLength = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
transcriptItems.push(item)
|
||||
totalLength += item.content.length
|
||||
if (totalLength >= size || i === items.length-1) { // new segment or last
|
||||
// add
|
||||
segments.push({
|
||||
items: transcriptItems,
|
||||
startIdx: transcriptItems[0].idx,
|
||||
endIdx: transcriptItems[transcriptItems.length - 1].idx,
|
||||
text: getWholeText(transcriptItems.map(item => item.content)),
|
||||
summaries: {},
|
||||
|
||||
// 如果启用章节模式且有章节信息,按章节分割
|
||||
if ((envData.chapterMode ?? true) && chapters && chapters.length > 0) {
|
||||
for (let chapterIdx = 0; chapterIdx < chapters.length; chapterIdx++) {
|
||||
const chapter = chapters[chapterIdx]
|
||||
const nextChapter = chapters[chapterIdx + 1]
|
||||
|
||||
// 找到属于当前章节的字幕项
|
||||
const chapterItems = items.filter(item => {
|
||||
const itemTime = item.from
|
||||
return itemTime >= chapter.from && (nextChapter ? itemTime < nextChapter.from : true)
|
||||
})
|
||||
// reset
|
||||
transcriptItems = []
|
||||
totalLength = 0
|
||||
|
||||
if (chapterItems.length === 0) continue
|
||||
|
||||
// 如果章节内容过长,需要进一步分割
|
||||
const chapterText = getWholeText(chapterItems.map(item => item.content))
|
||||
if (chapterText.length <= size) {
|
||||
// 章节内容不长,作为一个segment
|
||||
segments.push({
|
||||
items: chapterItems,
|
||||
startIdx: chapterItems[0].idx,
|
||||
endIdx: chapterItems[chapterItems.length - 1].idx,
|
||||
text: chapterText,
|
||||
chapterTitle: chapter.content,
|
||||
summaries: {},
|
||||
})
|
||||
} else {
|
||||
// 章节内容过长,需要分割成多个segment
|
||||
let transcriptItems: TranscriptItem[] = []
|
||||
let totalLength = 0
|
||||
for (let i = 0; i < chapterItems.length; i++) {
|
||||
const item = chapterItems[i]
|
||||
transcriptItems.push(item)
|
||||
totalLength += item.content.length
|
||||
if (totalLength >= size || i === chapterItems.length - 1) {
|
||||
segments.push({
|
||||
items: transcriptItems,
|
||||
startIdx: transcriptItems[0].idx,
|
||||
endIdx: transcriptItems[transcriptItems.length - 1].idx,
|
||||
text: getWholeText(transcriptItems.map(item => item.content)),
|
||||
chapterTitle: chapter.content,
|
||||
summaries: {},
|
||||
})
|
||||
// reset
|
||||
transcriptItems = []
|
||||
totalLength = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 没有章节信息,按原来的逻辑分割
|
||||
let transcriptItems: TranscriptItem[] = []
|
||||
let totalLength = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
transcriptItems.push(item)
|
||||
totalLength += item.content.length
|
||||
if (totalLength >= size || i === items.length-1) { // new segment or last
|
||||
// add
|
||||
segments.push({
|
||||
items: transcriptItems,
|
||||
startIdx: transcriptItems[0].idx,
|
||||
endIdx: transcriptItems[transcriptItems.length - 1].idx,
|
||||
text: getWholeText(transcriptItems.map(item => item.content)),
|
||||
summaries: {},
|
||||
})
|
||||
// reset
|
||||
transcriptItems = []
|
||||
totalLength = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { // 都放一个分段
|
||||
@@ -192,12 +244,15 @@ const useSubtitleService = () => {
|
||||
}
|
||||
}
|
||||
dispatch(setSegments(segments))
|
||||
}, [data?.body, dispatch, envData])
|
||||
}, [data?.body, dispatch, envData, chapters])
|
||||
|
||||
// 每0.5秒更新当前视频时间
|
||||
useInterval(() => {
|
||||
sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => {
|
||||
dispatch(setCurrentTime(status.currentTime))
|
||||
// 只有当时间发生显著变化时才更新状态(差异大于0.1秒),避免不必要的重新渲染
|
||||
if (currentTime == null || Math.abs(status.currentTime - currentTime) > 0.1) {
|
||||
dispatch(setCurrentTime(status.currentTime))
|
||||
}
|
||||
})
|
||||
}, 500)
|
||||
|
||||
|
@@ -88,24 +88,9 @@ const useTranslate = () => {
|
||||
prompt = prompt.replaceAll('{{subtitles}}', lineStr)
|
||||
|
||||
const taskDef: TaskDef = {
|
||||
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
|
||||
type: 'chatComplete',
|
||||
serverUrl: envData.serverUrl,
|
||||
data: envData.aiType === 'gemini'
|
||||
?{
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{
|
||||
text: prompt
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 2048
|
||||
}
|
||||
}
|
||||
:{
|
||||
data: {
|
||||
model: getModel(envData),
|
||||
messages: [
|
||||
{
|
||||
@@ -120,7 +105,6 @@ const useTranslate = () => {
|
||||
extra: {
|
||||
type: 'translate',
|
||||
apiKey: envData.apiKey,
|
||||
geminiApiKey: envData.geminiApiKey,
|
||||
startIdx,
|
||||
size: lines.length,
|
||||
}
|
||||
@@ -165,24 +149,9 @@ const useTranslate = () => {
|
||||
prompt = prompt.replaceAll('{{segment}}', segment.text)
|
||||
|
||||
const taskDef: TaskDef = {
|
||||
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
|
||||
type: 'chatComplete',
|
||||
serverUrl: envData.serverUrl,
|
||||
data: envData.aiType === 'gemini'
|
||||
?{
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{
|
||||
text: prompt
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 2048
|
||||
}
|
||||
}
|
||||
:{
|
||||
data: {
|
||||
model: getModel(envData),
|
||||
messages: [
|
||||
{
|
||||
@@ -199,7 +168,6 @@ const useTranslate = () => {
|
||||
summaryType: type,
|
||||
startIdx: segment.startIdx,
|
||||
apiKey: envData.apiKey,
|
||||
geminiApiKey: envData.geminiApiKey,
|
||||
}
|
||||
}
|
||||
console.debug('addSummarizeTask', taskDef)
|
||||
@@ -220,24 +188,9 @@ const useTranslate = () => {
|
||||
prompt = prompt.replaceAll('{{question}}', question)
|
||||
|
||||
const taskDef: TaskDef = {
|
||||
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
|
||||
type: 'chatComplete',
|
||||
serverUrl: envData.serverUrl,
|
||||
data: envData.aiType === 'gemini'
|
||||
?{
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{
|
||||
text: prompt
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 2048
|
||||
}
|
||||
}
|
||||
:{
|
||||
data: {
|
||||
model: getModel(envData),
|
||||
messages: [
|
||||
{
|
||||
@@ -253,7 +206,6 @@ const useTranslate = () => {
|
||||
type: 'ask',
|
||||
// startIdx: segment.startIdx,
|
||||
apiKey: envData.apiKey,
|
||||
geminiApiKey: envData.geminiApiKey,
|
||||
askId: id,
|
||||
}
|
||||
}
|
||||
@@ -335,7 +287,7 @@ const useTranslate = () => {
|
||||
console.debug('getTask', taskResp.task)
|
||||
const task: Task = taskResp.task
|
||||
const taskType: string | undefined = task.def.extra?.type
|
||||
const content = envData.aiType === 'gemini'?task.resp?.candidates[0]?.content?.parts[0]?.text?.trim():task.resp?.choices?.[0]?.message?.content?.trim()
|
||||
const content = task.resp?.choices?.[0]?.message?.content?.trim()
|
||||
if (task.status === 'done') {
|
||||
// 异常提示
|
||||
if (task.error) {
|
||||
@@ -355,7 +307,7 @@ const useTranslate = () => {
|
||||
} else {
|
||||
dispatch(delTaskId(taskId))
|
||||
}
|
||||
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate, sendExtension])
|
||||
}, [dispatch, handleAsk, handleSummarize, handleTranslate, sendExtension])
|
||||
|
||||
return {getFetch, getTask, addTask, addSummarizeTask, addAskTask}
|
||||
}
|
||||
|
@@ -161,6 +161,21 @@ const debug = (...args: any[]) => {
|
||||
if (aidOrBvid) {
|
||||
// aid,pages
|
||||
let cid: string | undefined
|
||||
/**
|
||||
* [
|
||||
{
|
||||
"type": 2,
|
||||
"from": 0,
|
||||
"to": 152, //单位秒
|
||||
"content": "发现美",
|
||||
"imgUrl": "http://i0.hdslb.com/bfs/vchapter/29168372111_0.jpg",
|
||||
"logoUrl": "",
|
||||
"team_type": "",
|
||||
"team_name": ""
|
||||
}
|
||||
]
|
||||
*/
|
||||
let chapters: any[] = []
|
||||
let subtitles
|
||||
if (aidOrBvid.toLowerCase().startsWith('av')) { // avxxx
|
||||
aid = parseInt(aidOrBvid.slice(2))
|
||||
@@ -170,6 +185,7 @@ const debug = (...args: any[]) => {
|
||||
author = pages[0].owner?.name
|
||||
title = pages[0].part
|
||||
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
|
||||
chapters = res.data.view_points ?? []
|
||||
subtitles = res.data.subtitle.subtitles
|
||||
})
|
||||
} else { // bvxxx
|
||||
@@ -182,10 +198,14 @@ const debug = (...args: any[]) => {
|
||||
pages = res.data.pages
|
||||
})
|
||||
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid!}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
|
||||
chapters = res.data.view_points ?? []
|
||||
subtitles = res.data.subtitle.subtitles
|
||||
})
|
||||
}
|
||||
|
||||
//筛选chapters里type为2的
|
||||
chapters = chapters.filter(chapter => chapter.type === 2)
|
||||
|
||||
// pagesMap
|
||||
pagesMap = {}
|
||||
pages.forEach(page => {
|
||||
@@ -202,6 +222,7 @@ const debug = (...args: any[]) => {
|
||||
ctime,
|
||||
author,
|
||||
pages,
|
||||
chapters,
|
||||
infos: subtitles,
|
||||
})
|
||||
}
|
||||
|
2
src/message-typings.d.ts
vendored
2
src/message-typings.d.ts
vendored
@@ -80,7 +80,7 @@ interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
|
||||
method: 'SET_INFOS'
|
||||
}
|
||||
|
||||
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, infos: any }> {
|
||||
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, chapters: any, infos: any }> {
|
||||
method: 'SET_VIDEO_INFO'
|
||||
}
|
||||
|
||||
|
@@ -4,8 +4,8 @@ import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {
|
||||
ASK_ENABLED_DEFAULT,
|
||||
CUSTOM_MODEL_TOKENS,
|
||||
DEFAULT_SERVER_URL_GEMINI,
|
||||
DEFAULT_SERVER_URL_OPENAI,
|
||||
GEMINI_TOKENS,
|
||||
LANGUAGE_DEFAULT,
|
||||
LANGUAGES,
|
||||
MODEL_DEFAULT,
|
||||
@@ -77,9 +77,9 @@ const OptionsPage = () => {
|
||||
const {value: askEnabledValue, onChange: setAskEnabledValue} = useEventChecked(envData.askEnabled??ASK_ENABLED_DEFAULT)
|
||||
const {value: cnSearchEnabledValue, onChange: setCnSearchEnabledValue} = useEventChecked(envData.cnSearchEnabled)
|
||||
const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat)
|
||||
const {value: chapterModeValue, onChange: setChapterModeValue} = useEventChecked(envData.chapterMode ?? true)
|
||||
const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''})
|
||||
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 [modelValue, { onChange: onChangeModelValue }] = useEventTarget({initialValue: envData.model??MODEL_DEFAULT})
|
||||
const [customModelValue, { onChange: onChangeCustomModelValue }] = useEventTarget({initialValue: envData.customModel})
|
||||
@@ -88,7 +88,6 @@ const OptionsPage = () => {
|
||||
const [hideOnDisableAutoTranslateValue, setHideOnDisableAutoTranslateValue] = useState(envData.hideOnDisableAutoTranslate)
|
||||
const [themeValue, setThemeValue] = useState(envData.theme)
|
||||
const [fontSizeValue, setFontSizeValue] = useState(envData.fontSize)
|
||||
const [aiTypeValue, setAiTypeValue] = useState(envData.aiType)
|
||||
const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay)
|
||||
const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words)
|
||||
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
|
||||
@@ -109,11 +108,8 @@ const OptionsPage = () => {
|
||||
return list
|
||||
}, [])
|
||||
const apiKeySetted = useMemo(() => {
|
||||
if (aiTypeValue === 'gemini') {
|
||||
return !!geminiApiKeyValue
|
||||
}
|
||||
return !!apiKeyValue
|
||||
}, [aiTypeValue, apiKeyValue, geminiApiKeyValue])
|
||||
}, [apiKeyValue])
|
||||
|
||||
const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => {
|
||||
setHideOnDisableAutoTranslateValue(e.target.checked)
|
||||
@@ -124,13 +120,11 @@ const OptionsPage = () => {
|
||||
sidePanel: sidePanelValue,
|
||||
manualInsert: !autoInsertValue,
|
||||
autoExpand: autoExpandValue,
|
||||
aiType: aiTypeValue,
|
||||
apiKey: apiKeyValue,
|
||||
serverUrl: serverUrlValue,
|
||||
model: modelValue,
|
||||
customModel: customModelValue,
|
||||
customModelTokens: customModelTokensValue,
|
||||
geminiApiKey: geminiApiKeyValue,
|
||||
translateEnable: translateEnableValue,
|
||||
language: languageValue,
|
||||
hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue,
|
||||
@@ -146,6 +140,7 @@ const OptionsPage = () => {
|
||||
searchEnabled: searchEnabledValue,
|
||||
cnSearchEnabled: cnSearchEnabledValue,
|
||||
askEnabled: askEnabledValue,
|
||||
chapterMode: chapterModeValue,
|
||||
}))
|
||||
toast.success('保存成功')
|
||||
sendExtension(null, 'CLOSE_SIDE_PANEL')
|
||||
@@ -153,7 +148,7 @@ const OptionsPage = () => {
|
||||
setTimeout(() => {
|
||||
window.close()
|
||||
}, 3000)
|
||||
}, [dispatch, sendExtension, sidePanelValue, autoInsertValue, autoExpandValue, aiTypeValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, geminiApiKeyValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue])
|
||||
}, [dispatch, sendExtension, sidePanelValue, autoInsertValue, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue, chapterModeValue])
|
||||
|
||||
const onCancel = useCallback(() => {
|
||||
window.close()
|
||||
@@ -199,14 +194,6 @@ const OptionsPage = () => {
|
||||
setFontSizeValue('large')
|
||||
}, [])
|
||||
|
||||
const onSelOpenai = useCallback(() => {
|
||||
setAiTypeValue('openai')
|
||||
}, [])
|
||||
|
||||
const onSelGemini = useCallback(() => {
|
||||
setAiTypeValue('gemini')
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className='container mx-auto max-w-3xl p-4'>
|
||||
<OptionCard title="通用配置">
|
||||
@@ -222,6 +209,10 @@ const OptionsPage = () => {
|
||||
<input id='autoExpand' type='checkbox' className='toggle toggle-primary' checked={autoExpandValue}
|
||||
onChange={setAutoExpandValue}/>
|
||||
</FormItem>}
|
||||
<FormItem title='章节模式' htmlFor='chapterMode' tip='如果视频包含章节,则会按章节分割(会导致总结只能按章节来)'>
|
||||
<input id='chapterMode' type='checkbox' className='toggle toggle-primary' checked={chapterModeValue}
|
||||
onChange={setChapterModeValue}/>
|
||||
</FormItem>
|
||||
<FormItem title='主题'>
|
||||
<div className="btn-group">
|
||||
<button onClick={onSelTheme1} className={classNames('btn btn-sm no-animation', (!themeValue || themeValue === 'system')?'btn-active':'')}>系统</button>
|
||||
@@ -235,32 +226,32 @@ const OptionsPage = () => {
|
||||
<button onClick={onSelFontSize2} className={classNames('btn btn-sm no-animation', fontSizeValue === 'large'?'btn-active':'')}>加大</button>
|
||||
</div>
|
||||
</FormItem>
|
||||
<FormItem title='AI类型' tip='OPENAI质量更高'>
|
||||
<div className="btn-group">
|
||||
<button onClick={onSelOpenai} className={classNames('btn btn-sm', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
|
||||
<button onClick={onSelGemini} className={classNames('btn btn-sm', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
|
||||
</div>
|
||||
</FormItem>
|
||||
</OptionCard>
|
||||
|
||||
<OptionCard title="AI 配置">
|
||||
{(!aiTypeValue || aiTypeValue === '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}/>
|
||||
</FormItem>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='服务器' htmlFor='serverUrl'>
|
||||
{<FormItem title='服务器' htmlFor='serverUrl'>
|
||||
<input id='serverUrl' type='text' className='input input-sm input-bordered w-full'
|
||||
placeholder={DEFAULT_SERVER_URL_OPENAI} value={serverUrlValue}
|
||||
onChange={e => setServerUrlValue(e.target.value)}/>
|
||||
</FormItem>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <div>
|
||||
{<div>
|
||||
<div className='desc text-sm text-center'>
|
||||
<div className='flex justify-center font-semibold'>【官方地址】</div>
|
||||
<div className='flex justify-center font-semibold'>【OpenAI官方地址】</div>
|
||||
<div>官方网址:<a className='link link-primary' href='https://platform.openai.com/' target='_blank'
|
||||
rel="noreferrer">点击访问</a></div>
|
||||
<div>服务器地址:<a className='link link-primary'
|
||||
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_OPENAI)}
|
||||
rel='noreferrer'>点击设置</a></div>
|
||||
<div className='flex justify-center font-semibold'>【Gemini官方地址】</div>
|
||||
<div>官方网址:<a className='link link-primary' href='https://aistudio.google.com/apikey' target='_blank'
|
||||
rel="noreferrer">点击访问</a></div>
|
||||
<div>服务器地址:<a className='link link-primary'
|
||||
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_GEMINI)}
|
||||
rel='noreferrer'>点击设置</a></div>
|
||||
<div className='flex justify-center font-semibold'>【第三方国内代理】</div>
|
||||
<div>代理网址:<a className='link link-primary' href='https://api.kksj.org/register?aff=ucVc'
|
||||
target='_blank'
|
||||
@@ -272,13 +263,13 @@ const OptionsPage = () => {
|
||||
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>国内可访问,无需🪜<FaGripfire/></div>
|
||||
</div>
|
||||
</div>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='模型选择' htmlFor='modelSel' tip='注意,不同模型有不同价格与token限制'>
|
||||
{<FormItem title='模型选择' htmlFor='modelSel' tip='注意,不同模型有不同价格与token限制'>
|
||||
<select id='modelSel' className="select select-sm select-bordered" value={modelValue}
|
||||
onChange={onChangeModelValue}>
|
||||
{MODELS.map(model => <option key={model.code} value={model.code}>{model.name}</option>)}
|
||||
</select>
|
||||
</FormItem>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <div className='desc text-sm'>
|
||||
{<div className='desc text-sm'>
|
||||
{MODEL_TIP}
|
||||
</div>}
|
||||
{modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'>
|
||||
@@ -291,20 +282,6 @@ const OptionsPage = () => {
|
||||
value={customModelTokensValue}
|
||||
onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/>
|
||||
</FormItem>}
|
||||
{aiTypeValue === '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>}
|
||||
{aiTypeValue === 'gemini' && <div>
|
||||
<div className='desc text-sm'>
|
||||
<div>官方网址:<a className='link link-primary' href='https://makersuite.google.com/app/apikey'
|
||||
target='_blank'
|
||||
rel="noreferrer">Google AI Studio</a> (目前免费)
|
||||
</div>
|
||||
<div className='text-sm text-error flex items-center'><IoWarning className='text-sm text-warning'/>谷歌模型安全要求比较高,有些视频可能无法生成总结!
|
||||
</div>
|
||||
</div>
|
||||
</div>}
|
||||
</OptionCard>
|
||||
|
||||
<OptionCard title={<div className='flex items-center'>
|
||||
@@ -372,7 +349,7 @@ const OptionsPage = () => {
|
||||
</div>
|
||||
</FormItem>
|
||||
<div className='desc text-sm'>
|
||||
当前选择的模型的分段字数上限是<span className='font-semibold font-mono'>{aiTypeValue === 'gemini'?GEMINI_TOKENS:(MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知')}</span>
|
||||
当前选择的模型的分段字数上限是<span className='font-semibold font-mono'>{MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知'}</span>
|
||||
(太接近上限总结会报错)
|
||||
</div>
|
||||
</OptionCard>
|
||||
|
23
src/redux/currentTimeReducer.ts
Normal file
23
src/redux/currentTimeReducer.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
|
||||
interface CurrentTimeState {
|
||||
currentTime?: number
|
||||
}
|
||||
|
||||
const initialState: CurrentTimeState = {
|
||||
currentTime: undefined
|
||||
}
|
||||
|
||||
export const slice = createSlice({
|
||||
name: 'currentTime',
|
||||
initialState,
|
||||
reducers: {
|
||||
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
|
||||
state.currentTime = action.payload
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const { setCurrentTime } = slice.actions
|
||||
|
||||
export default slice.reducer
|
@@ -23,7 +23,7 @@ interface EnvState {
|
||||
totalHeight: number
|
||||
curIdx?: number // 从0开始
|
||||
needScroll?: boolean
|
||||
currentTime?: number
|
||||
chapters?: Chapter[]
|
||||
infos?: any[]
|
||||
curInfo?: any
|
||||
curFetched?: boolean
|
||||
@@ -263,9 +263,6 @@ export const slice = createSlice({
|
||||
setNeedScroll: (state, action: PayloadAction<boolean>) => {
|
||||
state.needScroll = action.payload
|
||||
},
|
||||
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
|
||||
state.currentTime = action.payload
|
||||
},
|
||||
setUrl: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.url = action.payload
|
||||
},
|
||||
@@ -278,6 +275,9 @@ export const slice = createSlice({
|
||||
setAuthor: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.author = action.payload
|
||||
},
|
||||
setChapters: (state, action: PayloadAction<Chapter[]>) => {
|
||||
state.chapters = action.payload
|
||||
},
|
||||
setInfos: (state, action: PayloadAction<any[]>) => {
|
||||
state.infos = action.payload
|
||||
},
|
||||
@@ -337,7 +337,6 @@ export const {
|
||||
setCurIdx,
|
||||
setEnvData,
|
||||
setEnvReady,
|
||||
setCurrentTime,
|
||||
setInfos,
|
||||
setCurInfo,
|
||||
setCurFetched,
|
||||
@@ -351,6 +350,7 @@ export const {
|
||||
mergeAskInfo,
|
||||
setCtime,
|
||||
setAuthor,
|
||||
setChapters,
|
||||
} = slice.actions
|
||||
|
||||
export default slice.reducer
|
||||
|
@@ -1,9 +1,11 @@
|
||||
import {configureStore} from '@reduxjs/toolkit'
|
||||
import envReducer from './redux/envReducer'
|
||||
import currentTimeReducer from './redux/currentTimeReducer'
|
||||
|
||||
const store = configureStore({
|
||||
reducer: {
|
||||
env: envReducer,
|
||||
currentTime: currentTimeReducer,
|
||||
},
|
||||
})
|
||||
|
||||
|
15
src/typings.d.ts
vendored
15
src/typings.d.ts
vendored
@@ -11,15 +11,12 @@ interface EnvData {
|
||||
autoExpand?: boolean
|
||||
flagDot?: boolean
|
||||
|
||||
aiType?: 'openai' | 'gemini'
|
||||
// openai
|
||||
apiKey?: string
|
||||
serverUrl?: string
|
||||
model?: string
|
||||
customModel?: string
|
||||
customModelTokens?: number
|
||||
// gemini
|
||||
geminiApiKey?: string
|
||||
|
||||
translateEnable?: boolean
|
||||
language?: string
|
||||
@@ -33,6 +30,9 @@ interface EnvData {
|
||||
theme?: 'system' | 'light' | 'dark'
|
||||
fontSize?: 'normal' | 'large'
|
||||
|
||||
// chapter
|
||||
chapterMode?: boolean // 是否启用章节模式,undefined/null/true表示启用,false表示禁用
|
||||
|
||||
// search
|
||||
searchEnabled?: boolean
|
||||
cnSearchEnabled?: boolean
|
||||
@@ -54,7 +54,7 @@ interface TempData {
|
||||
}
|
||||
|
||||
interface TaskDef {
|
||||
type: 'chatComplete' | 'geminiChatComplete'
|
||||
type: 'chatComplete'
|
||||
serverUrl?: string
|
||||
data: any
|
||||
extra?: any
|
||||
@@ -91,12 +91,19 @@ interface TranscriptItem {
|
||||
idx: number
|
||||
}
|
||||
|
||||
interface Chapter {
|
||||
from: number
|
||||
to: number
|
||||
content: string // 标题
|
||||
}
|
||||
|
||||
interface Segment {
|
||||
items: TranscriptItem[]
|
||||
startIdx: number // 从1开始
|
||||
endIdx: number
|
||||
text: string
|
||||
fold?: boolean
|
||||
chapterTitle?: string // 章节标题
|
||||
summaries: {
|
||||
[type: string]: Summary
|
||||
}
|
||||
|
@@ -195,12 +195,56 @@ export const getSummarize = (title: string | undefined, segments: Segment[] | un
|
||||
}
|
||||
|
||||
/**
|
||||
* @param time '03:10'
|
||||
* 将 MM:SS 或 HH:MM:SS 格式的时间字符串转换为总秒数。
|
||||
* @param time '03:10' 或 '01:03:10' 格式的时间字符串
|
||||
* @returns number 总秒数,如果格式无效则返回 0 或 NaN (根据下面选择)。
|
||||
* 建议添加更严格的错误处理,例如抛出错误。
|
||||
*/
|
||||
export const parseStrTimeToSeconds = (time: string): number => {
|
||||
const parts = time.split(':')
|
||||
return parseInt(parts[0]) * 60 + parseInt(parts[1])
|
||||
}
|
||||
// 1. 基本输入验证 (可选但推荐)
|
||||
if (!time || typeof time !== 'string') {
|
||||
console.warn(`Invalid input type for time: ${typeof time}`);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
|
||||
const parts = time.split(':');
|
||||
const partCount = parts.length;
|
||||
|
||||
let hours = 0;
|
||||
let minutes = 0;
|
||||
let seconds = 0;
|
||||
|
||||
try {
|
||||
if (partCount === 2) {
|
||||
// 格式: MM:SS
|
||||
minutes = parseInt(parts[0]);
|
||||
seconds = parseInt(parts[1]);
|
||||
} else if (partCount === 3) {
|
||||
// 格式: HH:MM:SS
|
||||
hours = parseInt(parts[0]);
|
||||
minutes = parseInt(parts[1]);
|
||||
seconds = parseInt(parts[2]);
|
||||
} else {
|
||||
// 格式无效
|
||||
console.warn(`Invalid time format: "${time}". Expected MM:SS or HH:MM:SS.`);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
|
||||
// 2. 验证解析出的部分是否为有效数字
|
||||
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
|
||||
console.warn(`Invalid numeric values in time string: "${time}"`);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
|
||||
// 3. 计算总秒数
|
||||
return hours * 3600 + minutes * 60 + seconds;
|
||||
|
||||
} catch (error) {
|
||||
// 捕获潜在的错误 (虽然在此逻辑中不太可能,但以防万一)
|
||||
console.error(`Error parsing time string: "${time}"`, error);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param time '00:04:11,599' or '00:04:11.599' or '04:11,599' or '04:11.599'
|
||||
|
@@ -5,13 +5,40 @@ export const isEdgeBrowser = () => {
|
||||
return userAgent.includes('edg/') && !userAgent.includes('edge/')
|
||||
}
|
||||
|
||||
export const formatTime = (time: number) => {
|
||||
if (!time) return '00:00'
|
||||
/**
|
||||
* 将总秒数格式化为 MM:SS 或 HH:MM:SS 格式的字符串。
|
||||
* 如果时间小于 1 小时,则使用 MM:SS 格式。
|
||||
* 如果时间大于或等于 1 小时,则使用 HH:MM:SS 格式。
|
||||
*
|
||||
* @param time 总秒数 (number)
|
||||
* @returns string 格式化后的时间字符串 ('MM:SS' 或 'HH:MM:SS')
|
||||
*/
|
||||
export const formatTime = (time: number): string => {
|
||||
// 1. 输入验证和处理 0 或负数的情况
|
||||
if (typeof time !== 'number' || isNaN(time) || time <= 0) {
|
||||
return '00:00'; // 对于无效输入、0 或负数,返回 '00:00'
|
||||
}
|
||||
|
||||
const minutes = Math.floor(time / 60)
|
||||
const seconds = Math.floor(time % 60)
|
||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
|
||||
}
|
||||
// 取整确保我们处理的是整数秒
|
||||
const totalSeconds = Math.floor(time);
|
||||
|
||||
// 2. 计算小时、分钟和秒
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
// 3. 格式化各个部分,确保是两位数 (例如 0 -> '00', 5 -> '05', 10 -> '10')
|
||||
const formattedSeconds = seconds.toString().padStart(2, '0');
|
||||
const formattedMinutes = minutes.toString().padStart(2, '0');
|
||||
|
||||
// 4. 根据是否有小时来决定最终格式
|
||||
if (hours > 0) {
|
||||
const formattedHours = hours.toString().padStart(2, '0');
|
||||
return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
|
||||
} else {
|
||||
return `${formattedMinutes}:${formattedSeconds}`;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param time 2.82
|
||||
|
@@ -3,7 +3,11 @@ module.exports = {
|
||||
darkMode: 'class',
|
||||
content: ["./src/**/*.{js,ts,jsx,tsx}"],
|
||||
theme: {
|
||||
extend: {},
|
||||
extend: {
|
||||
fontSize: {
|
||||
xs: '13px',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
require('tailwind-scrollbar-hide'),
|
||||
|
Reference in New Issue
Block a user