12 Commits
1.7.4 ... 1.7.8

Author SHA1 Message Date
IndieKKY
728e4dce84 chore: release 1.7.8 2023-12-24 09:05:41 +08:00
IndieKKY
a54b4a7e5f youtube caption 调整 2023-12-24 09:02:13 +08:00
IndieKKY
8a908ecf99 主颜色调整 2023-12-24 09:01:18 +08:00
IndieKKY
bdc7823965 chore: release 1.7.7 2023-11-28 19:45:30 +08:00
IndieKKY
8d1bac4623 添加字幕搜索功能 2023-11-28 19:43:58 +08:00
IndieKKY
9f486b7269 readme 2023-11-28 10:46:59 +08:00
IndieKKY
e10de9bc48 version 2023-11-28 10:35:51 +08:00
IndieKKY
dd7ce4ab38 readme 2023-11-28 10:34:20 +08:00
IndieKKY
250da4fd28 添加firefox支持 2023-11-28 10:30:42 +08:00
IndieKKY
65861829e2 增加模型选择 2023-11-28 10:23:35 +08:00
IndieKKY
0b4890399a chore: release 1.7.5 2023-11-18 08:51:35 +08:00
IndieKKY
51bf522eeb 添加youtube版字幕列表链接 2023-11-18 08:51:21 +08:00
20 changed files with 452 additions and 41 deletions

View File

@@ -19,7 +19,9 @@
## 下载扩展 ## 下载扩展
[chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp) - [chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp)
- [edge商店](https://microsoftedge.microsoft.com/addons/detail/lignnlhlpiefmcjkdkmfjdckhlaiajan)
- [firefox商店](https://addons.mozilla.org/zh-CN/firefox/addon/bilibili-subtitle)
## 使用说明 ## 使用说明

22
fixFirefox.cjs Normal file
View File

@@ -0,0 +1,22 @@
console.log('fixFirefox.js loaded');
const fs = require('fs')
const manifest = require('./dist/manifest.json')
manifest.web_accessible_resources[0].resources.push('index.html')
manifest.action.default_popup = 'popup.html'
//browser_specific_settings
manifest.browser_specific_settings = {
"gecko": {
"id": "bilibili-subtitle@indiekky"
}
}
//background
manifest.background = {
type: "module",
scripts: [manifest.background.service_worker]
}
//写回文件
fs.writeFileSync('./dist/manifest.json', JSON.stringify(manifest, null, 2))
console.log('fixFirefox.js done');

View File

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

View File

@@ -1,15 +1,16 @@
{ {
"private": true, "private": true,
"name": "bilibili-subtitle", "name": "bilibili-subtitle",
"version": "1.7.4", "version": "1.7.8",
"type": "module", "type": "module",
"description": "哔哩哔哩字幕列表", "description": "哔哩哔哩字幕列表",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build_chrome": "tsc && vite build -m production_chrome && pnpm run fixChrome", "build": "tsc && vite build -m production_chrome",
"fix": "eslint --fix --quiet .", "build_chrome": "pnpm run build && node fixChrome.cjs",
"fixChrome": "node fixChrome.cjs" "build_firefox": "pnpm run build && node fixFirefox.cjs",
"fix": "eslint --fix --quiet ."
}, },
"author": "IndieKKY", "author": "IndieKKY",
"license": "MIT", "license": "MIT",

10
pnpm-lock.yaml generated
View File

@@ -1,5 +1,9 @@
lockfileVersion: '6.0' lockfileVersion: '6.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
dependencies: dependencies:
'@crxjs/vite-plugin': '@crxjs/vite-plugin':
specifier: ^1.0.14 specifier: ^1.0.14
@@ -2386,6 +2390,7 @@ packages:
/iconv-lite@0.6.3: /iconv-lite@0.6.3:
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
requiresBuild: true
dependencies: dependencies:
safer-buffer: 2.1.2 safer-buffer: 2.1.2
optional: true optional: true
@@ -3392,6 +3397,7 @@ packages:
/pify@4.0.1: /pify@4.0.1:
resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==} resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==}
engines: {node: '>=6'} engines: {node: '>=6'}
requiresBuild: true
optional: true optional: true
/postcss-import@14.1.0(postcss@8.4.19): /postcss-import@14.1.0(postcss@8.4.19):
@@ -3475,6 +3481,7 @@ packages:
/prr@1.0.1: /prr@1.0.1:
resolution: {integrity: sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==} resolution: {integrity: sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==}
requiresBuild: true
optional: true optional: true
/punycode@2.1.1: /punycode@2.1.1:
@@ -3802,10 +3809,12 @@ packages:
/safer-buffer@2.1.2: /safer-buffer@2.1.2:
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
requiresBuild: true
optional: true optional: true
/sax@1.2.4: /sax@1.2.4:
resolution: {integrity: sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==} resolution: {integrity: sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==}
requiresBuild: true
optional: true optional: true
/scheduler@0.23.0: /scheduler@0.23.0:
@@ -3822,6 +3831,7 @@ packages:
/semver@5.7.1: /semver@5.7.1:
resolution: {integrity: sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==} resolution: {integrity: sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==}
hasBin: true hasBin: true
requiresBuild: true
optional: true optional: true
/semver@6.3.0: /semver@6.3.0:

