From 2cd633cbd43365befe046d3db9ada82c13cdd788 Mon Sep 17 00:00:00 2001 From: IndieKKY Date: Mon, 5 May 2025 23:13:07 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=B1=E4=BA=8Egemini=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E4=BA=86openai=E6=A0=BC=E5=BC=8F=EF=BC=8C=E5=9B=A0=E6=AD=A4?= =?UTF-8?q?=E5=8E=BB=E9=99=A4=E4=BA=86=E4=B8=93=E9=97=A8=E7=9A=84gemini?= =?UTF-8?q?=E9=80=89=E9=A1=B9=EF=BC=8C=E7=AE=80=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/chrome/openaiService.ts | 13 ------- src/chrome/taskService.ts | 5 +-- src/components/ApiKeyReminder.tsx | 4 +- src/components/Ask.tsx | 4 +- src/components/Body.tsx | 12 +++--- src/components/SegmentCard.tsx | 4 +- src/consts/const.ts | 1 - src/hooks/useSubtitleService.ts | 8 +--- src/hooks/useTranslate.ts | 64 ++++--------------------------- src/pages/OptionsPage.tsx | 52 ++++--------------------- src/typings.d.ts | 5 +-- 11 files changed, 31 insertions(+), 141 deletions(-) diff --git a/src/chrome/openaiService.ts b/src/chrome/openaiService.ts index ee86bd7..20105bb 100644 --- a/src/chrome/openaiService.ts +++ b/src/chrome/openaiService.ts @@ -36,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() -} diff --git a/src/chrome/taskService.ts b/src/chrome/taskService.ts index 5c040ba..098a4c6 100644 --- a/src/chrome/taskService.ts +++ b/src/chrome/taskService.ts @@ -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() @@ -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}`) diff --git a/src/components/ApiKeyReminder.tsx b/src/components/ApiKeyReminder.tsx index 9dc8b97..288be40 100644 --- a/src/components/ApiKeyReminder.tsx +++ b/src/components/ApiKeyReminder.tsx @@ -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 } diff --git a/src/components/Ask.tsx b/src/components/Ask.tsx index 425d8e8..1268225 100644 --- a/src/components/Ask.tsx +++ b/src/components/Ask.tsx @@ -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({ diff --git a/src/components/Body.tsx b/src/components/Body.tsx index b87aca9..77eec27 100644 --- a/src/components/Body.tsx +++ b/src/components/Body.tsx @@ -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() diff --git a/src/components/SegmentCard.tsx b/src/components/SegmentCard.tsx index ff2787a..779447d 100644 --- a/src/components/SegmentCard.tsx +++ b/src/components/SegmentCard.tsx @@ -73,13 +73,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) { diff --git a/src/consts/const.ts b/src/consts/const.ts index 68b098c..1a37448 100644 --- a/src/consts/const.ts +++ b/src/consts/const.ts @@ -284,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) { diff --git a/src/hooks/useSubtitleService.ts b/src/hooks/useSubtitleService.ts index 46ba9cf..6cbfacf 100644 --- a/src/hooks/useSubtitleService.ts +++ b/src/hooks/useSubtitleService.ts @@ -16,7 +16,7 @@ import { 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' @@ -152,11 +152,7 @@ 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) diff --git a/src/hooks/useTranslate.ts b/src/hooks/useTranslate.ts index f4f04d3..7f98adb 100644 --- a/src/hooks/useTranslate.ts +++ b/src/hooks/useTranslate.ts @@ -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} } diff --git a/src/pages/OptionsPage.tsx b/src/pages/OptionsPage.tsx index a2613aa..a99e2f0 100644 --- a/src/pages/OptionsPage.tsx +++ b/src/pages/OptionsPage.tsx @@ -6,7 +6,6 @@ import { CUSTOM_MODEL_TOKENS, DEFAULT_SERVER_URL_GEMINI, DEFAULT_SERVER_URL_OPENAI, - GEMINI_TOKENS, LANGUAGE_DEFAULT, LANGUAGES, MODEL_DEFAULT, @@ -80,7 +79,6 @@ const OptionsPage = () => { const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat) 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}) @@ -89,7 +87,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(envData.words) const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT) @@ -110,11 +107,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) @@ -125,13 +119,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, @@ -154,7 +146,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]) const onCancel = useCallback(() => { window.close() @@ -200,14 +192,6 @@ const OptionsPage = () => { setFontSizeValue('large') }, []) - const onSelOpenai = useCallback(() => { - setAiTypeValue('openai') - }, []) - - const onSelGemini = useCallback(() => { - setAiTypeValue('gemini') - }, []) - return (
@@ -236,25 +220,19 @@ const OptionsPage = () => {
- -
- - -
-
- {(!aiTypeValue || aiTypeValue === 'openai') && + { } - {(!aiTypeValue || aiTypeValue === 'openai') && + { setServerUrlValue(e.target.value)}/> } - {(!aiTypeValue || aiTypeValue === 'openai') &&
+ {
【OpenAI官方地址】
} - {(!aiTypeValue || aiTypeValue === 'openai') && + { } - {(!aiTypeValue || aiTypeValue === 'openai') &&
- 当前选择的模型的分段字数上限是{aiTypeValue === 'gemini'?GEMINI_TOKENS:(MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知')} + 当前选择的模型的分段字数上限是{MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知'} (太接近上限总结会报错)
diff --git a/src/typings.d.ts b/src/typings.d.ts index 2c89c3e..000288a 100644 --- a/src/typings.d.ts +++ b/src/typings.d.ts @@ -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 @@ -54,7 +51,7 @@ interface TempData { } interface TaskDef { - type: 'chatComplete' | 'geminiChatComplete' + type: 'chatComplete' serverUrl?: string data: any extra?: any