You've already forked bilibili-subtitle
Compare commits
19 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
728e4dce84 | ||
![]() |
a54b4a7e5f | ||
![]() |
8a908ecf99 | ||
![]() |
bdc7823965 | ||
![]() |
8d1bac4623 | ||
![]() |
9f486b7269 | ||
![]() |
e10de9bc48 | ||
![]() |
dd7ce4ab38 | ||
![]() |
250da4fd28 | ||
![]() |
65861829e2 | ||
![]() |
0b4890399a | ||
![]() |
51bf522eeb | ||
![]() |
a5808d8385 | ||
![]() |
e005c5e214 | ||
![]() |
e7e8758716 | ||
![]() |
49e311a9ed | ||
![]() |
a1462ae2f2 | ||
![]() |
2b0d294c2a | ||
![]() |
2825f9355a |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -25,3 +25,5 @@ dist-ssr
|
||||
*.sw?
|
||||
|
||||
stats.html
|
||||
dist.zip
|
||||
360/
|
||||
|
@@ -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
22
fixFirefox.cjs
Normal 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');
|
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "哔哩哔哩字幕列表",
|
||||
"description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!",
|
||||
"version": "1.7.3",
|
||||
"version": "1.7.8",
|
||||
"manifest_version": 3,
|
||||
"permissions": [
|
||||
"storage"
|
||||
|
@@ -1,15 +1,16 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "bilibili-subtitle",
|
||||
"version": "1.7.3",
|
||||
"version": "1.7.8",
|
||||
"type": "module",
|
||||
"description": "哔哩哔哩字幕列表",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build_chrome": "tsc && vite build -m production_chrome && pnpm run fixChrome",
|
||||
"fix": "eslint --fix --quiet .",
|
||||
"fixChrome": "node fixChrome.cjs"
|
||||
"build": "tsc && vite build -m production_chrome",
|
||||
"build_chrome": "pnpm run build && node fixChrome.cjs",
|
||||
"build_firefox": "pnpm run build && node fixFirefox.cjs",
|
||||
"fix": "eslint --fix --quiet ."
|
||||
},
|
||||
"author": "IndieKKY",
|
||||
"license": "MIT",
|
||||
|
10
pnpm-lock.yaml
generated
10
pnpm-lock.yaml
generated
@@ -1,5 +1,9 @@
|
||||
lockfileVersion: '6.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
dependencies:
|
||||
'@crxjs/vite-plugin':
|
||||
specifier: ^1.0.14
|
||||
@@ -2386,6 +2390,7 @@ packages:
|
||||
/iconv-lite@0.6.3:
|
||||
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
requiresBuild: true
|
||||
dependencies:
|
||||
safer-buffer: 2.1.2
|
||||
optional: true
|
||||
@@ -3392,6 +3397,7 @@ packages:
|
||||
/pify@4.0.1:
|
||||
resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==}
|
||||
engines: {node: '>=6'}
|
||||
requiresBuild: true
|
||||
optional: true
|
||||
|
||||
/postcss-import@14.1.0(postcss@8.4.19):
|
||||
@@ -3475,6 +3481,7 @@ packages:
|
||||
|
||||
/prr@1.0.1:
|
||||
resolution: {integrity: sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==}
|
||||
requiresBuild: true
|
||||
optional: true
|
||||
|
||||
/punycode@2.1.1:
|
||||
@@ -3802,10 +3809,12 @@ packages:
|
||||
|
||||
/safer-buffer@2.1.2:
|
||||
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
|
||||
requiresBuild: true
|
||||
optional: true
|
||||
|
||||
/sax@1.2.4:
|
||||
resolution: {integrity: sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==}
|
||||
requiresBuild: true
|
||||
optional: true
|
||||
|
||||
/scheduler@0.23.0:
|
||||
@@ -3822,6 +3831,7 @@ packages:
|
||||
/semver@5.7.1:
|
||||
resolution: {integrity: sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==}
|
||||
hasBin: true
|
||||
requiresBuild: true
|
||||
optional: true
|
||||
|
||||
/semver@6.3.0:
|
||||
|
BIN
public/youtube-caption.png
Normal file
BIN
public/youtube-caption.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 24 KiB |
1
push.sh
1
push.sh
@@ -25,6 +25,7 @@ echo "Version updated to: $new_version"
|
||||
# build
|
||||
pnpm run build_chrome
|
||||
# zip dist
|
||||
rm -f dist.zip
|
||||
cd dist
|
||||
zip -r ../dist.zip ./*
|
||||
cd ../
|
||||
|
@@ -15,6 +15,7 @@ import {handleJson} from '@kky002/kky-util'
|
||||
import {useLocalStorage} from '@kky002/kky-hooks'
|
||||
import {Toaster} from 'react-hot-toast'
|
||||
import {setTheme} from './util/biz_util'
|
||||
import useSearchService from './hooks/useSearchService'
|
||||
|
||||
function App() {
|
||||
const dispatch = useAppDispatch()
|
||||
@@ -72,6 +73,7 @@ function App() {
|
||||
// services
|
||||
useSubtitleService()
|
||||
useTranslateService()
|
||||
useSearchService()
|
||||
|
||||
return <div className={classNames('select-none', import.meta.env.VITE_ENV === 'web-dev'?'w-[350px]':'w-full')} style={{
|
||||
height: fold?undefined:`${totalHeight}px`,
|
||||
|
@@ -7,17 +7,34 @@ import {
|
||||
setFoldAll,
|
||||
setNeedScroll,
|
||||
setPage,
|
||||
setSearchText,
|
||||
setSegmentFold
|
||||
} from '../redux/envReducer'
|
||||
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 toast from 'react-hot-toast'
|
||||
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 useTranslate from '../hooks/useTranslate'
|
||||
import {getSummarize} from '../util/biz_util'
|
||||
import {openUrl} from '@kky002/kky-util'
|
||||
|
||||
const Body = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
@@ -40,6 +57,7 @@ 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 searchText = useAppSelector(state => state.env.searchText)
|
||||
|
||||
const normalCallback = useCallback(() => {
|
||||
dispatch(setCompact(false))
|
||||
@@ -117,6 +135,15 @@ const Body = () => {
|
||||
}
|
||||
}, [curSummaryType, segments, title])
|
||||
|
||||
const onSearchTextChange = useCallback((e: any) => {
|
||||
const searchText = e.target.value
|
||||
dispatch(setSearchText(searchText))
|
||||
}, [dispatch])
|
||||
|
||||
const onClearSearchText = useCallback(() => {
|
||||
dispatch(setSearchText(''))
|
||||
}, [dispatch])
|
||||
|
||||
// 自动滚动
|
||||
useEffect(() => {
|
||||
if (checkAutoScroll && curOffsetTop && autoScroll && !needScroll) {
|
||||
@@ -131,6 +158,7 @@ const Body = () => {
|
||||
}, [autoScroll, checkAutoScroll, curOffsetTop, dispatch, floatKeyPointsSegIdx, needScroll, totalHeight])
|
||||
|
||||
return <div className='relative'>
|
||||
{/* title */}
|
||||
<div className='absolute top-1 left-6 flex-center gap-1'>
|
||||
<AiOutlineAim className='cursor-pointer' onClick={posCallback} title='滚动到视频位置'/>
|
||||
{segments != null && segments.length > 0 &&
|
||||
@@ -158,24 +186,50 @@ const Body = () => {
|
||||
<IoWarning className='text-warning'/>
|
||||
</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
|
||||
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='开启自动滚动'
|
||||
onClick={onEnableAutoScroll}>
|
||||
<FaRegArrowAltCircleDown className={autoScroll ? 'text-accent' : ''}/>
|
||||
</div>}
|
||||
|
||||
{/* 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}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}/>)}
|
||||
|
||||
{/* 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>
|
||||
{(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='/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='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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
@@ -4,11 +4,7 @@ import {getDisplay, getTransText} from '../util/biz_util'
|
||||
import classNames from 'classnames'
|
||||
|
||||
const CompactSegmentItem = (props: {
|
||||
item: {
|
||||
from: number
|
||||
to: number
|
||||
content: string
|
||||
}
|
||||
item: TranscriptItem
|
||||
idx: number
|
||||
isIn: 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}>
|
||||
<text className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</text>
|
||||
{display.sub && <text className='desc'>({display.sub})</text>}</span>
|
||||
<span>{!last && ', '}</span>
|
||||
<span>{!last && ' '}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
|
@@ -259,6 +259,16 @@ 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://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 Pro
|
||||
</a>
|
||||
</li>
|
||||
<li className='hover:bg-accent'>
|
||||
<a className='flex items-center' onClick={(e) => {
|
||||
dispatch(setPage(PAGE_SETTINGS))
|
||||
|
@@ -5,11 +5,7 @@ import {getDisplay, getTransText} from '../util/biz_util'
|
||||
import classNames from 'classnames'
|
||||
|
||||
const NormalSegmentItem = (props: {
|
||||
item: {
|
||||
from: number
|
||||
to: number
|
||||
content: string
|
||||
}
|
||||
item: TranscriptItem
|
||||
idx: number
|
||||
isIn: boolean
|
||||
moveCallback: (event: any) => void
|
||||
|
@@ -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 useSubtitle from '../hooks/useSubtitle'
|
||||
import {setCheckAutoScroll, setCurOffsetTop, setNeedScroll} from '../redux/envReducer'
|
||||
@@ -7,21 +7,27 @@ import CompactSegmentItem from './CompactSegmentItem'
|
||||
|
||||
const SegmentItem = (props: {
|
||||
bodyRef: any
|
||||
item: {
|
||||
from: number
|
||||
to: number
|
||||
content: string
|
||||
}
|
||||
item: TranscriptItem
|
||||
idx: number
|
||||
isIn: boolean
|
||||
needScroll?: boolean
|
||||
last: boolean
|
||||
}) => {
|
||||
const dispatch = useAppDispatch()
|
||||
const {bodyRef, item, idx, isIn, needScroll, last} = props
|
||||
const dispatch = useAppDispatch()
|
||||
const ref = useRef<any>()
|
||||
const {move} = useSubtitle()
|
||||
|
||||
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) => {
|
||||
if (event.altKey) { // 复制
|
||||
@@ -47,7 +53,9 @@ const SegmentItem = (props: {
|
||||
}
|
||||
}, [dispatch, isIn])
|
||||
|
||||
return <span ref={ref}>
|
||||
return <span ref={ref} style={{
|
||||
display
|
||||
}}>
|
||||
{compact
|
||||
? <CompactSegmentItem
|
||||
item={item}
|
||||
|
@@ -58,6 +58,8 @@ const Settings = () => {
|
||||
// const {value: autoScrollValue, onChange: setAutoScrollValue} = useEventChecked(envData.autoScroll)
|
||||
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: cnSearchEnabledValue, onChange: setCnSearchEnabledValue} = useEventChecked(envData.cnSearchEnabled)
|
||||
const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat)
|
||||
const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''})
|
||||
const [serverUrlValue, setServerUrlValue] = useState(envData.serverUrl)
|
||||
@@ -112,10 +114,12 @@ const Settings = () => {
|
||||
fetchAmount: fetchAmountValue,
|
||||
fontSize: fontSizeValue,
|
||||
prompts: promptsValue,
|
||||
searchEnabled: searchEnabledValue,
|
||||
cnSearchEnabled: cnSearchEnabledValue,
|
||||
}))
|
||||
dispatch(setPage(PAGE_MAIN))
|
||||
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(() => {
|
||||
dispatch(setPage(PAGE_MAIN))
|
||||
@@ -300,6 +304,18 @@ const Settings = () => {
|
||||
</div>
|
||||
</FormItem>
|
||||
</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'>
|
||||
<button className='btn btn-primary btn-sm' onClick={onSave}>保存</button>
|
||||
<button className='btn btn-sm' onClick={onCancel}>取消</button>
|
||||
|
@@ -141,6 +141,7 @@ export const TOTAL_HEIGHT_DEF = 520
|
||||
export const TOTAL_HEIGHT_MAX = 800
|
||||
export const HEADER_HEIGHT = 44
|
||||
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_MIN = 500
|
||||
@@ -159,6 +160,9 @@ export const MODELS = [{
|
||||
}, {
|
||||
code: '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
|
||||
|
||||
|
58
src/hooks/useSearchService.ts
Normal file
58
src/hooks/useSearchService.ts
Normal 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
|
@@ -38,6 +38,9 @@ interface EnvState {
|
||||
transResults: { [key: number]: TransResult }
|
||||
lastTransTime?: number
|
||||
lastSummarizeTime?: number
|
||||
|
||||
searchText: string
|
||||
searchResult: Set<number>
|
||||
}
|
||||
|
||||
const initialState: EnvState = {
|
||||
@@ -45,7 +48,9 @@ const initialState: EnvState = {
|
||||
serverUrl: SERVER_URL_OPENAI,
|
||||
translateEnable: true,
|
||||
summarizeEnable: true,
|
||||
autoExpand: true,
|
||||
theme: 'light',
|
||||
searchEnabled: true,
|
||||
},
|
||||
tempData: {
|
||||
curSummaryType: 'overview',
|
||||
@@ -58,6 +63,9 @@ const initialState: EnvState = {
|
||||
fold: true,
|
||||
data: import.meta.env.VITE_ENV === 'web-dev' ? getDevData() : undefined,
|
||||
transResults: {},
|
||||
|
||||
searchText: '',
|
||||
searchResult: new Set(),
|
||||
}
|
||||
|
||||
export const slice = createSlice({
|
||||
@@ -82,6 +90,12 @@ export const slice = createSlice({
|
||||
setTempReady: (state) => {
|
||||
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>) => {
|
||||
state.floatKeyPointsSegIdx = action.payload
|
||||
},
|
||||
@@ -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
|
||||
|
4
src/typings.d.ts
vendored
4
src/typings.d.ts
vendored
@@ -16,6 +16,10 @@ interface EnvData {
|
||||
theme?: 'system' | 'light' | 'dark'
|
||||
fontSize?: 'normal' | 'large'
|
||||
|
||||
// search
|
||||
searchEnabled?: boolean
|
||||
cnSearchEnabled?: boolean
|
||||
|
||||
prompts?: {
|
||||
[key: string]: string
|
||||
}
|
||||
|
@@ -203,12 +203,13 @@ export const parseTranscript = (filename: string, text: string | ArrayBuffer): T
|
||||
if (filename.toLowerCase().endsWith('.srt')) {
|
||||
const lines = text.split('\n\n')
|
||||
for (const line of lines) {
|
||||
const lines = line.split('\n')
|
||||
if (lines.length >= 3) {
|
||||
const time = lines[1].split(' --> ')
|
||||
try {
|
||||
const linesInner = line.trim().split('\n')
|
||||
if (linesInner.length >= 3) {
|
||||
const time = linesInner[1].split(' --> ')
|
||||
const from = parseTime(time[0])
|
||||
const to = parseTime(time[1])
|
||||
const content = lines.slice(2).join('\n')
|
||||
const content = linesInner.slice(2).join('\n')
|
||||
items.push({
|
||||
from,
|
||||
to,
|
||||
@@ -216,6 +217,9 @@ export const parseTranscript = (filename: string, text: string | ArrayBuffer): T
|
||||
idx: items.length,
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('parse error', line)
|
||||
}
|
||||
}
|
||||
}
|
||||
// .vtt:
|
||||
|
125
src/util/pinyin_util.ts
Normal file
125
src/util/pinyin_util.ts
Normal 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
65
src/util/search.ts
Normal 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}
|
||||
}
|
@@ -18,11 +18,13 @@ module.exports = {
|
||||
light: {
|
||||
...require("daisyui/src/colors/themes")["[data-theme=light]"],
|
||||
"--rounded-btn": "0.15rem",
|
||||
"primary": "rgb(0, 174, 236)",
|
||||
},
|
||||
}, {
|
||||
dark: {
|
||||
...require("daisyui/src/colors/themes")["[data-theme=dark]"],
|
||||
"--rounded-btn": "0.15rem",
|
||||
"primary": "rgb(0, 174, 236)",
|
||||
}
|
||||
}],
|
||||
base: true,
|
||||
|
Reference in New Issue
Block a user