View File

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -15,6 +15,7 @@ import {handleJson} from '@kky002/kky-util'
import {useLocalStorage} from '@kky002/kky-hooks' import {useLocalStorage} from '@kky002/kky-hooks'
import {Toaster} from 'react-hot-toast' import {Toaster} from 'react-hot-toast'
import {setTheme} from './util/biz_util' import {setTheme} from './util/biz_util'
import useSearchService from './hooks/useSearchService'
function App() { function App() {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
@@ -72,6 +73,7 @@ function App() {
// services // services
useSubtitleService() useSubtitleService()
useTranslateService() useTranslateService()
useSearchService()
return <div className={classNames('select-none', import.meta.env.VITE_ENV === 'web-dev'?'w-[350px]':'w-full')} style={{ return <div className={classNames('select-none', import.meta.env.VITE_ENV === 'web-dev'?'w-[350px]':'w-full')} style={{
height: fold?undefined:`${totalHeight}px`, height: fold?undefined:`${totalHeight}px`,

View File

@@ -7,17 +7,34 @@ import {
setFoldAll, setFoldAll,
setNeedScroll, setNeedScroll,
setPage, setPage,
setSearchText,
setSegmentFold setSegmentFold
} from '../redux/envReducer' } from '../redux/envReducer'
import {useAppDispatch, useAppSelector} from '../hooks/redux' import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {AiOutlineAim, FaRegArrowAltCircleDown, IoWarning, MdExpand, RiFileCopy2Line, RiTranslate} from 'react-icons/all' import {
AiOutlineAim,
AiOutlineCloseCircle,
FaRegArrowAltCircleDown,
IoWarning,
MdExpand,
RiFileCopy2Line,
RiTranslate
} from 'react-icons/all'
import classNames from 'classnames' import classNames from 'classnames'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import SegmentCard from './SegmentCard' import SegmentCard from './SegmentCard'
import {HEADER_HEIGHT, PAGE_SETTINGS, SUMMARIZE_ALL_THRESHOLD, SUMMARIZE_TYPES, TITLE_HEIGHT} from '../const' import {
HEADER_HEIGHT,
PAGE_SETTINGS,
SEARCH_BAR_HEIGHT,
SUMMARIZE_ALL_THRESHOLD,
SUMMARIZE_TYPES,
TITLE_HEIGHT
} from '../const'
import {FaClipboardList} from 'react-icons/fa' import {FaClipboardList} from 'react-icons/fa'
import useTranslate from '../hooks/useTranslate' import useTranslate from '../hooks/useTranslate'
import {getSummarize} from '../util/biz_util' import {getSummarize} from '../util/biz_util'
import {openUrl} from '@kky002/kky-util'
const Body = () => { const Body = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
@@ -40,6 +57,7 @@ const Body = () => {
const totalHeight = useAppSelector(state => state.env.totalHeight) const totalHeight = useAppSelector(state => state.env.totalHeight)
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType) const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
const title = useAppSelector(state => state.env.title) const title = useAppSelector(state => state.env.title)
const searchText = useAppSelector(state => state.env.searchText)
const normalCallback = useCallback(() => { const normalCallback = useCallback(() => {
dispatch(setCompact(false)) dispatch(setCompact(false))
@@ -117,6 +135,15 @@ const Body = () => {
} }
}, [curSummaryType, segments, title]) }, [curSummaryType, segments, title])
const onSearchTextChange = useCallback((e: any) => {
const searchText = e.target.value
dispatch(setSearchText(searchText))
}, [dispatch])
const onClearSearchText = useCallback(() => {
dispatch(setSearchText(''))
}, [dispatch])
// 自动滚动 // 自动滚动
useEffect(() => { useEffect(() => {
if (checkAutoScroll && curOffsetTop && autoScroll && !needScroll) { if (checkAutoScroll && curOffsetTop && autoScroll && !needScroll) {
@@ -131,6 +158,7 @@ const Body = () => {
}, [autoScroll, checkAutoScroll, curOffsetTop, dispatch, floatKeyPointsSegIdx, needScroll, totalHeight]) }, [autoScroll, checkAutoScroll, curOffsetTop, dispatch, floatKeyPointsSegIdx, needScroll, totalHeight])
return <div className='relative'> return <div className='relative'>
{/* title */}
<div className='absolute top-1 left-6 flex-center gap-1'> <div className='absolute top-1 left-6 flex-center gap-1'>
<AiOutlineAim className='cursor-pointer' onClick={posCallback} title='滚动到视频位置'/> <AiOutlineAim className='cursor-pointer' onClick={posCallback} title='滚动到视频位置'/>
{segments != null && segments.length > 0 && {segments != null && segments.length > 0 &&
@@ -158,30 +186,48 @@ const Body = () => {
<IoWarning className='text-warning'/> <IoWarning className='text-warning'/>
</div>} </div>}
</div> </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}/>
{searchText && <button className='absolute top-1 right-2 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClearSearchText}><AiOutlineCloseCircle/></button>}
</div>}
{/* auto scroll btn */}
{!autoScroll && <div {!autoScroll && <div
className='absolute z-[999] top-[96px] right-6 tooltip tooltip-left cursor-pointer rounded-full bg-primary/25 hover:bg-primary/75 text-primary-content p-1.5 text-xl' className='absolute z-[999] top-[96px] right-6 tooltip tooltip-left cursor-pointer rounded-full bg-primary/25 hover:bg-primary/75 text-primary-content p-1.5 text-xl'
data-tip='开启自动滚动' data-tip='开启自动滚动'
onClick={onEnableAutoScroll}> onClick={onEnableAutoScroll}>
<FaRegArrowAltCircleDown className={autoScroll ? 'text-accent' : ''}/> <FaRegArrowAltCircleDown className={autoScroll ? 'text-accent' : ''}/>
</div>} </div>}
{/* body */}
<div ref={bodyRef} onWheel={onWheel} <div ref={bodyRef} onWheel={onWheel}
className={classNames('flex flex-col gap-1.5 overflow-y-auto select-text scroll-smooth', floatKeyPointsSegIdx != null && 'pb-[100px]')} className={classNames('flex flex-col gap-1.5 overflow-y-auto select-text scroll-smooth', floatKeyPointsSegIdx != null && 'pb-[100px]')}
style={{ style={{
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT}px` height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - (envData.searchEnabled?SEARCH_BAR_HEIGHT:0)}px`
}} }}
> >
{segments?.map((segment, segmentIdx) => <SegmentCard key={segment.startIdx} segment={segment} segmentIdx={segmentIdx} bodyRef={bodyRef}/>)} {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='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='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> <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>} {(segments?.length??0) > 0 && <button className='mt-1.5 btn btn-xs btn-info' onClick={onCopy}>{SUMMARIZE_TYPES[curSummaryType].name}<RiFileCopy2Line/></button>}
</div> </div>
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'> <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-subtitle.png' alt='youtube subtitle' className='w-8 h-8'/>Youtube Subtitle</div> <div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png' alt='youtube caption pro' className='w-8 h-8'/>YouTube Caption Pro</div>
<div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'>Youtube</span></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'> <div className='flex gap-2'>
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf' className='link text-sm text-accent'>Chrome商店</a> <a title='Chrome商店' href='https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf' onClick={(e) => {
<a title='Edge商店' href='https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc' className='link text-sm text-accent'>Edge商店</a> 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> </div>
</div> </div>
</div> </div>

View File

@@ -4,11 +4,7 @@ import {getDisplay, getTransText} from '../util/biz_util'
import classNames from 'classnames' import classNames from 'classnames'
const CompactSegmentItem = (props: { const CompactSegmentItem = (props: {
item: { item: TranscriptItem
from: number
to: number
content: string
}
idx: number idx: number
isIn: boolean isIn: boolean
last: boolean last: boolean
@@ -26,7 +22,7 @@ const CompactSegmentItem = (props: {
<span className={'pl-1 pr-0.5 py-0.5 cursor-pointer rounded-sm hover:bg-base-200'} onClick={moveCallback}> <span className={'pl-1 pr-0.5 py-0.5 cursor-pointer rounded-sm hover:bg-base-200'} onClick={moveCallback}>
<text className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</text> <text className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</text>
{display.sub && <text className='desc'>({display.sub})</text>}</span> {display.sub && <text className='desc'>({display.sub})</text>}</span>
<span>{!last && ', '}</span> <span>{!last && ' '}</span>
</div> </div>
} }

View File

@@ -265,8 +265,8 @@ const MoreBtn = (props: Props) => {
e.stopPropagation() e.stopPropagation()
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf') openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
}}> }}>
<img alt='youtube subtitle' src='/youtube-subtitle.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/> <img alt='youtube subtitle' src='/youtube-caption.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/>
Youtube Subtitle Youtube Caption Pro
</a> </a>
</li> </li>
<li className='hover:bg-accent'> <li className='hover:bg-accent'>

View File

@@ -5,11 +5,7 @@ import {getDisplay, getTransText} from '../util/biz_util'
import classNames from 'classnames' import classNames from 'classnames'
const NormalSegmentItem = (props: { const NormalSegmentItem = (props: {
item: { item: TranscriptItem
from: number
to: number
content: string
}
idx: number idx: number
isIn: boolean isIn: boolean
moveCallback: (event: any) => void moveCallback: (event: any) => void

View File

@@ -1,4 +1,4 @@
import React, {useCallback, useEffect, useRef} from 'react' import React, {useCallback, useEffect, useMemo, useRef} from 'react'
import {useAppDispatch, useAppSelector} from '../hooks/redux' import {useAppDispatch, useAppSelector} from '../hooks/redux'
import useSubtitle from '../hooks/useSubtitle' import useSubtitle from '../hooks/useSubtitle'
import {setCheckAutoScroll, setCurOffsetTop, setNeedScroll} from '../redux/envReducer' import {setCheckAutoScroll, setCurOffsetTop, setNeedScroll} from '../redux/envReducer'
@@ -7,21 +7,27 @@ import CompactSegmentItem from './CompactSegmentItem'
const SegmentItem = (props: { const SegmentItem = (props: {
bodyRef: any bodyRef: any
item: { item: TranscriptItem
from: number
to: number
content: string
}
idx: number idx: number
isIn: boolean isIn: boolean
needScroll?: boolean needScroll?: boolean
last: boolean last: boolean
}) => { }) => {
const dispatch = useAppDispatch()
const {bodyRef, item, idx, isIn, needScroll, last} = props const {bodyRef, item, idx, isIn, needScroll, last} = props
const dispatch = useAppDispatch()
const ref = useRef<any>() const ref = useRef<any>()
const {move} = useSubtitle() const {move} = useSubtitle()
const compact = useAppSelector(state => state.env.compact) const compact = useAppSelector(state => state.env.compact)
const searchText = useAppSelector(state => state.env.searchText)
const searchResult = useAppSelector(state => state.env.searchResult)
const display = useMemo(() => {
if (searchText) {
return searchResult.has(item.idx) ? 'inline' : 'none'
} else {
return 'inline'
}
}, [item.idx, searchResult, searchText])
const moveCallback = useCallback((event: any) => { const moveCallback = useCallback((event: any) => {
if (event.altKey) { // 复制 if (event.altKey) { // 复制
@@ -47,7 +53,9 @@ const SegmentItem = (props: {
} }
}, [dispatch, isIn]) }, [dispatch, isIn])
return <span ref={ref}> return <span ref={ref} style={{
display
}}>
{compact {compact
? <CompactSegmentItem ? <CompactSegmentItem
item={item} item={item}

View File

@@ -58,6 +58,8 @@ const Settings = () => {
// const {value: autoScrollValue, onChange: setAutoScrollValue} = useEventChecked(envData.autoScroll) // const {value: autoScrollValue, onChange: setAutoScrollValue} = useEventChecked(envData.autoScroll)
const {value: translateEnableValue, onChange: setTranslateEnableValue} = useEventChecked(envData.translateEnable) const {value: translateEnableValue, onChange: setTranslateEnableValue} = useEventChecked(envData.translateEnable)
const {value: summarizeEnableValue, onChange: setSummarizeEnableValue} = useEventChecked(envData.summarizeEnable) const {value: summarizeEnableValue, onChange: setSummarizeEnableValue} = useEventChecked(envData.summarizeEnable)
const {value: searchEnabledValue, onChange: setSearchEnabledValue} = useEventChecked(envData.searchEnabled)
const {value: cnSearchEnabledValue, onChange: setCnSearchEnabledValue} = useEventChecked(envData.cnSearchEnabled)
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)
@@ -112,10 +114,12 @@ const Settings = () => {
fetchAmount: fetchAmountValue, fetchAmount: fetchAmountValue,
fontSize: fontSizeValue, fontSize: fontSizeValue,
prompts: promptsValue, prompts: promptsValue,
searchEnabled: searchEnabledValue,
cnSearchEnabled: cnSearchEnabledValue,
})) }))
dispatch(setPage(PAGE_MAIN)) dispatch(setPage(PAGE_MAIN))
toast.success('保存成功') toast.success('保存成功')
}, [modelValue, promptsValue, fontSizeValue, apiKeyValue, autoExpandValue, dispatch, fetchAmountValue, hideOnDisableAutoTranslateValue, languageValue, serverUrlValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, themeValue, transDisplayValue, translateEnableValue, wordsValue]) }, [dispatch, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue])
const onCancel = useCallback(() => { const onCancel = useCallback(() => {
dispatch(setPage(PAGE_MAIN)) dispatch(setPage(PAGE_MAIN))
@@ -300,6 +304,18 @@ const Settings = () => {
</div> </div>
</FormItem> </FormItem>
</Section> </Section>
<Section title={<div className='flex items-center'>
</div>}>
<FormItem title='启用搜索' htmlFor='searchEnabled' tip='是否启用字幕搜索功能'>
<input id='searchEnabled' type='checkbox' className='toggle toggle-primary' checked={searchEnabledValue}
onChange={setSearchEnabledValue}/>
</FormItem>
<FormItem title='拼音搜索' htmlFor='cnSearchEnabled' tip='是否启用中文拼音搜索'>
<input id='cnSearchEnabled' type='checkbox' className='toggle toggle-primary' checked={cnSearchEnabledValue}
onChange={setCnSearchEnabledValue}/>
</FormItem>
</Section>
<div className='flex justify-center gap-5'> <div className='flex justify-center gap-5'>
<button className='btn btn-primary btn-sm' onClick={onSave}></button> <button className='btn btn-primary btn-sm' onClick={onSave}></button>
<button className='btn btn-sm' onClick={onCancel}></button> <button className='btn btn-sm' onClick={onCancel}></button>

View File

@@ -141,6 +141,7 @@ export const TOTAL_HEIGHT_DEF = 520
export const TOTAL_HEIGHT_MAX = 800 export const TOTAL_HEIGHT_MAX = 800
export const HEADER_HEIGHT = 44 export const HEADER_HEIGHT = 44
export const TITLE_HEIGHT = 24 export const TITLE_HEIGHT = 24
export const SEARCH_BAR_HEIGHT = 32
export const WORDS_DEFAULT = import.meta.env.VITE_ENV === 'web-dev'?500:2000 export const WORDS_DEFAULT = import.meta.env.VITE_ENV === 'web-dev'?500:2000
export const WORDS_MIN = 500 export const WORDS_MIN = 500
@@ -159,6 +160,9 @@ export const MODELS = [{
}, { }, {
code: 'gpt-3.5-turbo-16k', code: 'gpt-3.5-turbo-16k',
name: 'gpt-3.5-turbo-16k', name: 'gpt-3.5-turbo-16k',
}, {
code: 'gpt-3.5-turbo-1106',
name: 'gpt-3.5-turbo-1106',
}] }]
export const MODEL_DEFAULT = MODELS[0].code export const MODEL_DEFAULT = MODELS[0].code

View File

@@ -0,0 +1,58 @@
import {useAppDispatch, useAppSelector} from './redux'
import {useEffect, useMemo} from 'react'
import {setSearchResult, setSearchText, } from '../redux/envReducer'
import {Search} from '../util/search'
interface Document {
idx: number
s: string // searchKeys
}
const useSearchService = () => {
const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData)
const data = useAppSelector(state => state.env.data)
const searchText = useAppSelector(state => state.env.searchText)
const {reset, search} = useMemo(() => Search('idx', 's', 256, {
cnSearchEnabled: envData.cnSearchEnabled
}), [envData.cnSearchEnabled]) // 搜索实例
// reset search
useEffect(() => {
const startTime = Date.now()
const docs: Document[] = []
for (const item of data?.body??[]) {
docs.push({
idx: item.idx,
s: item.content,
})
}
reset(docs)
// 清空搜索文本
dispatch(setSearchText(''))
// 日志
const endTime = Date.now()
console.debug(`[Search]reset ${docs.length} docs, cost ${endTime-startTime}ms`)
}, [data?.body, dispatch, reset])
// search text
useEffect(() => {
const searchResult: Set<number> = new Set()
if (searchText) {
// @ts-expect-error
const documents: Document[] | undefined = search(searchText)
if (documents != null) {
for (const document of documents) {
searchResult.add(document.idx)
}
}
}
dispatch(setSearchResult(searchResult))
}, [dispatch, search, searchText])
}
export default useSearchService

View File

@@ -35,9 +35,12 @@ interface EnvState {
title?: string title?: string
taskIds?: string[] taskIds?: string[]
transResults: {[key: number]: TransResult} transResults: { [key: number]: TransResult }
lastTransTime?: number lastTransTime?: number
lastSummarizeTime?: number lastSummarizeTime?: number
searchText: string
searchResult: Set<number>
} }
const initialState: EnvState = { const initialState: EnvState = {
@@ -45,19 +48,24 @@ const initialState: EnvState = {
serverUrl: SERVER_URL_OPENAI, serverUrl: SERVER_URL_OPENAI,
translateEnable: true, translateEnable: true,
summarizeEnable: true, summarizeEnable: true,
autoExpand: true,
theme: 'light', theme: 'light',
searchEnabled: true,
}, },
tempData: { tempData: {
curSummaryType: 'overview', curSummaryType: 'overview',
}, },
totalHeight: TOTAL_HEIGHT_DEF, totalHeight: TOTAL_HEIGHT_DEF,
autoScroll: true, autoScroll: true,
currentTime: import.meta.env.VITE_ENV === 'web-dev'? 30: undefined, currentTime: import.meta.env.VITE_ENV === 'web-dev' ? 30 : undefined,
envReady: false, envReady: false,
tempReady: false, tempReady: false,
fold: true, fold: true,
data: import.meta.env.VITE_ENV === 'web-dev'? getDevData(): undefined, data: import.meta.env.VITE_ENV === 'web-dev' ? getDevData() : undefined,
transResults: {}, transResults: {},
searchText: '',
searchResult: new Set(),
} }
export const slice = createSlice({ export const slice = createSlice({
@@ -82,6 +90,12 @@ export const slice = createSlice({
setTempReady: (state) => { setTempReady: (state) => {
state.tempReady = true state.tempReady = true
}, },
setSearchText: (state, action: PayloadAction<string>) => {
state.searchText = action.payload
},
setSearchResult: (state, action: PayloadAction<Set<number>>) => {
state.searchResult = action.payload
},
setFloatKeyPointsSegIdx: (state, action: PayloadAction<number | undefined>) => { setFloatKeyPointsSegIdx: (state, action: PayloadAction<number | undefined>) => {
state.floatKeyPointsSegIdx = action.payload state.floatKeyPointsSegIdx = action.payload
}, },
@@ -107,12 +121,12 @@ export const slice = createSlice({
state.lastSummarizeTime = action.payload state.lastSummarizeTime = action.payload
}, },
addTaskId: (state, action: PayloadAction<string>) => { addTaskId: (state, action: PayloadAction<string>) => {
state.taskIds = [...(state.taskIds??[]), action.payload] state.taskIds = [...(state.taskIds ?? []), action.payload]
}, },
delTaskId: (state, action: PayloadAction<string>) => { delTaskId: (state, action: PayloadAction<string>) => {
state.taskIds = state.taskIds?.filter(id => id !== action.payload) state.taskIds = state.taskIds?.filter(id => id !== action.payload)
}, },
addTransResults: (state, action: PayloadAction<{[key: number]: TransResult}>) => { addTransResults: (state, action: PayloadAction<{ [key: number]: TransResult }>) => {
// 不要覆盖TransResult里code为200的 // 不要覆盖TransResult里code为200的
for (const payloadKey in action.payload) { for (const payloadKey in action.payload) {
const payloadItem = action.payload[payloadKey] const payloadItem = action.payload[payloadKey]
@@ -252,6 +266,46 @@ export const slice = createSlice({
}, },
}) })
export const { setTempReady, setTempData, setUploadedTranscript, setTotalHeight, setCheckAutoScroll, setCurOffsetTop, setFloatKeyPointsSegIdx, setFoldAll, setCompact, setSegmentFold, setSummaryContent, setSummaryStatus, setSummaryError, setTitle, setSegments, setLastSummarizeTime, setPage, setLastTransTime, clearTransResults, addTransResults, addTaskId, delTaskId, setTaskIds, setDownloadType, setAutoTranslate, setAutoScroll, setNoVideo, setNeedScroll, setCurIdx, setEnvData, setEnvReady, setCurrentTime, setInfos, setCurInfo, setCurFetched, setData, setFold } = slice.actions export const {
setTempReady,
setTempData,
setUploadedTranscript,
setTotalHeight,
setCheckAutoScroll,
setCurOffsetTop,
setFloatKeyPointsSegIdx,
setFoldAll,
setCompact,
setSegmentFold,
setSummaryContent,
setSummaryStatus,
setSummaryError,
setTitle,
setSegments,
setLastSummarizeTime,
setPage,
setLastTransTime,
clearTransResults,
addTransResults,
addTaskId,
delTaskId,
setTaskIds,
setDownloadType,
setAutoTranslate,
setAutoScroll,
setNoVideo,
setNeedScroll,
setCurIdx,
setEnvData,
setEnvReady,
setCurrentTime,
setInfos,
setCurInfo,
setCurFetched,
setData,
setFold,
setSearchText,
setSearchResult,
} = slice.actions
export default slice.reducer export default slice.reducer

4
src/typings.d.ts vendored
View File

@@ -16,6 +16,10 @@ interface EnvData {
theme?: 'system' | 'light' | 'dark' theme?: 'system' | 'light' | 'dark'
fontSize?: 'normal' | 'large' fontSize?: 'normal' | 'large'
// search
searchEnabled?: boolean
cnSearchEnabled?: boolean
prompts?: { prompts?: {
[key: string]: string [key: string]: string
} }

125
src/util/pinyin_util.ts Normal file
View File

@@ -0,0 +1,125 @@
import pinyin from 'tiny-pinyin'
import {uniq} from 'lodash-es'
/**
* pinyin的返回结果
*/
interface Ret {
type: 1 | 2 | 3
source: string
target: string
}
interface Phase {
pinyin: boolean
list: Ret[]
}
/**
* 获取Phase列表(中英文分离列表)
*/
export const getPhases = (str: string) => {
const rets = pinyin.parse(str)
const phases: Phase[] = []
let curPinyin_ = false
let curPhase_: Ret[] = []
const addCurrentPhase = () => {
if (curPhase_.length > 0) {
phases.push({
pinyin: curPinyin_,
list: curPhase_,
})
}
}
// 遍历rets
for (const ret of rets) {
const newPinyin = ret.type === 2
// 如果跟旧的pinyin类型不同先保存旧的
if (newPinyin !== curPinyin_) {
addCurrentPhase()
// 重置
curPinyin_ = newPinyin
curPhase_ = []
}
// 添加新的
curPhase_.push(ret)
}
// 最后一个
addCurrentPhase()
return phases
}
/**
* 获取原子字符列表,如 tool tab 汉 字
*/
export const getAtoms = (str: string) => {
const phases = getPhases(str)
const atoms = []
for (const phase of phases) {
if (phase.pinyin) { // all words
atoms.push(...phase.list.map(e => e.source).filter(e => e))
} else { // split
atoms.push(...(phase.list.map((e: any) => e.source).join('').match(/\w+/g)??[]).filter((e: string) => e))
}
}
return atoms
}
const fixStrs = (atoms: string[]) => {
// 小写
atoms = atoms.map(e => e.toLowerCase())
// 去重
atoms = uniq(atoms)
// 返回
return atoms
}
export const getWords = (str: string) => {
// 获取全部原子字符
const atoms = getAtoms(str)
// fix
return fixStrs(atoms)
}
/**
* 我的世界Minecraft => ['wodeshijie', 'deshijie', 'shijie', 'jie'] + ['wdsj', 'dsj', 'sj', 'j']
*
* 1. only handle pinyin, other is ignored
*/
export const getWordsPinyin = (str: string) => {
let result: string[] = []
for (const phase of getPhases(str)) {
// only handle pinyin
if (phase.pinyin) { // 我的世界
// 获取全部原子字符
// 我的世界 => [我, 的, 世, 界]
const atoms: string[] = []
atoms.push(...phase.list.map(e => e.source).filter(e => e))
// 获取全部子串
// [我, 的, 世, 界] => [我的世界, 的世界, 世界, 界]
const allSubStr = []
for (let i = 0; i < atoms.length; i++) {
allSubStr.push(atoms.slice(i).join(''))
}
// pinyin version
const pinyinList = allSubStr.map((e: string) => pinyin.convertToPinyin(e))
result.push(...pinyinList)
// pinyin first version
const pinyinFirstList = allSubStr.map((e: string) => pinyin.parse(e).map((e: any) => e.type === 2?e.target[0]:null).filter(e => !!e).join(''))
result.push(...pinyinFirstList)
}
}
// fix
result = fixStrs(result)
return result
}

65
src/util/search.ts Normal file
View File

@@ -0,0 +1,65 @@
import * as JsSearch from 'js-search'
import {uniq} from 'lodash-es'
import {getWords, getWordsPinyin} from './pinyin_util'
const tokenize = (maxLength: number, content: string, options?: SearchOptions) => {
const result: string[] = []
// 最大长度
if (content.length > maxLength) {
content = content.substring(0, maxLength)
}
result.push(...getWords(content))
// check cn
if (options?.cnSearchEnabled) {
result.push(...getWordsPinyin(content))
}
// console.debug('[Search] tokenize:', str, '=>', result)
return uniq(result)
}
export interface SearchOptions {
cnSearchEnabled?: boolean
}
export const Search = (uidFieldName: string, index: string, maxLength: number, options?: SearchOptions) => {
let searchRef: JsSearch.Search | undefined// 搜索器
/**
* 重置索引
*/
const reset = (documents?: Object[]) => {
// 搜索器
searchRef = new JsSearch.Search(uidFieldName)
searchRef.tokenizer = {
tokenize: (str) => {
return tokenize(maxLength, str, options)
}
}
searchRef.addIndex(index)
// 检测添加文档
if (documents != null) {
searchRef.addDocuments(documents)
}
}
/**
* 添加文档
*/
const add = (document: Object) => {
searchRef?.addDocument(document)
}
/**
* 搜索
* @return 未去重
*/
const search = (text: string) => {
return searchRef?.search(text.toLowerCase())
}
return {reset, add, search}
}

View File

@@ -18,11 +18,13 @@ module.exports = {
light: { light: {
...require("daisyui/src/colors/themes")["[data-theme=light]"], ...require("daisyui/src/colors/themes")["[data-theme=light]"],
"--rounded-btn": "0.15rem", "--rounded-btn": "0.15rem",
"primary": "rgb(0, 174, 236)",
}, },
}, { }, {
dark: { dark: {
...require("daisyui/src/colors/themes")["[data-theme=dark]"], ...require("daisyui/src/colors/themes")["[data-theme=dark]"],
"--rounded-btn": "0.15rem", "--rounded-btn": "0.15rem",
"primary": "rgb(0, 174, 236)",
} }
}], }],
base: true, base: true,