提问优化

This commit is contained in:
IndieKKY
2024-05-27 10:12:55 +08:00
parent 64059f71e5
commit 4a6ebf0894
5 changed files with 148 additions and 99 deletions

72
src/biz/Ask.tsx Normal file
View File

@@ -0,0 +1,72 @@
import {AiOutlineCloseCircle, BsDashSquare, BsPlusSquare, FaQuestion} from 'react-icons/all'
import classNames from 'classnames'
import Markdown from '../components/Markdown'
import React, {useCallback} from 'react'
import {delAskInfo, mergeAskInfo, setPage} from '../redux/envReducer'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {PAGE_SETTINGS} from '../const'
import toast from 'react-hot-toast'
import useTranslate from '../hooks/useTranslate'
const Ask = (props: {
ask: AskInfo
}) => {
const {ask} = props
const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData)
const fontSize = useAppSelector(state => state.env.envData.fontSize)
const segments = useAppSelector(state => state.env.segments)
const {addAskTask} = useTranslate()
const onRegenerate = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (apiKey) {
if (segments != null && segments.length > 0) {
addAskTask(ask.id, segments[0], ask.question).catch(console.error)
}
} else {
dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!')
}
}, [addAskTask, ask.id, ask.question, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
const onAskFold = useCallback(() => {
dispatch(mergeAskInfo({
id: ask.id,
fold: !ask.fold
}))
}, [ask, dispatch])
const onClose = useCallback(() => {
dispatch(delAskInfo(ask.id))
}, [ask, dispatch])
return <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'>
{ask.fold
? <BsPlusSquare className='cursor-pointer' onClick={onAskFold}/> :
<BsDashSquare className='cursor-pointer' onClick={onAskFold}/>}
</div>
<button className='absolute right-0 top-0 bottom-0 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClose}>
<AiOutlineCloseCircle/>
</button>
<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>
{!ask.fold && ask.question && <div className='text-sm font-medium max-w-[90%]'>{ask.question}</div>}
{!ask.fold && ask.content &&
<div className={classNames('font-medium max-w-[90%] mt-1', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
<Markdown content={ask.content}/>
</div>}
{!ask.fold && <button disabled={ask.status !== 'done'}
className={classNames('btn btn-link btn-xs', ask.status === 'pending' && 'loading')}
onClick={onRegenerate}>{ask.status === 'pending' ? '生成中' : '重新生成'}</button>}
{!ask.fold && ask.error && <div className='text-xs text-error'>{ask.error}</div>}
</div>
}
export default Ask

View File

@@ -1,7 +1,7 @@
import React, {useCallback, useEffect, useMemo, useRef} from 'react' import React, {useCallback, useEffect, useMemo, useRef} from 'react'
import { import {
setAskFold, addAskInfo,
setAskQuestion, mergeAskInfo,
setAutoScroll, setAutoScroll,
setAutoTranslate, setAutoTranslate,
setCheckAutoScroll, setCheckAutoScroll,
@@ -16,9 +16,6 @@ import {useAppDispatch, useAppSelector} from '../hooks/redux'
import { import {
AiOutlineAim, AiOutlineAim,
AiOutlineCloseCircle, AiOutlineCloseCircle,
BsDashSquare,
BsPlusSquare,
FaQuestion,
FaRegArrowAltCircleDown, FaRegArrowAltCircleDown,
IoWarning, IoWarning,
MdExpand, MdExpand,
@@ -37,10 +34,10 @@ import {
} from '../const' } 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 {openUrl} from '@kky002/kky-util' import {openUrl} from '@kky002/kky-util'
import Markdown from '../components/Markdown'
import useKeyService from '../hooks/useKeyService' import useKeyService from '../hooks/useKeyService'
import Ask from './Ask'
import {v4} from 'uuid'
const Body = () => { const Body = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
@@ -57,20 +54,16 @@ const Body = () => {
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable) const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
const {addSummarizeTask, addAskTask} = useTranslate() const {addSummarizeTask, addAskTask} = useTranslate()
// const infos = useAppSelector(state => state.env.infos) // 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 bodyRef = useRef<any>()
const curOffsetTop = useAppSelector(state => state.env.curOffsetTop) const curOffsetTop = useAppSelector(state => state.env.curOffsetTop)
const checkAutoScroll = useAppSelector(state => state.env.checkAutoScroll) const checkAutoScroll = useAppSelector(state => state.env.checkAutoScroll)
const needScroll = useAppSelector(state => state.env.needScroll) const needScroll = useAppSelector(state => state.env.needScroll)
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 fontSize = useAppSelector(state => state.env.envData.fontSize) // const fontSize = useAppSelector(state => state.env.envData.fontSize)
const searchText = useAppSelector(state => state.env.searchText) const searchText = useAppSelector(state => state.env.searchText)
const asks = useAppSelector(state => state.env.asks)
// const recommendIdx = useMemo(() => random(0, 3), []) // const recommendIdx = useMemo(() => random(0, 3), [])
const showSearchInput = useMemo(() => { const showSearchInput = useMemo(() => {
return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT)) return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT))
@@ -135,14 +128,19 @@ const Body = () => {
const onFoldAll = useCallback(() => { const onFoldAll = useCallback(() => {
dispatch(setFoldAll(!foldAll)) dispatch(setFoldAll(!foldAll))
dispatch(setAskFold(!foldAll)) for (const ask of asks) {
dispatch(mergeAskInfo({
id: ask.id,
fold: !foldAll
}))
}
for (const segment of segments ?? []) { for (const segment of segments ?? []) {
dispatch(setSegmentFold({ dispatch(setSegmentFold({
segmentStartIdx: segment.startIdx, segmentStartIdx: segment.startIdx,
fold: !foldAll fold: !foldAll
})) }))
} }
}, [dispatch, foldAll, segments]) }, [asks, dispatch, foldAll, segments])
const toggleAutoTranslateCallback = useCallback(() => { const toggleAutoTranslateCallback = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
@@ -165,14 +163,14 @@ const Body = () => {
} }
}, [autoScroll, dispatch]) }, [autoScroll, dispatch])
const onCopy = useCallback(() => { // const onCopy = useCallback(() => {
const [success, content] = getSummarize(title, segments, curSummaryType) // const [success, content] = getSummarize(title, segments, curSummaryType)
if (success) { // if (success) {
navigator.clipboard.writeText(content).then(() => { // navigator.clipboard.writeText(content).then(() => {
toast.success('复制成功') // toast.success('复制成功')
}).catch(console.error) // }).catch(console.error)
} // }
}, [curSummaryType, segments, title]) // }, [curSummaryType, segments, title])
const onSearchTextChange = useCallback((e: any) => { const onSearchTextChange = useCallback((e: any) => {
const searchText = e.target.value const searchText = e.target.value
@@ -188,8 +186,14 @@ const Body = () => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (apiKey) { if (apiKey) {
if (segments != null && segments.length > 0) { if (segments != null && segments.length > 0) {
dispatch(setAskQuestion(searchText)) const id = v4()
addAskTask(segments[0], searchText).catch(console.error) addAskTask(id, segments[0], searchText).catch(console.error)
// 添加ask
dispatch(addAskInfo({
id,
question: searchText,
status: 'pending',
}))
} }
} else { } else {
dispatch(setPage(PAGE_SETTINGS)) dispatch(setPage(PAGE_SETTINGS))
@@ -198,14 +202,6 @@ const Body = () => {
} }
}, [addAskTask, dispatch, envData.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, searchText, segments]) }, [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 // service
useKeyService() useKeyService()
@@ -282,33 +278,8 @@ const Body = () => {
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - (showSearchInput ? SEARCH_BAR_HEIGHT : 0)}px` height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - (showSearchInput ? SEARCH_BAR_HEIGHT : 0)}px`
}} }}
> >
{/* ask */} {/* asks */}
{(envData.askEnabled ?? ASK_ENABLED_DEFAULT) && (searchText || askQuestion) && {asks.map(ask => <Ask key={ask.id} ask={ask}/>)}
<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 */}
{segments?.map((segment, segmentIdx) => <SegmentCard key={segment.startIdx} segment={segment} {segments?.map((segment, segmentIdx) => <SegmentCard key={segment.startIdx} segment={segment}

View File

@@ -4,9 +4,7 @@ import {
addTaskId, addTaskId,
addTransResults, addTransResults,
delTaskId, delTaskId,
setAskContent, mergeAskInfo,
setAskError,
setAskStatus,
setLastSummarizeTime, setLastSummarizeTime,
setLastTransTime, setLastTransTime,
setSummaryContent, setSummaryContent,
@@ -199,7 +197,7 @@ const useTranslate = () => {
} }
}, [dispatch, envData, summarizeLanguage.name, title]) }, [dispatch, envData, summarizeLanguage.name, title])
const addAskTask = useCallback(async (segment: Segment, question: string) => { const addAskTask = useCallback(async (id: string, segment: Segment, question: string) => {
if (segment.text.length >= SUMMARIZE_THRESHOLD) { if (segment.text.length >= SUMMARIZE_THRESHOLD) {
let prompt: string = envData.prompts?.[PROMPT_TYPE_ASK]??PROMPT_DEFAULTS[PROMPT_TYPE_ASK] let prompt: string = envData.prompts?.[PROMPT_TYPE_ASK]??PROMPT_DEFAULTS[PROMPT_TYPE_ASK]
// replace params // replace params
@@ -243,10 +241,14 @@ const useTranslate = () => {
// startIdx: segment.startIdx, // startIdx: segment.startIdx,
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey, geminiApiKey: envData.geminiApiKey,
askId: id,
} }
} }
console.debug('addAskTask', taskDef) console.debug('addAskTask', taskDef)
dispatch(setAskStatus({status: 'pending'})) dispatch(mergeAskInfo({
id,
status: 'pending'
}))
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef}) const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
dispatch(addTaskId(task.id)) dispatch(addTaskId(task.id))
} }
@@ -304,9 +306,13 @@ const useTranslate = () => {
}) })
const handleAsk = useMemoizedFn((task: Task, content?: string) => { const handleAsk = useMemoizedFn((task: Task, content?: string) => {
dispatch(setAskContent({content})) dispatch(mergeAskInfo({
dispatch(setAskStatus({status: 'done'})) id: task.def.extra.askId,
dispatch(setAskError({error: task.error})) content,
status: 'done',
error: task.error,
}))
console.debug('setAsk', content, task.error) console.debug('setAsk', content, task.error)
}) })

