13 Commits
1.8.3 ... 1.9.2

Author SHA1 Message Date
IndieKKY
71ac909855 chore: release 1.9.2 2024-04-12 10:27:17 +08:00
IndieKKY
60697769bb ollama支持 2024-04-12 10:25:26 +08:00
IndieKKY
c40338a5f5 chore: release 1.9.1 2024-03-19 22:23:55 +08:00
IndieKKY
13e90c1ab7 上下键移动 2024-03-19 22:22:39 +08:00
IndieKKY
9b2d620cdf Revert "去除是否自动展开配置"
This reverts commit e6db6747
2024-03-19 21:39:16 +08:00
IndieKKY
2383603b39 chore: release 1.9.0 2024-03-18 21:57:26 +08:00
IndieKKY
1d2b708682 推荐优化 2024-03-18 21:57:10 +08:00
IndieKKY
2ba841c8f2 优化字幕复制 2024-03-18 19:28:10 +08:00
IndieKKY
e6db674755 去除是否自动展开配置 2024-03-18 19:14:24 +08:00
IndieKKY
72c8f9608e 优化推荐 2024-03-18 18:59:13 +08:00
IndieKKY
7a03d37c61 新增字幕提问功能 2024-03-18 11:36:30 +08:00
IndieKKY
a86ba9e09f 新增字幕提问功能 2024-03-17 23:31:48 +08:00
IndieKKY
d6d7e17f84 新增字幕提问功能 2024-03-17 21:17:40 +08:00
23 changed files with 679 additions and 194 deletions

View File

