index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import type { FC, SVGProps } from 'react'
  2. import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  3. import useSWR from 'swr'
  4. import { useRouter } from 'next/navigation'
  5. import { useContext } from 'use-context-selector'
  6. import { useTranslation } from 'react-i18next'
  7. import { omit } from 'lodash-es'
  8. import { ArrowRightIcon } from '@heroicons/react/24/solid'
  9. import SegmentCard from '../completed/SegmentCard'
  10. import { FieldInfo } from '../metadata'
  11. import style from '../completed/style.module.css'
  12. import { DocumentContext } from '../index'
  13. import s from './style.module.css'
  14. import cn from '@/utils/classnames'
  15. import Button from '@/app/components/base/button'
  16. import Divider from '@/app/components/base/divider'
  17. import { ToastContext } from '@/app/components/base/toast'
  18. import type { FullDocumentDetail, ProcessRuleResponse } from '@/models/datasets'
  19. import type { CommonResponse } from '@/models/common'
  20. import { asyncRunSafe, sleep } from '@/utils'
  21. import { fetchIndexingStatus as doFetchIndexingStatus, fetchProcessRule, pauseDocIndexing, resumeDocIndexing } from '@/service/datasets'
  22. import StopEmbeddingModal from '@/app/components/datasets/create/stop-embedding-modal'
  23. type Props = {
  24. detail?: FullDocumentDetail
  25. stopPosition?: 'top' | 'bottom'
  26. datasetId?: string
  27. documentId?: string
  28. indexingType?: string
  29. detailUpdate: VoidFunction
  30. }
  31. const StopIcon = ({ className }: SVGProps<SVGElement>) => {
  32. return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
  33. <g clipPath="url(#clip0_2328_2798)">
  34. <path d="M1.5 3.9C1.5 3.05992 1.5 2.63988 1.66349 2.31901C1.8073 2.03677 2.03677 1.8073 2.31901 1.66349C2.63988 1.5 3.05992 1.5 3.9 1.5H8.1C8.94008 1.5 9.36012 1.5 9.68099 1.66349C9.96323 1.8073 10.1927 2.03677 10.3365 2.31901C10.5 2.63988 10.5 3.05992 10.5 3.9V8.1C10.5 8.94008 10.5 9.36012 10.3365 9.68099C10.1927 9.96323 9.96323 10.1927 9.68099 10.3365C9.36012 10.5 8.94008 10.5 8.1 10.5H3.9C3.05992 10.5 2.63988 10.5 2.31901 10.3365C2.03677 10.1927 1.8073 9.96323 1.66349 9.68099C1.5 9.36012 1.5 8.94008 1.5 8.1V3.9Z" stroke="#344054" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  35. </g>
  36. <defs>
  37. <clipPath id="clip0_2328_2798">
  38. <rect width="12" height="12" fill="white" />
  39. </clipPath>
  40. </defs>
  41. </svg>
  42. }
  43. const ResumeIcon = ({ className }: SVGProps<SVGElement>) => {
  44. return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
  45. <path d="M10 3.5H5C3.34315 3.5 2 4.84315 2 6.5C2 8.15685 3.34315 9.5 5 9.5H10M10 3.5L8 1.5M10 3.5L8 5.5" stroke="#344054" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  46. </svg>
  47. }
  48. const RuleDetail: FC<{ sourceData?: ProcessRuleResponse; docName?: string }> = ({ sourceData, docName }) => {
  49. const { t } = useTranslation()
  50. const segmentationRuleMap = {
  51. docName: t('datasetDocuments.embedding.docName'),
  52. mode: t('datasetDocuments.embedding.mode'),
  53. segmentLength: t('datasetDocuments.embedding.segmentLength'),
  54. textCleaning: t('datasetDocuments.embedding.textCleaning'),
  55. }
  56. const getRuleName = (key: string) => {
  57. if (key === 'remove_extra_spaces')
  58. return t('datasetCreation.stepTwo.removeExtraSpaces')
  59. if (key === 'remove_urls_emails')
  60. return t('datasetCreation.stepTwo.removeUrlEmails')
  61. if (key === 'remove_stopwords')
  62. return t('datasetCreation.stepTwo.removeStopwords')
  63. }
  64. const getValue = useCallback((field: string) => {
  65. let value: string | number | undefined = '-'
  66. switch (field) {
  67. case 'docName':
  68. value = docName
  69. break
  70. case 'mode':
  71. value = sourceData?.mode === 'automatic' ? (t('datasetDocuments.embedding.automatic') as string) : (t('datasetDocuments.embedding.custom') as string)
  72. break
  73. case 'segmentLength':
  74. value = sourceData?.rules?.segmentation?.max_tokens
  75. break
  76. default:
  77. value = sourceData?.mode === 'automatic'
  78. ? (t('datasetDocuments.embedding.automatic') as string)
  79. // eslint-disable-next-line array-callback-return
  80. : sourceData?.rules?.pre_processing_rules?.map((rule) => {
  81. if (rule.enabled)
  82. return getRuleName(rule.id)
  83. }).filter(Boolean).join(';')
  84. break
  85. }
  86. return value
  87. }, [sourceData, docName])
  88. return <div className='flex flex-col pt-8 pb-10 first:mt-0'>
  89. {Object.keys(segmentationRuleMap).map((field) => {
  90. return <FieldInfo
  91. key={field}
  92. label={segmentationRuleMap[field as keyof typeof segmentationRuleMap]}
  93. displayedValue={String(getValue(field))}
  94. />
  95. })}
  96. </div>
  97. }
  98. const EmbeddingDetail: FC<Props> = ({ detail, stopPosition = 'top', datasetId: dstId, documentId: docId, detailUpdate }) => {
  99. const onTop = stopPosition === 'top'
  100. const { t } = useTranslation()
  101. const { notify } = useContext(ToastContext)
  102. const { datasetId = '', documentId = '' } = useContext(DocumentContext)
  103. const localDatasetId = dstId ?? datasetId
  104. const localDocumentId = docId ?? documentId
  105. const [indexingStatusDetail, setIndexingStatusDetail] = useState<any>(null)
  106. const fetchIndexingStatus = async () => {
  107. const status = await doFetchIndexingStatus({ datasetId: localDatasetId, documentId: localDocumentId })
  108. setIndexingStatusDetail(status)
  109. return status
  110. }
  111. const isStopQuery = useRef(false)
  112. const stopQueryStatus = useCallback(() => {
  113. isStopQuery.current = true
  114. }, [])
  115. const startQueryStatus = useCallback(async () => {
  116. if (isStopQuery.current)
  117. return
  118. try {
  119. const indexingStatusDetail = await fetchIndexingStatus()
  120. if (['completed', 'error', 'paused'].includes(indexingStatusDetail?.indexing_status)) {
  121. stopQueryStatus()
  122. detailUpdate()
  123. return
  124. }
  125. await sleep(2500)
  126. await startQueryStatus()
  127. }
  128. catch (e) {
  129. await sleep(2500)
  130. await startQueryStatus()
  131. }
  132. }, [stopQueryStatus])
  133. useEffect(() => {
  134. isStopQuery.current = false
  135. startQueryStatus()
  136. return () => {
  137. stopQueryStatus()
  138. }
  139. }, [startQueryStatus, stopQueryStatus])
  140. const { data: ruleDetail, error: ruleError } = useSWR({
  141. action: 'fetchProcessRule',
  142. params: { documentId: localDocumentId },
  143. }, apiParams => fetchProcessRule(omit(apiParams, 'action')), {
  144. revalidateOnFocus: false,
  145. })
  146. const [showModal, setShowModal] = useState(false)
  147. const modalShowHandle = () => setShowModal(true)
  148. const modalCloseHandle = () => setShowModal(false)
  149. const router = useRouter()
  150. const navToDocument = () => {
  151. router.push(`/datasets/${localDatasetId}/documents/${localDocumentId}`)
  152. }
  153. const isEmbedding = useMemo(() => ['indexing', 'splitting', 'parsing', 'cleaning'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
  154. const isEmbeddingCompleted = useMemo(() => ['completed'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
  155. const isEmbeddingPaused = useMemo(() => ['paused'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
  156. const isEmbeddingError = useMemo(() => ['error'].includes(indexingStatusDetail?.indexing_status || ''), [indexingStatusDetail])
  157. const percent = useMemo(() => {
  158. const completedCount = indexingStatusDetail?.completed_segments || 0
  159. const totalCount = indexingStatusDetail?.total_segments || 0
  160. if (totalCount === 0)
  161. return 0
  162. const percent = Math.round(completedCount * 100 / totalCount)
  163. return percent > 100 ? 100 : percent
  164. }, [indexingStatusDetail])
  165. const handleSwitch = async () => {
  166. const opApi = isEmbedding ? pauseDocIndexing : resumeDocIndexing
  167. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId: localDatasetId, documentId: localDocumentId }) as Promise<CommonResponse>)
  168. if (!e) {
  169. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  170. setIndexingStatusDetail(null)
  171. }
  172. else {
  173. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  174. }
  175. }
  176. // if (!ruleDetail && !error)
  177. // return <Loading type='app' />
  178. return (
  179. <>
  180. <div className={s.embeddingStatus}>
  181. {isEmbedding && t('datasetDocuments.embedding.processing')}
  182. {isEmbeddingCompleted && t('datasetDocuments.embedding.completed')}
  183. {isEmbeddingPaused && t('datasetDocuments.embedding.paused')}
  184. {isEmbeddingError && t('datasetDocuments.embedding.error')}
  185. {onTop && isEmbedding && (
  186. <Button onClick={handleSwitch} className={s.opBtn}>
  187. <StopIcon className={s.opIcon} />
  188. {t('datasetDocuments.embedding.stop')}
  189. </Button>
  190. )}
  191. {onTop && isEmbeddingPaused && (
  192. <Button onClick={handleSwitch} className={s.opBtn}>
  193. <ResumeIcon className={s.opIcon} />
  194. {t('datasetDocuments.embedding.resume')}
  195. </Button>
  196. )}
  197. </div>
  198. {/* progress bar */}
  199. <div className={s.progressContainer}>
  200. {new Array(10).fill('').map((_, idx) => <div
  201. key={idx}
  202. className={cn(s.progressBgItem, isEmbedding ? 'bg-primary-50' : 'bg-gray-100')}
  203. />)}
  204. <div
  205. className={cn(
  206. 'rounded-l-md',
  207. s.progressBar,
  208. (isEmbedding || isEmbeddingCompleted) && s.barProcessing,
  209. (isEmbeddingPaused || isEmbeddingError) && s.barPaused,
  210. indexingStatusDetail?.indexing_status === 'completed' && 'rounded-r-md',
  211. )}
  212. style={{ width: `${percent}%` }}
  213. />
  214. </div>
  215. <div className={s.progressData}>
  216. <div>{t('datasetDocuments.embedding.segments')} {indexingStatusDetail?.completed_segments}/{indexingStatusDetail?.total_segments} · {percent}%</div>
  217. </div>
  218. <RuleDetail sourceData={ruleDetail} docName={detail?.name} />
  219. {!onTop && (
  220. <div className='flex items-center gap-2 mt-10'>
  221. {isEmbedding && (
  222. <Button onClick={modalShowHandle} className='w-fit'>
  223. {t('datasetCreation.stepThree.stop')}
  224. </Button>
  225. )}
  226. {isEmbeddingPaused && (
  227. <Button onClick={handleSwitch} className='w-fit'>
  228. {t('datasetCreation.stepThree.resume')}
  229. </Button>
  230. )}
  231. <Button className='w-fit' variant='primary' onClick={navToDocument}>
  232. <span>{t('datasetCreation.stepThree.navTo')}</span>
  233. <ArrowRightIcon className='h-4 w-4 ml-2 stroke-current stroke-1' />
  234. </Button>
  235. </div>
  236. )}
  237. {onTop && <>
  238. <Divider />
  239. <div className={s.previewTip}>{t('datasetDocuments.embedding.previewTip')}</div>
  240. <div className={style.cardWrapper}>
  241. {[1, 2, 3].map((v, index) => (
  242. <SegmentCard key={index} loading={true} detail={{ position: v } as any} />
  243. ))}
  244. </div>
  245. </>}
  246. <StopEmbeddingModal show={showModal} onConfirm={handleSwitch} onHide={modalCloseHandle} />
  247. </>
  248. )
  249. }
  250. export default React.memo(EmbeddingDetail)