View File

@@ -1,5 +1,5 @@
import {createSlice, PayloadAction} from '@reduxjs/toolkit' import {createSlice, PayloadAction} from '@reduxjs/toolkit'
import {find} from 'lodash-es' import {find, findIndex} from 'lodash-es'
import {getDevData} from '../util/biz_util' import {getDevData} from '../util/biz_util'
import {DEFAULT_SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../const' import {DEFAULT_SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../const'
@@ -39,11 +39,7 @@ interface EnvState {
lastSummarizeTime?: number lastSummarizeTime?: number
// ask // ask
askFold?: boolean asks: AskInfo[]
askQuestion?: string
askStatus: SummaryStatus
askError?: string
askContent?: string
/** /**
* 是否输入中(中文) * 是否输入中(中文)
@@ -66,7 +62,6 @@ const initialState: EnvState = {
tempData: { tempData: {
curSummaryType: 'overview', curSummaryType: 'overview',
}, },
askStatus: 'init',
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,
@@ -80,6 +75,8 @@ const initialState: EnvState = {
searchText: '', searchText: '',
searchResult: new Set(), searchResult: new Set(),
asks: [],
} }
export const slice = createSlice({ export const slice = createSlice({
@@ -211,26 +208,20 @@ export const slice = createSlice({
} }
} }
}, },
setAskFold: (state, action: PayloadAction<boolean>) => { addAskInfo: (state, action: PayloadAction<AskInfo>) => {
state.askFold = action.payload state.asks.push(action.payload)
}, },
setAskQuestion: (state, action: PayloadAction<string | undefined>) => { delAskInfo: (state, action: PayloadAction<string>) => {
state.askQuestion = action.payload state.asks = state.asks.filter(ask => ask.id !== action.payload)
}, },
setAskContent: (state, action: PayloadAction<{ mergeAskInfo: (state, action: PayloadAction<PartialOfAskInfo>) => {
content?: any const idx = findIndex(state.asks, {id: action.payload.id})
}>) => { if (idx >= 0) {
state.askContent = action.payload.content state.asks[idx] = {
}, ...state.asks[idx],
setAskStatus: (state, action: PayloadAction<{ ...action.payload,
status: SummaryStatus }
}>) => { }
state.askStatus = action.payload.status
},
setAskError: (state, action: PayloadAction<{
error?: string
}>) => {
state.askError = action.payload.error
}, },
setSegmentFold: (state, action: PayloadAction<{ setSegmentFold: (state, action: PayloadAction<{
segmentStartIdx: number segmentStartIdx: number
@@ -303,11 +294,6 @@ export const slice = createSlice({
export const { export const {
setUrl, setUrl,
setAskFold,
setAskQuestion,
setAskStatus,
setAskError,
setAskContent,
setTempReady, setTempReady,
setTempData, setTempData,
setUploadedTranscript, setUploadedTranscript,
@@ -346,6 +332,9 @@ export const {
setSearchText, setSearchText,
setSearchResult, setSearchResult,
setInputting, setInputting,
addAskInfo,
delAskInfo,
mergeAskInfo,
} = slice.actions } = slice.actions
export default slice.reducer export default slice.reducer

11
src/typings.d.ts vendored
View File

@@ -105,6 +105,17 @@ interface Summary {
content?: any content?: any
} }
interface AskInfo {
id: string
fold?: boolean
question: string
status: SummaryStatus
error?: string
content?: string
}
type PartialOfAskInfo = Partial<PartOfAskInfo>
/** /**
* 概览 * 概览
*/ */