@@ -1,11 +1,15 @@
{
"name": "哔哩哔哩字幕列表",
"description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!",
"version": "1.8.3",
"version": "1.9.2",
"manifest_version": 3,
"permissions": [
"storage"
],
"host_permissions": [
"http://localhost/*",
"http://127.0.0.1/*"
],
"background": {
"service_worker": "src/chrome/background.ts"
},

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
public/openai-up.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -1,5 +1,7 @@
import React, {useCallback, useEffect, useRef} from 'react'
import React, {useCallback, useEffect, useMemo, useRef} from 'react'
import {
setAskFold,
setAskQuestion,
setAutoScroll,
setAutoTranslate,
setCheckAutoScroll,
@@ -14,27 +16,34 @@ import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {
AiOutlineAim,
AiOutlineCloseCircle,
BsDashSquare,
BsPlusSquare,
FaGripfire,
FaQuestion,
FaRegArrowAltCircleDown,
IoWarning,
MdExpand,
RiFileCopy2Line,
RiTranslate
} from 'react-icons/all'
import classNames from 'classnames'
import toast from 'react-hot-toast'
import SegmentCard from './SegmentCard'
import {
ASK_ENABLED_DEFAULT,
HEADER_HEIGHT,
PAGE_SETTINGS,
RECOMMEND_HEIGHT,
SEARCH_BAR_HEIGHT,
SUMMARIZE_ALL_THRESHOLD,
SUMMARIZE_TYPES,
TITLE_HEIGHT
} from '../const'
import {FaClipboardList} from 'react-icons/fa'
import useTranslate from '../hooks/useTranslate'
import {getSummarize} from '../util/biz_util'
import {openUrl} from '@kky002/kky-util'
import Markdown from '../components/Markdown'
import {random} from 'lodash-es'
import useKeyService from '../hooks/useKeyService'
const Body = () => {
const dispatch = useAppDispatch()
@@ -48,7 +57,13 @@ const Body = () => {
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
const translateEnable = useAppSelector(state => state.env.envData.translateEnable)
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
const {addSummarizeTask} = useTranslate()
const {addSummarizeTask, addAskTask} = useTranslate()
const infos = useAppSelector(state => state.env.infos)
const askFold = useAppSelector(state => state.env.askFold)
const askQuestion = useAppSelector(state => state.env.askQuestion)
const askContent = useAppSelector(state => state.env.askContent)
const askStatus = useAppSelector(state => state.env.askStatus)
const askError = useAppSelector(state => state.env.askError)
const bodyRef = useRef<any>()
const curOffsetTop = useAppSelector(state => state.env.curOffsetTop)
const checkAutoScroll = useAppSelector(state => state.env.checkAutoScroll)
@@ -56,7 +71,27 @@ const Body = () => {
const totalHeight = useAppSelector(state => state.env.totalHeight)
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
const title = useAppSelector(state => state.env.title)
const fontSize = useAppSelector(state => state.env.envData.fontSize)
const searchText = useAppSelector(state => state.env.searchText)
const recommendIdx = useMemo(() => random(0, 3), [])
const showSearchInput = useMemo(() => {
return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT))
}, [envData.askEnabled, envData.searchEnabled, segments])
const searchPlaceholder = useMemo(() => {
let placeholder = ''
if (envData.searchEnabled) {
if (envData.askEnabled??ASK_ENABLED_DEFAULT) {
placeholder = '搜索或提问字幕内容'
} else {
placeholder = '搜索字幕内容'
}
} else {
if (envData.askEnabled??ASK_ENABLED_DEFAULT) {
placeholder = '提问字幕内容'
}
}
return placeholder
}, [envData.askEnabled, envData.searchEnabled])
const normalCallback = useCallback(() => {
dispatch(setTempData({
@@ -102,6 +137,7 @@ const Body = () => {
const onFoldAll = useCallback(() => {
dispatch(setFoldAll(!foldAll))
dispatch(setAskFold(!foldAll))
for (const segment of segments ?? []) {
dispatch(setSegmentFold({
segmentStartIdx: segment.startIdx,
@@ -149,10 +185,36 @@ const Body = () => {
dispatch(setSearchText(''))
}, [dispatch])
const onAsk = useCallback(() => {
if ((envData.askEnabled??ASK_ENABLED_DEFAULT) && searchText) {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (apiKey) {
if (segments != null && segments.length > 0) {
dispatch(setAskQuestion(searchText))
addAskTask(segments[0], searchText).catch(console.error)
}
} else {
dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!')
}
}
}, [addAskTask, dispatch, envData.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, searchText, segments])
const onSetAsk = useCallback(() => {
dispatch(setSearchText(askQuestion??''))
}, [askQuestion, dispatch])
const onAskFold = useCallback(() => {
dispatch(setAskFold(!askFold))
}, [askFold, dispatch])
// service
useKeyService()
// 自动滚动
useEffect(() => {
if (checkAutoScroll && curOffsetTop && autoScroll && !needScroll) {
if (bodyRef.current.scrollTop <= curOffsetTop - bodyRef.current.offsetTop - (totalHeight-120) + (floatKeyPointsSegIdx != null ? 100 : 0) ||
if (bodyRef.current.scrollTop <= curOffsetTop - bodyRef.current.offsetTop - (totalHeight-160) + (floatKeyPointsSegIdx != null ? 100 : 0) ||
bodyRef.current.scrollTop >= curOffsetTop - bodyRef.current.offsetTop - 40 - 10
) {
dispatch(setNeedScroll(true))
@@ -193,8 +255,8 @@ const Body = () => {
</div>
{/* search */}
{envData.searchEnabled && <div className='px-2 py-1 flex flex-col relative'>
<input type='text' className='input input-xs bg-base-200' placeholder='搜索字幕内容' value={searchText} onChange={onSearchTextChange}/>
{showSearchInput && <div className='px-2 py-1 flex flex-col relative'>
<input type='text' className='input input-xs bg-base-200' placeholder={searchPlaceholder} value={searchText} onChange={onSearchTextChange}/>
{searchText && <button className='absolute top-1 right-2 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClearSearchText}><AiOutlineCloseCircle/></button>}
</div>}
@@ -210,57 +272,167 @@ const Body = () => {
<div ref={bodyRef} onWheel={onWheel}
className={classNames('flex flex-col gap-1.5 overflow-y-auto select-text scroll-smooth', floatKeyPointsSegIdx != null && 'pb-[100px]')}
style={{
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - (envData.searchEnabled ? SEARCH_BAR_HEIGHT : 0)}px`
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - RECOMMEND_HEIGHT - (showSearchInput ? SEARCH_BAR_HEIGHT : 0)}px`
}}
>
{/* ask */}
{(envData.askEnabled ?? ASK_ENABLED_DEFAULT) && (searchText || askQuestion) &&
<div className='shadow bg-base-200 my-0.5 mx-1.5 p-1.5 rounded flex flex-col justify-center items-center'>
<div className='w-full relative flex justify-center min-h-[20px]'>
<div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'>
{askFold
? <BsPlusSquare className='cursor-pointer' onClick={onAskFold}/> :
<BsDashSquare className='cursor-pointer' onClick={onAskFold}/>}
</div>
<div className="tabs">
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
<a className='tab tab-lifted tab-xs tab-active'><FaQuestion/></a>
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
</div>
</div>
{!askFold && askQuestion &&
<div className='link link-hover text-sm font-medium max-w-[90%]' onClick={onSetAsk}>{askQuestion}</div>}
{!askFold && askContent &&
<div className={classNames('font-medium max-w-[90%] mt-1', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
<Markdown content={askContent}/>
</div>}
{!askFold && <button disabled={askStatus === 'pending'}
className={classNames('btn btn-link btn-xs', askStatus === 'pending' && 'loading')}
onClick={onAsk}>{askStatus === 'init' ? '点击提问' : (askStatus === 'pending' ? '生成中' : '重新生成')}</button>}
{!askFold && askStatus === 'init' && <div className='desc-lighter text-xs'></div>}
{!askFold && askError && <div className='text-xs text-error'>{askError}</div>}
</div>}
{/* segments */}
{segments?.map((segment, segmentIdx) => <SegmentCard key={segment.startIdx} segment={segment}
segmentIdx={segmentIdx} bodyRef={bodyRef}/>)}
{/* tip */}
<div className='flex flex-col items-center text-center pt-1 pb-2'>
<div className='font-semibold text-accent'>💡<span className='underline underline-offset-4'></span>💡</div>
<div className='text-sm desc px-2'><span className='text-amber-600 font-semibold'></span><span
className='text-secondary/75 font-semibold'></span>🥳
<div className='text-sm font-semibold text-center'></div>
<ul className='list-disc text-sm desc pl-5'>
<li>+</li>
<li>alt+</li>
<li>(使)</li>
</ul>
{/* <div className='flex flex-col items-center text-center pt-1 pb-2'> */}
{/* <div className='font-semibold text-accent'>💡<span className='underline underline-offset-4'>提示</span>💡</div> */}
{/* <div className='text-sm desc px-2'>可以尝试将<span className='text-amber-600 font-semibold'>概览</span>生成的内容粘贴到<span */}
{/* className='text-secondary/75 font-semibold'>视频评论</span>里,发布后看看有什么效果🥳 */}
{/* </div> */}
{/* {(segments?.length ?? 0) > 0 && <button className='mt-1.5 btn btn-xs btn-info' */}
{/* onClick={onCopy}>点击复制生成的{SUMMARIZE_TYPES[curSummaryType].name}<RiFileCopy2Line/> */}
{/* </button>} */}
{/* </div> */}
<div className='flex flex-col'>
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
<div className='font-semibold text-accent flex items-center gap-1'><img src='/bibigpt.png'
alt='BibiGPT logo'
className='w-8 h-8'/>BibiGPT
</div>
<div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'></span><span
className='font-semibold'></span>
</div>
<div className='flex gap-2'>
<a title='BibiGPT' href='https://bibigpt.co/r/bilibili'
onClick={(e) => {
e.preventDefault()
openUrl('https://bibigpt.co/r/bilibili')
}} className='link text-sm text-accent'> BibiGPT </a>
</div>
</div>
{(segments?.length ?? 0) > 0 && <button className='mt-1.5 btn btn-xs btn-info'
onClick={onCopy}>{SUMMARIZE_TYPES[curSummaryType].name}<RiFileCopy2Line/>
</button>}
</div>
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
<div className='font-semibold text-accent flex items-center gap-1'><img src='/bibigpt.png'
alt='BibiGPT'
className='w-8 h-8'/>BibiGPT
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
<div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png'
alt='youtube caption logo'
className='w-8 h-8'/>YouTube Caption
</div>
<div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'>YouTube</span>
</div>
<div className='flex gap-2'>
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf'
onClick={(e) => {
e.preventDefault()
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
}} className='link text-sm text-accent'>Chrome商店</a>
<a title='Edge商店'
href='https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc'
onClick={e => {
e.preventDefault()
openUrl('https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc')
}} className='link text-sm text-accent'>Edge商店</a>
<a title='Crx搜搜(国内可访问)'
href='https://www.crxsoso.com/webstore/detail/fiaeclpicddpifeflpmlgmbjgaedladf'
onClick={(e) => {
e.preventDefault()
openUrl('https://www.crxsoso.com/webstore/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
}} className='link text-sm text-accent'>Crx搜搜(访)</a>
</div>
</div>
<div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'></span><span className='font-semibold'></span></div>
<div className='flex gap-2'>
<a title='BibiGPT' href='https://bibigpt.co/r/bilibili'
onClick={(e) => {
e.preventDefault()
openUrl('https://bibigpt.co/r/bilibili')
}} className='link text-sm text-accent'> BibiGPT </a>
</div>
</div>
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
<div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png'
alt='youtube caption'
className='w-8 h-8'/>YouTube Caption
</div>
<div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'>YouTube</span>
</div>
<div className='flex gap-2'>
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf'
onClick={(e) => {
e.preventDefault()
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
}} className='link text-sm text-accent'>Chrome商店</a>
<a title='Edge商店' href='https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc'
onClick={e => {
e.preventDefault()
openUrl('https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc')
}} className='link text-sm text-accent'>Edge商店</a>
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
<div className='font-semibold text-accent flex items-center gap-1'><img src='/immersive-summary.png'
alt='Immersive Summary logo'
className='w-8 h-8'/>Immersive Summary
</div>
<div className='text-sm px-2 desc'></div>
<div className='flex gap-2'>
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/mcijpllinkhflgpkggimnafkbmpiijah'
onClick={(e) => {
e.preventDefault()
openUrl('https://chromewebstore.google.com/detail/mcijpllinkhflgpkggimnafkbmpiijah')
}} className='link text-sm text-accent'>Chrome商店</a>
<a title='Crx搜搜(国内可访问)'
href='https://www.crxsoso.com/webstore/detail/mcijpllinkhflgpkggimnafkbmpiijah'
onClick={(e) => {
e.preventDefault()
openUrl('https://www.crxsoso.com/webstore/detail/mcijpllinkhflgpkggimnafkbmpiijah')
}} className='link text-sm text-accent'>Crx搜搜(访)</a>
</div>
</div>
</div>
</div>
{/* recommend */}
<div className='p-0.5' style={{
height: `${RECOMMEND_HEIGHT}px`
}}>
{recommendIdx === 0 && <div className='flex items-center gap-1.5 rounded shadow-sm bg-base-200/10'>
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
e.preventDefault()
openUrl('https://bibigpt.co/r/bilibili')
}}><img src='/bibigpt.png'
alt='BibiGPT logo'
className='w-8 h-8'/> BibiGPT </a>
<span className='text-sm desc'></span>
</div>}
{recommendIdx === 1 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'>
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
e.preventDefault()
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
}}><img src='/youtube-caption.png'
alt='youtube caption logo'
className='w-8 h-8'/>YouTube Caption</a>
<span className='text-sm desc'>YouTube版的字幕列表</span>
</div>}
{recommendIdx === 2 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'>
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
e.preventDefault()
openUrl('https://chromewebstore.google.com/detail/mcijpllinkhflgpkggimnafkbmpiijah')
}}><img src='/immersive-summary.png'
alt='Immersive Summary logo'
className='w-8 h-8'/>Immersive Summary</a>
<span className='text-sm desc'></span>
</div>}
{recommendIdx === 3 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'>
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
e.preventDefault()
openUrl('https://api.openai-up.com/register?aff=varM')
}}><img src='/openai-up.ico'
alt='Openai Up logo'
className='w-8 h-8'/>Openai代理</a>
<span className='text-sm desc flex items-center'>6<FaGripfire
className='text-amber-600'/></span>
</div>}
</div>
</div>
}

View File

@@ -9,8 +9,9 @@ const CompactSegmentItem = (props: {
isIn: boolean
last: boolean
moveCallback: (event: any) => void
move2Callback: (event: any) => void
}) => {
const {item, idx, last, isIn, moveCallback} = props
const {item, idx, last, isIn, moveCallback, move2Callback} = props
const transResult = useAppSelector(state => state.env.transResults[idx])
const envData = useAppSelector(state => state.env.envData)
const fontSize = useAppSelector(state => state.env.envData.fontSize)
@@ -19,7 +20,7 @@ const CompactSegmentItem = (props: {
const display = useMemo(() => getDisplay(envData.transDisplay, item.content, transText), [envData.transDisplay, item.content, transText])
return <div className={classNames('inline', fontSize === 'large'?'text-sm':'text-xs')}>
<span className={'pl-1 pr-0.5 py-0.5 cursor-pointer rounded-sm hover:bg-base-200'} onClick={moveCallback}>
<span className={'pl-1 pr-0.5 py-0.5 cursor-pointer rounded-sm hover:bg-base-200'} onClick={moveCallback} onDoubleClick={move2Callback}>
<text className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</text>
{display.sub && <text className='desc'>({display.sub})</text>}</span>
<span className='text-base-content/75'>{!last && ','}</span>

View File

@@ -66,6 +66,7 @@ const MoreBtn = (props: Props) => {
const [moreVisible, setMoreVisible] = useState(false)
const eventBus = useContext(EventBusContext)
const segments = useAppSelector(state => state.env.segments)
const url = useAppSelector(state => state.env.url)
const title = useAppSelector(state => state.env.title)
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
@@ -76,19 +77,19 @@ const MoreBtn = (props: Props) => {
let s, fileName
if (!downloadType || downloadType === 'text') {
s = ''
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
for (const item of data.body) {
s += item.content + '\n'
}
fileName = 'download.txt'
} else if (downloadType === 'textWithTime') {
s = ''
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
for (const item of data.body) {
s += formatTime(item.from) + ' ' + item.content + '\n'
}
fileName = 'download.txt'
} else if (downloadType === 'article') {
s = ''
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
for (const item of data.body) {
s += item.content + ', '
}
@@ -138,9 +139,10 @@ const MoreBtn = (props: Props) => {
s = JSON.stringify(data)
fileName = 'download.json'
} else if (downloadType === 'summarize') {
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
const [success, content] = getSummarize(title, segments, curSummaryType)
if (!success) return
s = content
s += content
fileName = '总结.txt'
} else {
return
@@ -153,7 +155,7 @@ const MoreBtn = (props: Props) => {
}).catch(console.error)
}
setMoreVisible(false)
}, [curSummaryType, data, downloadType, segments, title])
}, [curSummaryType, data, downloadType, segments, title, url])
const downloadAudioCallback = useCallback(() => {
window.parent.postMessage({
@@ -261,27 +263,27 @@ const MoreBtn = (props: Props) => {
(IndieKKY)
</a>
</li>
<li className='hover:bg-accent'>
<a className='flex items-center' onClick={(e) => {
e.preventDefault()
e.stopPropagation()
openUrl('https://bibigpt.co/r/bilibili')
}}>
<img alt='BibiGPT' src='/bibigpt.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/>
BibiGPT
</a>
</li>
<li className='hover:bg-accent'>
<a className='flex items-center' onClick={(e) => {
e.preventDefault()
e.stopPropagation()
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
}}>
<img alt='youtube subtitle' src='/youtube-caption.png'
className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/>
Youtube Caption
</a>
</li>
{/* <li className='hover:bg-accent'> */}
{/* <a className='flex items-center' onClick={(e) => { */}
{/* e.preventDefault() */}
{/* e.stopPropagation() */}
{/* openUrl('https://bibigpt.co/r/bilibili') */}
{/* }}> */}
{/* <img alt='BibiGPT' src='/bibigpt.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/> */}
{/* BibiGPT */}
{/* </a> */}
{/* </li> */}
{/* <li className='hover:bg-accent'> */}
{/* <a className='flex items-center' onClick={(e) => { */}
{/* e.preventDefault() */}
{/* e.stopPropagation() */}
{/* openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf') */}
{/* }}> */}
{/* <img alt='youtube subtitle' src='/youtube-caption.png' */}
{/* className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/> */}
{/* Youtube Caption */}
{/* </a> */}
{/* </li> */}
<li className='hover:bg-accent'>
<a className='flex items-center' onClick={(e) => {
dispatch(setPage(PAGE_SETTINGS))

View File

@@ -9,8 +9,9 @@ const NormalSegmentItem = (props: {
idx: number
isIn: boolean
moveCallback: (event: any) => void
move2Callback: (event: any) => void
}) => {
const {item, idx, isIn, moveCallback} = props
const {item, idx, isIn, moveCallback, move2Callback} = props
const transResult = useAppSelector(state => state.env.transResults[idx])
const envData = useAppSelector(state => state.env.envData)
const fontSize = useAppSelector(state => state.env.envData.fontSize)
@@ -19,7 +20,7 @@ const NormalSegmentItem = (props: {
const display = useMemo(() => getDisplay(envData.transDisplay, item.content, transText), [envData.transDisplay, item.content, transText])
return <div className={classNames('flex py-0.5 cursor-pointer rounded-sm hover:bg-base-200', fontSize === 'large'?'text-sm':'text-xs')}
onClick={moveCallback}>
onClick={moveCallback} onDoubleClick={move2Callback}>
<div className='desc w-[66px] flex justify-center'>{formatTime(item.from)}</div>
<div className={'flex-1'}>
<div className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</div>

View File

@@ -46,7 +46,7 @@ const SummarizeItemOverview = (props: {
if (event.altKey) { // 复制
navigator.clipboard.writeText(overviewItem.key).catch(console.error)
} else {
move(time)
move(time, false)
}
}, [overviewItem.key, move, time])

View File

@@ -33,7 +33,15 @@ const SegmentItem = (props: {
if (event.altKey) { // 复制
navigator.clipboard.writeText(item.content).catch(console.error)
} else {
move(item.from)
move(item.from, false)
}
}, [item.content, item.from, move])
const move2Callback = useCallback((event: any) => {
if (event.altKey) { // 复制
navigator.clipboard.writeText(item.content).catch(console.error)
} else {
move(item.from, true)
}
}, [item.content, item.from, move])
@@ -63,6 +71,7 @@ const SegmentItem = (props: {
isIn={isIn}
last={last}
moveCallback={moveCallback}
move2Callback={move2Callback}
/>
:
<NormalSegmentItem
@@ -70,6 +79,7 @@ const SegmentItem = (props: {
idx={idx}
isIn={isIn}
moveCallback={moveCallback}
move2Callback={move2Callback}
/>
}
</span>

View File

@@ -2,23 +2,27 @@ import React, {PropsWithChildren, useCallback, useMemo, useState} from 'react'
import {setEnvData, setPage} from '../redux/envReducer'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {
ASK_ENABLED_DEFAULT,
CUSTOM_MODEL_TOKENS,
DEFAULT_SERVER_URL_OPENAI,
GEMINI_TOKENS,
HEADER_HEIGHT,
LANGUAGE_DEFAULT,
LANGUAGES,
MODEL_DEFAULT,
MODEL_MAP,
MODELS,
PAGE_MAIN,
PROMPT_DEFAULTS,
PROMPT_TYPES,
SERVER_URL_THIRD,
SUMMARIZE_LANGUAGE_DEFAULT,
TRANSLATE_FETCH_DEFAULT,
TRANSLATE_FETCH_MAX,
TRANSLATE_FETCH_MIN,
TRANSLATE_FETCH_STEP,
WORDS_DEFAULT,
WORDS_RATE,
} from '../const'
import {IoWarning} from 'react-icons/all'
import {FaGripfire, IoWarning} from 'react-icons/all'
import classNames from 'classnames'
import toast from 'react-hot-toast'
import {useBoolean, useEventTarget} from 'ahooks'
@@ -59,6 +63,7 @@ const Settings = () => {
const {value: translateEnableValue, onChange: setTranslateEnableValue} = useEventChecked(envData.translateEnable)
const {value: summarizeEnableValue, onChange: setSummarizeEnableValue} = useEventChecked(envData.summarizeEnable)
const {value: searchEnabledValue, onChange: setSearchEnabledValue} = useEventChecked(envData.searchEnabled)
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 [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''})
@@ -66,13 +71,15 @@ const Settings = () => {
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})
const [customModelTokensValue, setCustomModelTokensValue] = useState(envData.customModelTokens)
const [summarizeLanguageValue, { onChange: onChangeSummarizeLanguageValue }] = useEventTarget({initialValue: envData.summarizeLanguage??SUMMARIZE_LANGUAGE_DEFAULT})
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??WORDS_DEFAULT)
const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words)
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
const [moreFold, {toggle: toggleMoreFold}] = useBoolean(true)
const [promptsFold, {toggle: togglePromptsFold}] = useBoolean(true)
@@ -111,6 +118,8 @@ const Settings = () => {
apiKey: apiKeyValue,
serverUrl: serverUrlValue,
model: modelValue,
customModel: customModelValue,
customModelTokens: customModelTokensValue,
geminiApiKey: geminiApiKeyValue,
translateEnable: translateEnableValue,
language: languageValue,
@@ -126,10 +135,11 @@ const Settings = () => {
prompts: promptsValue,
searchEnabled: searchEnabledValue,
cnSearchEnabled: cnSearchEnabledValue,
askEnabled: askEnabledValue,
}))
dispatch(setPage(PAGE_MAIN))
toast.success('保存成功')
}, [dispatch, aiTypeValue, geminiApiKeyValue, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue])
}, [dispatch, autoExpandValue, aiTypeValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, geminiApiKeyValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue])
const onCancel = useCallback(() => {
dispatch(setPage(PAGE_MAIN))
@@ -205,7 +215,7 @@ const Settings = () => {
<button onClick={onSelFontSize2} className={classNames('btn btn-xs no-animation', fontSizeValue === 'large'?'btn-active':'')}></button>
</div>
</FormItem>
<FormItem title='AI类型' tip='不同AI质量可能有差异'>
<FormItem title='AI类型' tip='OPENAI质量更高'>
<div className="btn-group">
<button onClick={onSelOpenai} className={classNames('btn btn-xs no-animation', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
<button onClick={onSelGemini} className={classNames('btn btn-xs no-animation', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
@@ -215,55 +225,46 @@ const Settings = () => {
{(!aiTypeValue || aiTypeValue === 'openai') && <Section title='openai配置'>
<FormItem title='ApiKey' htmlFor='apiKey'>
<input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx' value={apiKeyValue} onChange={onChangeApiKeyValue}/>
<input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx'
value={apiKeyValue} onChange={onChangeApiKeyValue}/>
</FormItem>
<FormItem title='服务器' htmlFor='serverUrl'>
<input id='serverUrl' type='text' className='input input-sm input-bordered w-full' placeholder='服务器地址,默认使用官方地址' value={serverUrlValue} onChange={e => setServerUrlValue(e.target.value)}/>
<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>
<div className='flex justify-center'>
<a className='link text-xs' onClick={toggleMoreFold}>{moreFold?'点击查看说明':'点击折叠说明'}</a>
<div>
<div className='desc text-xs text-center'>
<div className='flex justify-center font-semibold'></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'></div>
<div><a className='link link-primary' href='https://api.openai-up.com/register?aff=varM'
target='_blank'
rel="noreferrer">访</a></div>
<div><a className='link link-primary'
onClick={() => setServerUrlValue('https://api.openai-up.com')}
rel='noreferrer'></a></div>
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>6<FaGripfire/></div>
</div>
</div>
{!moreFold && <div>
<ul className='pl-3 list-decimal desc text-xs'>
<li>访</li>
<li><a className='link' href='https://platform.openai.com/' target='_blank' rel="noreferrer">openai.com</a></li>
<li>(使ApiKey)<a className='link' onClick={() => setServerUrlValue(SERVER_URL_THIRD)} rel='noreferrer'></a></li>
<li>(ApiKey)<a className='link' href='https://api2d.com/' target='_blank' rel="noreferrer">api2d</a> | <a className='link' onClick={() => setServerUrlValue('https://openai.api2d.net')} rel='noreferrer'></a></li>
<li>(ApiKey)<a className='link' href='https://openaimax.com/' target='_blank' rel="noreferrer">OpenAI-Max</a> | <a className='link' onClick={() => setServerUrlValue('https://api.openaimax.com')} rel='noreferrer'></a></li>
<li>(ApiKey)<a className='link' href='https://openai-sb.com/' target='_blank' rel="noreferrer">OpenAI-SB</a> | <a className='link' onClick={() => setServerUrlValue('https://api.openai-sb.com')} rel='noreferrer'></a></li>
<li>(ApiKey)<a className='link' href='https://www.ohmygpt.com/' target='_blank' rel="noreferrer">OhMyGPT</a> | <a className='link' onClick={() => setServerUrlValue('https://api.ohmygpt.com')} rel='noreferrer'></a></li>
<li>(ApiKey)<a className='link' href='https://aiproxy.io/' target='_blank' rel="noreferrer">AIProxy</a> | <a className='link' onClick={() => setServerUrlValue('https://api.aiproxy.io')} rel='noreferrer'></a></li>
<li>(ApiKey)<a className='link' href='https://key-rental.bowen.cool/' target='_blank' rel="noreferrer">Key Rental</a> | <a className='link' onClick={() => setServerUrlValue('https://key-rental-api.bowen.cool/openai')} rel='noreferrer'></a></li>
<li></li>
</ul>
</div>}
<FormItem title='模型选择' htmlFor='modelSel' tip='注意,不同模型有不同价格'>
<select id='modelSel' className="select select-sm select-bordered" value={modelValue} onChange={onChangeModelValue}>
<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>
<div className='flex justify-center'>
<a className='link text-xs' onClick={togglePromptsFold}>{promptsFold?'点击查看提示词':'点击折叠提示词'}</a>
</div>
{!promptsFold && <div>
{PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
<div>{item.name}</div>
<div className='link text-xs' onClick={() => {
setPromptsValue({
...promptsValue,
// @ts-expect-error
[item.type]: PROMPT_DEFAULTS[item.type]??''
})
}}></div>
</div>} htmlFor={`prompt-${item.type}`}>
<textarea id={`prompt-${item.type}`} className='mt-2 textarea input-bordered w-full' placeholder='留空使用默认提示词' value={promptsValue[item.type]??''} onChange={(e) => {
setPromptsValue({
...promptsValue,
[item.type]: e.target.value
})
}}/>
</FormItem>)}
</div>}
{modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'>
<input id='customModel' type='text' className='input input-sm input-bordered w-full' placeholder='llama2'
value={customModelValue} onChange={onChangeCustomModelValue}/>
</FormItem>}
{modelValue === 'custom' && <FormItem title='Token上限' htmlFor='customModelTokens'>
<input id='customModelTokens' type='number' className='input input-sm input-bordered w-full' placeholder={''+CUSTOM_MODEL_TOKENS}
value={customModelTokensValue} onChange={e => setCustomModelTokensValue(e.target.value?parseInt(e.target.value):undefined)}/>
</FormItem>}
</Section>}
{aiTypeValue === 'gemini' && <Section title='gemini配置'>
@@ -271,42 +272,38 @@ const Settings = () => {
<input id='geminiApiKey' type='text' className='input input-sm input-bordered w-full' placeholder='xxx'
value={geminiApiKeyValue} onChange={onChangeGeminiApiKeyValue}/>
</FormItem>
<div className='flex justify-center'>
<a className='link text-xs' onClick={toggleMoreFold}>{moreFold ? '点击查看说明' : '点击折叠说明'}</a>
</div>
{!moreFold && <div>
<ul className='pl-3 list-decimal desc text-xs'>
<li><a className='link' href='https://makersuite.google.com/app/apikey' target='_blank'
rel="noreferrer">Google AI Studio</a> ()</li>
</ul>
</div>}
<div className='flex justify-center'>
<a className='link text-xs'
onClick={togglePromptsFold}>{promptsFold ? '点击查看提示词' : '点击折叠提示词'}</a>
</div>
{!promptsFold && <div>
{PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
<div>{item.name}</div>
<div className='link text-xs' onClick={() => {
setPromptsValue({
...promptsValue,
// @ts-expect-error
[item.type]: PROMPT_DEFAULTS[item.type] ?? ''
})
}}>
<div>
<div className='desc text-xs'>
<div><a className='link link-primary' href='https://makersuite.google.com/app/apikey' target='_blank'
rel="noreferrer">Google AI Studio</a> ()
</div>
</div>} htmlFor={`prompt-${item.type}`}>
<textarea id={`prompt-${item.type}`} className='mt-2 textarea input-bordered w-full'
placeholder='留空使用默认提示词' value={promptsValue[item.type] ?? ''} onChange={(e) => {
setPromptsValue({
...promptsValue,
[item.type]: e.target.value
})
}}/>
</FormItem>)}
</div>}
<div className='text-xs text-error flex items-center'><IoWarning className='text-sm text-warning'/>!</div>
</div>
</div>
</Section>}
<Section title='提示词配置'>
{PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
<div>{item.name}</div>
<div className='link text-xs' onClick={() => {
setPromptsValue({
...promptsValue,
// @ts-expect-error
[item.type]: PROMPT_DEFAULTS[item.type] ?? ''
})
}}>
</div>
</div>} htmlFor={`prompt-${item.type}`}>
<textarea id={`prompt-${item.type}`} className='mt-2 textarea input-bordered w-full'
placeholder='留空使用默认提示词' value={promptsValue[item.type] ?? ''} onChange={(e) => {
setPromptsValue({
...promptsValue,
[item.type]: e.target.value
})
}}/>
</FormItem>)}
</Section>
<Section title={<div className='flex items-center'>
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
@@ -318,7 +315,8 @@ const Settings = () => {
onChange={setTranslateEnableValue}/>
</FormItem>
<FormItem title='目标语言' htmlFor='language'>
<select id='language' className="select select-sm select-bordered" value={languageValue} onChange={onChangeLanguageValue}>
<select id='language' className="select select-sm select-bordered" value={languageValue}
onChange={onChangeLanguageValue}>
{LANGUAGES.map(language => <option key={language.code} value={language.code}>{language.name}</option>)}
</select>
</FormItem>
@@ -363,13 +361,17 @@ const Settings = () => {
</FormItem>
<FormItem htmlFor='words' title='分段字数' tip='注意,不同模型有不同字数限制'>
<div className='flex-1 flex flex-col'>
<input id='words' type='number' className='input input-sm input-bordered w-full' placeholder='默认2000' value={wordsValue} onChange={e => setWordsValue(e.target.value?parseInt(e.target.value):undefined)}/>
<input id='words' type='number' className='input input-sm input-bordered w-full' placeholder={`默认为上限x${WORDS_RATE}`} value={wordsValue??''} onChange={e => setWordsValue(e.target.value?parseInt(e.target.value):undefined)}/>
{/* <input type="range" min={WORDS_MIN} max={WORDS_MAX} step={WORDS_STEP} value={wordsValue} className="range range-primary" onChange={onWordsChange} /> */}
{/* <div className="w-full flex justify-between text-xs px-2"> */}
{/* {wordsList.map(words => <span key={words}>{words}</span>)} */}
{/* </div> */}
</div>
</FormItem>
<div className='desc text-xs'>
<span className='font-semibold font-mono'>{aiTypeValue === 'gemini'?GEMINI_TOKENS:(MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知')}</span>
</div>
</Section>
<Section title={<div className='flex items-center'>
@@ -383,6 +385,14 @@ const Settings = () => {
onChange={setCnSearchEnabledValue}/>
</FormItem>
</Section>
<Section title={<div className='flex items-center'>
</div>}>
<FormItem title='启用提问' htmlFor='askEnabled' tip='是否启用字幕提问功能'>
<input id='askEnabled' type='checkbox' className='toggle toggle-primary' checked={askEnabledValue}
onChange={setAskEnabledValue}/>
</FormItem>
</Section>
<div className='flex justify-center gap-5'>
<button className='btn btn-primary btn-sm' onClick={onSave}></button>
<button className='btn btn-sm' onClick={onCancel}></button>

View File

@@ -102,6 +102,7 @@ const refreshVideoInfo = async () => {
//send setVideoInfo
iframe.contentWindow.postMessage({
type: 'setVideoInfo',
url: location.origin + location.pathname,
title,
aid,
pages,
@@ -157,6 +158,9 @@ window.addEventListener("message", (event) => {
const video = getVideoElement()
if (video) {
video.currentTime = data.time
if (data.togglePause) {
video.paused ? video.play() : video.pause()
}
}
}

View File

@@ -1,4 +1,14 @@
import {getServerUrl} from '../util/biz_util'
import {DEFAULT_SERVER_URL_OPENAI} from '../const'
const getServerUrl = (serverUrl?: string) => {
if (!serverUrl) {
return DEFAULT_SERVER_URL_OPENAI
}
if (serverUrl.endsWith('/')) {
serverUrl = serverUrl.slice(0, -1)
}
return serverUrl
}
export const handleChatCompleteTask = async (task: Task) => {
const data = task.def.data

View File

@@ -0,0 +1,46 @@
import classNames from 'classnames'
import ReactMarkdown from 'react-markdown'
import toast from 'react-hot-toast'
function CopyBtn(props: {
content: string
}) {
const {content} = props
return <div className='flex justify-center mt-1'>
<button className="btn btn-xs px-10 btn-primary normal-case" onClick={() => {
navigator.clipboard.writeText(content).then(() => {
toast.success('Copied!')
}).catch(console.error)
}}>Copy
</button>
</div>
}
function Markdown(props: {
content: string
codeBlockClass?: string
}) {
const {content, codeBlockClass} = props
return <ReactMarkdown
className='markdown prose prose-sm dark:prose-invert prose-h1:text-center prose-h1:font-bold prose-h1:underline-offset-4 overflow-y-auto scrollbar-hide'
linkTarget={'_blank'}
components={{
code({node, inline, className, children, ...props}) {
if (inline) {
return <code
className={classNames(className, 'md-inline-block kbd kbd-xs rounded text-base-content/80')} {...props}>
{children}
</code>
} else {
return <code className={classNames(className, 'relative', codeBlockClass)} {...props}>
{children}
{className?.includes('language-copy') && <CopyBtn content={children[0] as string}/>}
</code>
}
}
}}
>{content}</ReactMarkdown>
}
export default Markdown

View File

@@ -9,6 +9,7 @@ export const PROMPT_TYPE_TRANSLATE = 'translate'
export const PROMPT_TYPE_SUMMARIZE_OVERVIEW = 'summarize_overview'
export const PROMPT_TYPE_SUMMARIZE_KEYPOINT = 'summarize_keypoint'
export const PROMPT_TYPE_SUMMARIZE_BRIEF = 'summarize_brief'
export const PROMPT_TYPE_ASK = 'ask'
export const PROMPT_TYPES = [{
name: '翻译',
type: PROMPT_TYPE_TRANSLATE,
@@ -21,6 +22,9 @@ export const PROMPT_TYPES = [{
}, {
name: '总结',
type: PROMPT_TYPE_SUMMARIZE_BRIEF,
}, {
name: '提问',
type: PROMPT_TYPE_ASK,
}]
export const SUMMARIZE_TYPES = {
@@ -119,7 +123,20 @@ The video's subtitles:
'''
{{segment}}
'''`
'''`,
[PROMPT_TYPE_ASK]: `You are a helpful assistant who answers question related to video subtitles.
Answer in language '{{language}}'.
The video's title: '''{{title}}'''.
The video's subtitles:
'''
{{segment}}
'''
Question: '''{{question}}'''
Answer:
`,
}
export const EVENT_EXPAND = 'expand'
@@ -142,29 +159,41 @@ export const TOTAL_HEIGHT_MAX = 800
export const HEADER_HEIGHT = 44
export const TITLE_HEIGHT = 24
export const SEARCH_BAR_HEIGHT = 32
export const RECOMMEND_HEIGHT = 36
export const WORDS_DEFAULT = import.meta.env.VITE_ENV === 'web-dev'?500:2000
export const WORDS_RATE = 0.75
export const WORDS_MIN = 500
export const WORDS_MAX = 16000
export const WORDS_STEP = 500
export const SUMMARIZE_THRESHOLD = 100
export const SUMMARIZE_LANGUAGE_DEFAULT = 'cn'
export const SUMMARIZE_ALL_THRESHOLD = 5
export const SERVER_URL_OPENAI = 'https://api.openai.com'
export const SERVER_URL_THIRD = 'https://op.kongkongye.com'
export const ASK_ENABLED_DEFAULT = true
export const DEFAULT_SERVER_URL_OPENAI = 'https://api.openai.com'
export const CUSTOM_MODEL_TOKENS = 16385
export const MODELS = [{
code: 'gpt-3.5-turbo',
name: 'gpt-3.5-turbo',
tokens: 4096,
}, {
code: 'gpt-3.5-turbo-0125',
name: 'gpt-3.5-turbo-0125',
tokens: 16385,
}, {
code: 'gpt-3.5-turbo-1106',
name: 'gpt-3.5-turbo-1106',
tokens: 16385,
}, {
code: 'custom',
name: '自定义',
}]
export const MODEL_DEFAULT = MODELS[0].code
export const GEMINI_TOKENS = 32768
export const MODEL_DEFAULT = MODELS[1].code
export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {}
for (const model of MODELS) {
MODEL_MAP[model.code] = model
}
export const LANGUAGES = [{
code: 'en',

View File

@@ -0,0 +1,59 @@
import {useEffect} from 'react'
import {useMemoizedFn} from 'ahooks/es'
import {useAppSelector} from './redux'
import useSubtitle from './useSubtitle'
const useKeyService = () => {
const curIdx = useAppSelector(state => state.env.curIdx)
const data = useAppSelector(state => state.env.data)
const {move} = useSubtitle()
const onKeyDown = useMemoizedFn((e: KeyboardEvent) => {
// 有按其他控制键时,不触发
if (e.ctrlKey || e.metaKey || e.shiftKey) {
return
}
let cursorInInput = false
if (document.activeElement != null) {
const tagName = document.activeElement.tagName
if (tagName === 'INPUT' || tagName === 'TEXTAREA') {
cursorInInput = true
}
}
let prevent = false
// up arrow
if (e.key === 'ArrowUp') {
if (curIdx && (data != null) && !cursorInInput) {
prevent = true
const newCurIdx = Math.max(curIdx - 1, 0)
move(data.body[newCurIdx].from, false)
}
}
// down arrow
if (e.key === 'ArrowDown') {
if (curIdx !== undefined && (data != null) && !cursorInInput) {
prevent = true
const newCurIdx = Math.min(curIdx + 1, data.body.length - 1)
move(data.body[newCurIdx].from, false)
}
}
// 阻止默认事件
if (prevent) {
e.preventDefault()
e.stopPropagation()
}
})
// 检测快捷键
useEffect(() => {
document.addEventListener('keydown', onKeyDown)
return () => {
document.removeEventListener('keydown', onKeyDown)
}
}, [onKeyDown])
}
export default useKeyService

View File

@@ -21,6 +21,9 @@ const useSearchService = () => {
// reset search
useEffect(() => {
if (!envData.searchEnabled) {
return
}
const startTime = Date.now()
const docs: Document[] = []
for (const item of data?.body??[]) {
@@ -35,13 +38,13 @@ const useSearchService = () => {
// 日志
const endTime = Date.now()
console.debug(`[Search]reset ${docs.length} docs, cost ${endTime-startTime}ms`)
}, [data?.body, dispatch, reset])
}, [data?.body, dispatch, envData.searchEnabled, reset])
// search text
useEffect(() => {
const searchResult: Set<number> = new Set()
if (searchText) {
if (envData.searchEnabled && searchText) {
// @ts-expect-error
const documents: Document[] | undefined = search(searchText)
if (documents != null) {
@@ -52,7 +55,7 @@ const useSearchService = () => {
}
dispatch(setSearchResult(searchResult))
}, [dispatch, search, searchText])
}, [dispatch, envData.searchEnabled, search, searchText])
}
export default useSearchService

View File

@@ -5,8 +5,8 @@ import {setNeedScroll} from '../redux/envReducer'
const useSubtitle = () => {
const dispatch = useAppDispatch()
const move = useCallback((time: number) => {
window.parent.postMessage({type: 'move', time}, '*')
const move = useCallback((time: number, togglePause: boolean) => {
window.parent.postMessage({type: 'move', time, togglePause}, '*')
}, [])
const scrollIntoView = useCallback((ref: React.RefObject<HTMLDivElement>) => {

View File

@@ -12,11 +12,12 @@ import {
setSegments,
setTitle,
setTotalHeight,
setUrl,
} from '../redux/envReducer'
import {EventBusContext} from '../Router'
import {EVENT_EXPAND, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_DEFAULT, WORDS_MIN} from '../const'
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../const'
import {useInterval} from 'ahooks'
import {getWholeText} from '../util/biz_util'
import {getModelMaxTokens, getWholeText} from '../util/biz_util'
/**
* Service是单例类似后端的服务概念
@@ -46,6 +47,7 @@ const useSubtitleService = () => {
if (data.type === 'setVideoInfo') {
dispatch(setInfos(data.infos))
dispatch(setUrl(data.url))
dispatch(setTitle(data.title))
console.debug('video title: ', data.title)
}
@@ -94,7 +96,7 @@ const useSubtitleService = () => {
type: EVENT_EXPAND
})
}
}, [data, eventBus])
}, [data, eventBus, infos])
// 当前未展示 & (未折叠 | 自动展开) & 有列表 => 展示第一个
useEffect(() => {
@@ -156,7 +158,14 @@ const useSubtitleService = () => {
const items = data?.body
if (items != null) {
if (envData.summarizeEnable) { // 分段
let size = envData.words??WORDS_DEFAULT
let size = envData.words
if (!size) { // 默认
if (envData.aiType === 'gemini') {
size = GEMINI_TOKENS*WORDS_RATE
} else {
size = getModelMaxTokens(envData)*WORDS_RATE
}
}
size = Math.max(size, WORDS_MIN)
segments = []
@@ -191,7 +200,7 @@ const useSubtitleService = () => {
}
}
dispatch(setSegments(segments))
}, [data?.body, dispatch, envData.summarizeEnable, envData.words])
}, [data?.body, dispatch, envData])
// 每秒更新当前视频时间
useInterval(() => {

View File

@@ -4,6 +4,9 @@ import {
addTaskId,
addTransResults,
delTaskId,
setAskContent,
setAskError,
setAskStatus,
setLastSummarizeTime,
setLastTransTime,
setSummaryContent,
@@ -13,8 +16,8 @@ import {
import {
LANGUAGE_DEFAULT,
LANGUAGES_MAP,
MODEL_DEFAULT,
PROMPT_DEFAULTS,
PROMPT_TYPE_ASK,
PROMPT_TYPE_TRANSLATE,
SUMMARIZE_LANGUAGE_DEFAULT,
SUMMARIZE_THRESHOLD,
@@ -24,7 +27,7 @@ import {
} from '../const'
import toast from 'react-hot-toast'
import {useMemoizedFn} from 'ahooks/es'
import {extractJsonArray, extractJsonObject} from '../util/biz_util'
import {extractJsonArray, extractJsonObject, getModel} from '../util/biz_util'
import {formatTime} from '../util/util'
const useTranslate = () => {
@@ -100,14 +103,14 @@ const useTranslate = () => {
}
}
:{
model: envData.model??MODEL_DEFAULT,
model: getModel(envData),
messages: [
{
role: 'user',
content: prompt,
}
],
temperature: 0,
temperature: 0.25,
n: 1,
stream: false,
},
@@ -133,7 +136,7 @@ const useTranslate = () => {
dispatch(addTaskId(task.id))
}
}
}, [data?.body, envData.fetchAmount, envData.prompts, envData.aiType, envData.serverUrl, envData.model, envData.apiKey, envData.geminiApiKey, language.name, title, dispatch])
}, [data?.body, envData, language.name, title, dispatch])
const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => {
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
@@ -169,14 +172,14 @@ const useTranslate = () => {
}
}
:{
model: envData.model??MODEL_DEFAULT,
model: getModel(envData),
messages: [
{
role: 'user',
content: prompt,
}
],
temperature: 0,
temperature: 0.5,
n: 1,
stream: false,
},
@@ -194,7 +197,60 @@ const useTranslate = () => {
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
dispatch(addTaskId(task.id))
}
}, [dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, envData.model, envData.prompts, envData.serverUrl, summarizeLanguage.name, title])
}, [dispatch, envData, summarizeLanguage.name, title])
const addAskTask = useCallback(async (segment: Segment, question: string) => {
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
let prompt: string = envData.prompts?.[PROMPT_TYPE_ASK]??PROMPT_DEFAULTS[PROMPT_TYPE_ASK]
// replace params
prompt = prompt.replaceAll('{{language}}', summarizeLanguage.name)
prompt = prompt.replaceAll('{{title}}', title??'')
prompt = prompt.replaceAll('{{segment}}', segment.text)
prompt = prompt.replaceAll('{{question}}', question)
const taskDef: TaskDef = {
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
serverUrl: envData.serverUrl,
data: envData.aiType === 'gemini'
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
:{
model: getModel(envData),
messages: [
{
role: 'user',
content: prompt,
}
],
temperature: 0.5,
n: 1,
stream: false,
},
extra: {
type: 'ask',
// startIdx: segment.startIdx,
apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
}
}
console.debug('addAskTask', taskDef)
dispatch(setAskStatus({status: 'pending'}))
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
dispatch(addTaskId(task.id))
}
}, [dispatch, envData, summarizeLanguage.name, title])
const handleTranslate = useMemoizedFn((task: Task, content: string) => {
let map: {[key: string]: string} = {}
@@ -247,6 +303,13 @@ const useTranslate = () => {
console.debug('setSummary', task.def.extra.startIdx, summaryType, obj, task.error)
})
const handleAsk = useMemoizedFn((task: Task, content?: string) => {
dispatch(setAskContent({content}))
dispatch(setAskStatus({status: 'done'}))
dispatch(setAskError({error: task.error}))
console.debug('setAsk', content, task.error)
})
const getTask = useCallback(async (taskId: string) => {
const taskResp = await chrome.runtime.sendMessage({type: 'getTask', taskId})
if (taskResp.code === 'ok') {
@@ -266,14 +329,16 @@ const useTranslate = () => {
handleTranslate(task, content)
} else if (taskType === 'summarize') { // 总结
handleSummarize(task, content)
} else if (taskType === 'ask') { // 总结
handleAsk(task, content)
}
}
} else {
dispatch(delTaskId(taskId))
}
}, [dispatch, envData.aiType, handleSummarize, handleTranslate])
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate])
return {getFetch, getTask, addTask, addSummarizeTask}
return {getFetch, getTask, addTask, addSummarizeTask, addAskTask}
}
export default useTranslate

View File

@@ -1,7 +1,7 @@
import {createSlice, PayloadAction} from '@reduxjs/toolkit'
import {find} from 'lodash-es'
import {getDevData} from '../util/biz_util'
import {SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../const'
import {DEFAULT_SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../const'
interface EnvState {
envData: EnvData
@@ -30,6 +30,7 @@ interface EnvState {
data?: Transcript
uploadedTranscript?: Transcript
segments?: Segment[]
url?: string
title?: string
taskIds?: string[]
@@ -37,13 +38,20 @@ interface EnvState {
lastTransTime?: number
lastSummarizeTime?: number
// ask
askFold?: boolean
askQuestion?: string
askStatus: SummaryStatus
askError?: string
askContent?: string
searchText: string
searchResult: Set<number>
}
const initialState: EnvState = {
envData: {
serverUrl: SERVER_URL_OPENAI,
serverUrl: DEFAULT_SERVER_URL_OPENAI,
translateEnable: true,
summarizeEnable: true,
autoExpand: true,
@@ -53,6 +61,7 @@ const initialState: EnvState = {
tempData: {
curSummaryType: 'overview',
},
askStatus: 'init',
totalHeight: TOTAL_HEIGHT_DEF,
autoScroll: true,
currentTime: import.meta.env.VITE_ENV === 'web-dev' ? 30 : undefined,
@@ -195,6 +204,27 @@ export const slice = createSlice({
}
}
},
setAskFold: (state, action: PayloadAction<boolean>) => {
state.askFold = action.payload
},
setAskQuestion: (state, action: PayloadAction<string | undefined>) => {
state.askQuestion = action.payload
},
setAskContent: (state, action: PayloadAction<{
content?: any
}>) => {
state.askContent = action.payload.content
},
setAskStatus: (state, action: PayloadAction<{
status: SummaryStatus
}>) => {
state.askStatus = action.payload.status
},
setAskError: (state, action: PayloadAction<{
error?: string
}>) => {
state.askError = action.payload.error
},
setSegmentFold: (state, action: PayloadAction<{
segmentStartIdx: number
fold: boolean
@@ -231,6 +261,9 @@ export const slice = createSlice({
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
state.currentTime = action.payload
},
setUrl: (state, action: PayloadAction<string | undefined>) => {
state.url = action.payload
},
setTitle: (state, action: PayloadAction<string | undefined>) => {
state.title = action.payload
},
@@ -259,6 +292,12 @@ export const slice = createSlice({
})
export const {
setUrl,
setAskFold,
setAskQuestion,
setAskStatus,
setAskError,
setAskContent,
setTempReady,
setTempData,
setUploadedTranscript,

5
src/typings.d.ts vendored
View File

@@ -7,6 +7,8 @@ interface EnvData {
apiKey?: string
serverUrl?: string
model?: string
customModel?: string
customModelTokens?: number
// gemini
geminiApiKey?: string
@@ -26,6 +28,9 @@ interface EnvData {
searchEnabled?: boolean
cnSearchEnabled?: boolean
// ask
askEnabled?: boolean
prompts?: {
[key: string]: string
}

View File

@@ -1,5 +1,5 @@
import devData from '../data/data.json'
import {APP_DOM_ID, SUMMARIZE_TYPES} from '../const'
import {APP_DOM_ID, CUSTOM_MODEL_TOKENS, MODEL_DEFAULT, MODEL_MAP, SUMMARIZE_TYPES} from '../const'
import {isDarkMode} from '@kky002/kky-util'
import toast from 'react-hot-toast'
import {findIndex} from 'lodash-es'
@@ -123,6 +123,22 @@ export const getServerUrl = (serverUrl?: string) => {
return serverUrl
}
export const getModel = (envData: EnvData) => {
if (envData.model === 'custom') {
return envData.customModel
} else {
return envData.model
}
}
export const getModelMaxTokens = (envData: EnvData) => {
if (envData.model === 'custom') {
return envData.customModelTokens??CUSTOM_MODEL_TOKENS
} else {
return MODEL_MAP[envData.model??MODEL_DEFAULT]?.tokens??4000
}
}
export const setTheme = (theme: EnvData['theme']) => {
const appRoot = document.getElementById(APP_DOM_ID)
if (appRoot != null) {