14 Commits

Author SHA1 Message Date
IndieKKY
e4693cde6a chore: release 1.13.1 2025-06-02 09:31:24 +08:00
IndieKKY
fea22fae61 优化性能 2025-06-02 09:26:38 +08:00
IndieKKY
d5b5b5d374 优化性能 2025-06-02 09:18:02 +08:00
IndieKKY
17d4e60de0 chore: release 1.13.0 2025-05-05 23:14:46 +08:00
IndieKKY
2cd633cbd4 由于gemini兼容了openai格式,因此去除了专门的gemini选项,简化代码 2025-05-05 23:13:07 +08:00
IndieKKY
3ad198948f gemini优化 2025-05-05 22:43:00 +08:00
IndieKKY
774cc2726d Merge branch 'refs/heads/vector090/master' 2025-05-05 22:30:00 +08:00
IndieKKY
4765244638 Merge pull request #77 from 2-3-5-7/feature/time-format-enhancement
feat(时间): 支持 HH:MM:SS 格式的解析与格式化
2025-05-05 17:00:03 +08:00
2-3-5-7
b0107c4959 feat(时间): 支持 HH:MM:SS 格式的解析与格式化
改进 parseStrTimeToSeconds 以处理 MM:SS 和 HH:MM:SS 输入。更新 formatTime 以在存在小时的情况下输出 HH:MM:SS 格式。
2025-05-04 16:28:07 +08:00
user
e900b11f05 fix building under linux 2025-04-30 05:04:13 +00:00
IndieKKY
194df8525c chore: release 1.12.1 2025-03-06 18:57:13 +08:00
IndieKKY
28bb3dbb96 优化字体大小 2025-03-06 18:56:55 +08:00
IndieKKY
640f6d89fd fix serverUrl bug 2025-03-06 18:56:47 +08:00
IndieKKY
338e3145f2 update package version 2025-02-24 15:06:50 +08:00
20 changed files with 186 additions and 180 deletions

View File

@@ -1,7 +1,7 @@
{ {
"private": true, "private": true,
"name": "bilibili-subtitle", "name": "bilibili-subtitle",
"version": "1.12.0", "version": "1.13.1",
"type": "module", "type": "module",
"description": "哔哩哔哩字幕列表", "description": "哔哩哔哩字幕列表",
"main": "index.js", "main": "index.js",
@@ -15,7 +15,7 @@
"dependencies": { "dependencies": {
"@crxjs/vite-plugin": "^1.0.14", "@crxjs/vite-plugin": "^1.0.14",
"@kky002/kky-hooks": "^1.2.1", "@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-ui": "^1.0.9",
"@kky002/kky-util": "^1.13.13", "@kky002/kky-util": "^1.13.13",
"@logto/react": "1.0.0-beta.13", "@logto/react": "1.0.0-beta.13",

10
pnpm-lock.yaml generated
View File

@@ -15,8 +15,8 @@ importers:
specifier: ^1.2.1 specifier: ^1.2.1
version: 1.2.1 version: 1.2.1
'@kky002/kky-message': '@kky002/kky-message':
specifier: ^0.2.0 specifier: ^0.2.1
version: 0.2.0 version: 0.2.1
'@kky002/kky-ui': '@kky002/kky-ui':
specifier: ^1.0.9 specifier: ^1.0.9
version: 1.0.9 version: 1.0.9
@@ -397,8 +397,8 @@ packages:
'@kky002/kky-hooks@1.2.1': '@kky002/kky-hooks@1.2.1':
resolution: {integrity: sha512-AJM2gm75TtkZqOPd/WX0+4h/dfjSb8HlDQLwAJsYIHRNw8MQUKu32Ih6OxhKL2l9pdPsuj+S9/lBc4Cwu4tP+Q==} resolution: {integrity: sha512-AJM2gm75TtkZqOPd/WX0+4h/dfjSb8HlDQLwAJsYIHRNw8MQUKu32Ih6OxhKL2l9pdPsuj+S9/lBc4Cwu4tP+Q==}
'@kky002/kky-message@0.2.0': '@kky002/kky-message@0.2.1':
resolution: {integrity: sha512-bquH4+79xHYLgVGxfDHAHQgmkbJ8Wbx6U3vBR6fA6piheMATwVPW7c2scS0BMbB9F4w23I4fZj30nRWgZrcEig==} resolution: {integrity: sha512-LIg4T89t3TmjflepZeOPH/OMN3xxwLE0AxnfDycTlCpjHAiuvm/Aj3IIHLfzqbz5azRaGNu2ZcUsrUdb2jAtiQ==}
'@kky002/kky-ui@1.0.9': '@kky002/kky-ui@1.0.9':
resolution: {integrity: sha512-pepfRcLfC1eIQ1lsSJLWNr4PgdLqFLuvQMlitJy7W668yZ7qu8yAHSjg8A20R7HB4mFkJ+B96WETalOar1e/kA==} resolution: {integrity: sha512-pepfRcLfC1eIQ1lsSJLWNr4PgdLqFLuvQMlitJy7W668yZ7qu8yAHSjg8A20R7HB4mFkJ+B96WETalOar1e/kA==}
@@ -2846,7 +2846,7 @@ snapshots:
lodash-es: 4.17.21 lodash-es: 4.17.21
react: 18.2.0 react: 18.2.0
'@kky002/kky-message@0.2.0': '@kky002/kky-message@0.2.1':
dependencies: dependencies:
'@kky002/kky-util': 1.13.13 '@kky002/kky-util': 1.13.13
ahooks: 3.8.4(react@18.2.0) ahooks: 3.8.4(react@18.2.0)

View File

@@ -7,13 +7,21 @@ const getServerUrl = (serverUrl?: string) => {
if (serverUrl.endsWith('/')) { if (serverUrl.endsWith('/')) {
serverUrl = serverUrl.slice(0, -1) 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 return serverUrl
} }
export const handleChatCompleteTask = async (task: Task) => { export const handleChatCompleteTask = async (task: Task) => {
const data = task.def.data const data = task.def.data
const serverUrl = getServerUrl(task.def.serverUrl) const serverUrl = getServerUrl(task.def.serverUrl)
const resp = await fetch(`${serverUrl}/v1/chat/completions`, { const resp = await fetch(`${serverUrl}/chat/completions`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', '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 ??''}`) 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 '../consts/const' import {TASK_EXPIRE_TIME} from '../consts/const'
import {handleChatCompleteTask, handleGeminiChatCompleteTask} from './openaiService' import {handleChatCompleteTask} from './openaiService'
export const tasksMap = new Map<string, Task>() export const tasksMap = new Map<string, Task>()
@@ -11,9 +11,6 @@ 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

@@ -4,10 +4,8 @@ import { openOptionsPage } from '../utils/chromeUtils'
const ApiKeyReminder: React.FC = () => { const ApiKeyReminder: React.FC = () => {
const apiKey = useAppSelector(state => state.env.envData.apiKey) 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 return null
} }

View File

@@ -18,7 +18,7 @@ const Ask = (props: {
const {addAskTask} = useTranslate() const {addAskTask} = useTranslate()
const onRegenerate = useCallback(() => { const onRegenerate = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
if (segments != null && segments.length > 0) { if (segments != null && segments.length > 0) {
addAskTask(ask.id, segments[0], ask.question).catch(console.error) addAskTask(ask.id, segments[0], ask.question).catch(console.error)
@@ -26,7 +26,7 @@ const Ask = (props: {
} else { } else {
toast.error('请先在选项页面设置ApiKey!') 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(() => { const onAskFold = useCallback(() => {
dispatch(mergeAskInfo({ dispatch(mergeAskInfo({

View File

@@ -105,7 +105,7 @@ const Body = () => {
}, [dispatch]) }, [dispatch])
const onSummarizeAll = useCallback(() => { const onSummarizeAll = useCallback(() => {
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey const apiKey = envData.apiKey
if (!apiKey) { if (!apiKey) {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
return return
@@ -127,7 +127,7 @@ const Body = () => {
} }
toast.success(`已添加${segments_.length}个总结任务!`) toast.success(`已添加${segments_.length}个总结任务!`)
} }
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segments]) }, [addSummarizeTask, curSummaryType, envData.apiKey, segments])
const onFoldAll = useCallback(() => { const onFoldAll = useCallback(() => {
dispatch(setFoldAll(!foldAll)) dispatch(setFoldAll(!foldAll))
@@ -146,13 +146,13 @@ const Body = () => {
}, [asks, dispatch, foldAll, segments]) }, [asks, dispatch, foldAll, segments])
const toggleAutoTranslateCallback = useCallback(() => { const toggleAutoTranslateCallback = useCallback(() => {
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
dispatch(setAutoTranslate(!autoTranslate)) dispatch(setAutoTranslate(!autoTranslate))
} else { } else {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
} }
}, [autoTranslate, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey]) }, [autoTranslate, dispatch, envData.apiKey])
const onEnableAutoScroll = useCallback(() => { const onEnableAutoScroll = useCallback(() => {
dispatch(setAutoScroll(true)) dispatch(setAutoScroll(true))
@@ -185,7 +185,7 @@ const Body = () => {
const onAsk = useCallback(() => { const onAsk = useCallback(() => {
if ((envData.askEnabled ?? ASK_ENABLED_DEFAULT) && searchText) { if ((envData.askEnabled ?? ASK_ENABLED_DEFAULT) && searchText) {
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
if (segments != null && segments.length > 0) { if (segments != null && segments.length > 0) {
const id = v4() const id = v4()
@@ -201,7 +201,7 @@ const Body = () => {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
} }
} }
}, [addAskTask, dispatch, envData.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, searchText, segments]) }, [addAskTask, dispatch, envData.apiKey, envData.askEnabled, searchText, segments])
// service // service
useKeyService() useKeyService()

View File

@@ -13,6 +13,7 @@ import SegmentItem from './SegmentItem'
import {stopPopFunc} from '../utils/util' import {stopPopFunc} from '../utils/util'
import useSubtitle from '../hooks/useSubtitle' import useSubtitle from '../hooks/useSubtitle'
import DebateChat from './DebateChat' import DebateChat from './DebateChat'
import { RootState } from '../store'
const SummarizeItemOverview = (props: { const SummarizeItemOverview = (props: {
segment: Segment segment: Segment
@@ -25,7 +26,7 @@ const SummarizeItemOverview = (props: {
const {move} = useSubtitle() const {move} = useSubtitle()
const time = parseStrTimeToSeconds(overviewItem.time) const time = parseStrTimeToSeconds(overviewItem.time)
const currentTime = useAppSelector(state => state.env.currentTime) const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
const isIn = useMemo(() => { const isIn = useMemo(() => {
if (currentTime != null) { if (currentTime != null) {
// check in current segment // check in current segment
@@ -73,13 +74,13 @@ const Summarize = (props: {
const {addSummarizeTask} = useTranslate() const {addSummarizeTask} = useTranslate()
const onGenerate = useCallback(() => { const onGenerate = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
addSummarizeTask(curSummaryType, segment).catch(console.error) addSummarizeTask(curSummaryType, segment).catch(console.error)
} else { } else {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
} }
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segment]) }, [addSummarizeTask, curSummaryType, envData.apiKey, segment])
const onCopy = useCallback(() => { const onCopy = useCallback(() => {
if (summary != null) { if (summary != null) {

View File

@@ -268,6 +268,7 @@ export const SUMMARIZE_LANGUAGE_DEFAULT = 'cn'
export const SUMMARIZE_ALL_THRESHOLD = 5 export const SUMMARIZE_ALL_THRESHOLD = 5
export const ASK_ENABLED_DEFAULT = true export const ASK_ENABLED_DEFAULT = true
export const DEFAULT_SERVER_URL_OPENAI = 'https://api.openai.com' 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 CUSTOM_MODEL_TOKENS = 16385
export const MODEL_TIP = '推荐gpt-4o-mini能力强价格低token上限大' export const MODEL_TIP = '推荐gpt-4o-mini能力强价格低token上限大'
@@ -283,7 +284,6 @@ export const MODELS = [{
code: 'custom', code: 'custom',
name: '自定义', name: '自定义',
}] }]
export const GEMINI_TOKENS = 32768
export const MODEL_DEFAULT = MODELS[0].code export const MODEL_DEFAULT = MODELS[0].code
export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {} export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {}
for (const model of MODELS) { for (const model of MODELS) {

View File

@@ -4,22 +4,20 @@ import {
setCurFetched, setCurFetched,
setCurIdx, setCurIdx,
setCurInfo, setCurInfo,
setCurrentTime,
setData, setData,
setInfos,
setNoVideo, setNoVideo,
setSegmentFold, setSegmentFold,
setSegments, setSegments,
setTitle,
setTotalHeight, setTotalHeight,
setUrl,
setTempData, setTempData,
} from '../redux/envReducer' } from '../redux/envReducer'
import {EventBusContext} from '../Router' 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 {useAsyncEffect, useInterval} from 'ahooks'
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil' import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
import { useMessage } from './useMessageService' import { useMessage } from './useMessageService'
import { setCurrentTime } from '../redux/currentTimeReducer'
import { RootState } from '../store'
/** /**
* Service是单例类似后端的服务概念 * Service是单例类似后端的服务概念
@@ -31,10 +29,10 @@ const useSubtitleService = () => {
const curFetched = useAppSelector(state => state.env.curFetched) const curFetched = useAppSelector(state => state.env.curFetched)
const fold = useAppSelector(state => state.env.fold) const fold = useAppSelector(state => state.env.fold)
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: RootState) => state.env.envData)
const data = useAppSelector(state => state.env.data) const data = useAppSelector((state: RootState) => state.env.data)
const currentTime = useAppSelector(state => state.env.currentTime) const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
const curIdx = useAppSelector(state => state.env.curIdx) const curIdx = useAppSelector((state: RootState) => state.env.curIdx)
const eventBus = useContext(EventBusContext) const eventBus = useContext(EventBusContext)
const needScroll = useAppSelector(state => state.env.needScroll) const needScroll = useAppSelector(state => state.env.needScroll)
const segments = useAppSelector(state => state.env.segments) const segments = useAppSelector(state => state.env.segments)
@@ -113,19 +111,22 @@ const useSubtitleService = () => {
// 更新当前位置 // 更新当前位置
useEffect(() => { useEffect(() => {
let curIdx let newCurIdx
if (((data?.body) != null) && currentTime) { if (((data?.body) != null) && currentTime) {
for (let i=0; i<data.body.length; i++) { for (let i=0; i<data.body.length; i++) {
const item = data.body[i] const item = data.body[i]
if (item.from && currentTime < item.from) { if (item.from && currentTime < item.from) {
break break
} else { } else {
curIdx = i newCurIdx = i
} }
} }
} }
dispatch(setCurIdx(curIdx)) // 只有当索引发生变化时才更新状态
}, [currentTime, data?.body, dispatch]) if (newCurIdx !== curIdx) {
dispatch(setCurIdx(newCurIdx))
}
}, [currentTime, data?.body, dispatch, curIdx])
// 需要滚动 => segment自动展开 // 需要滚动 => segment自动展开
useEffect(() => { useEffect(() => {
@@ -152,11 +153,7 @@ const useSubtitleService = () => {
if (envData.summarizeEnable) { // 分段 if (envData.summarizeEnable) { // 分段
let size = envData.words let size = envData.words
if (!size) { // 默认 if (!size) { // 默认
if (envData.aiType === 'gemini') { size = getModelMaxTokens(envData)*WORDS_RATE
size = GEMINI_TOKENS*WORDS_RATE
} else {
size = getModelMaxTokens(envData)*WORDS_RATE
}
} }
size = Math.max(size, WORDS_MIN) size = Math.max(size, WORDS_MIN)
@@ -197,7 +194,10 @@ const useSubtitleService = () => {
// 每0.5秒更新当前视频时间 // 每0.5秒更新当前视频时间
useInterval(() => { useInterval(() => {
sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => { 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) }, 500)

View File

@@ -88,24 +88,9 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{subtitles}}', lineStr) prompt = prompt.replaceAll('{{subtitles}}', lineStr)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete', type: 'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: envData.aiType === 'gemini' data: {
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
:{
model: getModel(envData), model: getModel(envData),
messages: [ messages: [
{ {
@@ -120,7 +105,6 @@ const useTranslate = () => {
extra: { extra: {
type: 'translate', type: 'translate',
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
startIdx, startIdx,
size: lines.length, size: lines.length,
} }
@@ -165,24 +149,9 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{segment}}', segment.text) prompt = prompt.replaceAll('{{segment}}', segment.text)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete', type: 'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: envData.aiType === 'gemini' data: {
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
:{
model: getModel(envData), model: getModel(envData),
messages: [ messages: [
{ {
@@ -199,7 +168,6 @@ const useTranslate = () => {
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)
@@ -220,24 +188,9 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{question}}', question) prompt = prompt.replaceAll('{{question}}', question)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete', type: 'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: envData.aiType === 'gemini' data: {
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
:{
model: getModel(envData), model: getModel(envData),
messages: [ messages: [
{ {
@@ -253,7 +206,6 @@ const useTranslate = () => {
type: 'ask', type: 'ask',
// startIdx: segment.startIdx, // startIdx: segment.startIdx,
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
askId: id, askId: id,
} }
} }
@@ -335,7 +287,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 = 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.status === 'done') {
// 异常提示 // 异常提示
if (task.error) { if (task.error) {
@@ -355,7 +307,7 @@ const useTranslate = () => {
} else { } else {
dispatch(delTaskId(taskId)) dispatch(delTaskId(taskId))
} }
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate, sendExtension]) }, [dispatch, handleAsk, handleSummarize, handleTranslate, sendExtension])
return {getFetch, getTask, addTask, addSummarizeTask, addAskTask} return {getFetch, getTask, addTask, addSummarizeTask, addAskTask}
} }

View File

@@ -4,8 +4,8 @@ import {useAppDispatch, useAppSelector} from '../hooks/redux'
import { import {
ASK_ENABLED_DEFAULT, ASK_ENABLED_DEFAULT,
CUSTOM_MODEL_TOKENS, CUSTOM_MODEL_TOKENS,
DEFAULT_SERVER_URL_GEMINI,
DEFAULT_SERVER_URL_OPENAI, DEFAULT_SERVER_URL_OPENAI,
GEMINI_TOKENS,
LANGUAGE_DEFAULT, LANGUAGE_DEFAULT,
LANGUAGES, LANGUAGES,
MODEL_DEFAULT, MODEL_DEFAULT,
@@ -79,7 +79,6 @@ const OptionsPage = () => {
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 [customModelValue, { onChange: onChangeCustomModelValue }] = useEventTarget({initialValue: envData.customModel}) const [customModelValue, { onChange: onChangeCustomModelValue }] = useEventTarget({initialValue: envData.customModel})
@@ -88,7 +87,6 @@ const OptionsPage = () => {
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) const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words)
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT) const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
@@ -109,11 +107,8 @@ const OptionsPage = () => {
return list return list
}, []) }, [])
const apiKeySetted = useMemo(() => { const apiKeySetted = useMemo(() => {
if (aiTypeValue === 'gemini') {
return !!geminiApiKeyValue
}
return !!apiKeyValue return !!apiKeyValue
}, [aiTypeValue, apiKeyValue, geminiApiKeyValue]) }, [apiKeyValue])
const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => { const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => {
setHideOnDisableAutoTranslateValue(e.target.checked) setHideOnDisableAutoTranslateValue(e.target.checked)
@@ -124,13 +119,11 @@ const OptionsPage = () => {
sidePanel: sidePanelValue, sidePanel: sidePanelValue,
manualInsert: !autoInsertValue, manualInsert: !autoInsertValue,
autoExpand: autoExpandValue, autoExpand: autoExpandValue,
aiType: aiTypeValue,
apiKey: apiKeyValue, apiKey: apiKeyValue,
serverUrl: serverUrlValue, serverUrl: serverUrlValue,
model: modelValue, model: modelValue,
customModel: customModelValue, customModel: customModelValue,
customModelTokens: customModelTokensValue, customModelTokens: customModelTokensValue,
geminiApiKey: geminiApiKeyValue,
translateEnable: translateEnableValue, translateEnable: translateEnableValue,
language: languageValue, language: languageValue,
hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue, hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue,
@@ -153,7 +146,7 @@ const OptionsPage = () => {
setTimeout(() => { setTimeout(() => {
window.close() window.close()
}, 3000) }, 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])
const onCancel = useCallback(() => { const onCancel = useCallback(() => {
window.close() window.close()
@@ -199,14 +192,6 @@ const OptionsPage = () => {
setFontSizeValue('large') setFontSizeValue('large')
}, []) }, [])
const onSelOpenai = useCallback(() => {
setAiTypeValue('openai')
}, [])
const onSelGemini = useCallback(() => {
setAiTypeValue('gemini')
}, [])
return ( return (
<div className='container mx-auto max-w-3xl p-4'> <div className='container mx-auto max-w-3xl p-4'>
<OptionCard title="通用配置"> <OptionCard title="通用配置">
@@ -235,32 +220,32 @@ const OptionsPage = () => {
<button onClick={onSelFontSize2} className={classNames('btn btn-sm no-animation', fontSizeValue === 'large'?'btn-active':'')}></button> <button onClick={onSelFontSize2} className={classNames('btn btn-sm no-animation', fontSizeValue === 'large'?'btn-active':'')}></button>
</div> </div>
</FormItem> </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>
<OptionCard title="AI 配置"> <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' <input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx'
value={apiKeyValue} onChange={onChangeApiKeyValue}/> value={apiKeyValue} onChange={onChangeApiKeyValue}/>
</FormItem>} </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' <input id='serverUrl' type='text' className='input input-sm input-bordered w-full'
placeholder={DEFAULT_SERVER_URL_OPENAI} value={serverUrlValue} placeholder={DEFAULT_SERVER_URL_OPENAI} value={serverUrlValue}
onChange={e => setServerUrlValue(e.target.value)}/> onChange={e => setServerUrlValue(e.target.value)}/>
</FormItem>} </FormItem>}
{(!aiTypeValue || aiTypeValue === 'openai') && <div> {<div>
<div className='desc text-sm text-center'> <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' <div><a className='link link-primary' href='https://platform.openai.com/' target='_blank'
rel="noreferrer">访</a></div> rel="noreferrer">访</a></div>
<div><a className='link link-primary' <div><a className='link link-primary'
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_OPENAI)} onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_OPENAI)}
rel='noreferrer'></a></div> 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 className='flex justify-center font-semibold'></div>
<div><a className='link link-primary' href='https://api.kksj.org/register?aff=ucVc' <div><a className='link link-primary' href='https://api.kksj.org/register?aff=ucVc'
target='_blank' target='_blank'
@@ -272,13 +257,13 @@ const OptionsPage = () => {
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>访🪜<FaGripfire/></div> <div className='text-amber-600 flex justify-center items-center'><FaGripfire/>访🪜<FaGripfire/></div>
</div> </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} <select id='modelSel' className="select select-sm select-bordered" value={modelValue}
onChange={onChangeModelValue}> onChange={onChangeModelValue}>
{MODELS.map(model => <option key={model.code} value={model.code}>{model.name}</option>)} {MODELS.map(model => <option key={model.code} value={model.code}>{model.name}</option>)}
</select> </select>
</FormItem>} </FormItem>}
{(!aiTypeValue || aiTypeValue === 'openai') && <div className='desc text-sm'> {<div className='desc text-sm'>
{MODEL_TIP} {MODEL_TIP}
</div>} </div>}
{modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'> {modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'>
@@ -291,20 +276,6 @@ const OptionsPage = () => {
value={customModelTokensValue} value={customModelTokensValue}
onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/> onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/>
</FormItem>} </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>
<OptionCard title={<div className='flex items-center'> <OptionCard title={<div className='flex items-center'>
@@ -372,7 +343,7 @@ const OptionsPage = () => {
</div> </div>
</FormItem> </FormItem>
<div className='desc text-sm'> <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> </div>
</OptionCard> </OptionCard>

View 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

View File

@@ -23,7 +23,6 @@ interface EnvState {
totalHeight: number totalHeight: number
curIdx?: number // 从0开始 curIdx?: number // 从0开始
needScroll?: boolean needScroll?: boolean
currentTime?: number
infos?: any[] infos?: any[]
curInfo?: any curInfo?: any
curFetched?: boolean curFetched?: boolean
@@ -263,9 +262,6 @@ export const slice = createSlice({
setNeedScroll: (state, action: PayloadAction<boolean>) => { setNeedScroll: (state, action: PayloadAction<boolean>) => {
state.needScroll = action.payload state.needScroll = action.payload
}, },
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
state.currentTime = action.payload
},
setUrl: (state, action: PayloadAction<string | undefined>) => { setUrl: (state, action: PayloadAction<string | undefined>) => {
state.url = action.payload state.url = action.payload
}, },
@@ -337,7 +333,6 @@ export const {
setCurIdx, setCurIdx,
setEnvData, setEnvData,
setEnvReady, setEnvReady,
setCurrentTime,
setInfos, setInfos,
setCurInfo, setCurInfo,
setCurFetched, setCurFetched,

View File

@@ -1,9 +1,11 @@
import {configureStore} from '@reduxjs/toolkit' import {configureStore} from '@reduxjs/toolkit'
import envReducer from './redux/envReducer' import envReducer from './redux/envReducer'
import currentTimeReducer from './redux/currentTimeReducer'
const store = configureStore({ const store = configureStore({
reducer: { reducer: {
env: envReducer, env: envReducer,
currentTime: currentTimeReducer,
}, },
}) })

5
src/typings.d.ts vendored
View File

@@ -11,15 +11,12 @@ interface EnvData {
autoExpand?: boolean autoExpand?: boolean
flagDot?: boolean flagDot?: boolean
aiType?: 'openai' | 'gemini'
// openai // openai
apiKey?: string apiKey?: string
serverUrl?: string serverUrl?: string
model?: string model?: string
customModel?: string customModel?: string
customModelTokens?: number customModelTokens?: number
// gemini
geminiApiKey?: string
translateEnable?: boolean translateEnable?: boolean
language?: string language?: string
@@ -54,7 +51,7 @@ interface TempData {
} }
interface TaskDef { interface TaskDef {
type: 'chatComplete' | 'geminiChatComplete' type: 'chatComplete'
serverUrl?: string serverUrl?: string
data: any data: any
extra?: any extra?: any

View File

@@ -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 => { export const parseStrTimeToSeconds = (time: string): number => {
const parts = time.split(':') // 1. 基本输入验证 (可选但推荐)
return parseInt(parts[0]) * 60 + parseInt(parts[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' * @param time '00:04:11,599' or '00:04:11.599' or '04:11,599' or '04:11.599'

View File

@@ -5,13 +5,40 @@ export const isEdgeBrowser = () => {
return userAgent.includes('edg/') && !userAgent.includes('edge/') 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) const totalSeconds = Math.floor(time);
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
} // 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 * @param time 2.82

View File

@@ -3,7 +3,11 @@ module.exports = {
darkMode: 'class', darkMode: 'class',
content: ["./src/**/*.{js,ts,jsx,tsx}"], content: ["./src/**/*.{js,ts,jsx,tsx}"],
theme: { theme: {
extend: {}, extend: {
fontSize: {
xs: '13px',
},
},
}, },
plugins: [ plugins: [
require('tailwind-scrollbar-hide'), require('tailwind-scrollbar-hide'),