You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.tsx 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import React, { useEffect, useMemo, useRef, useState } from 'react'
  2. import useSWR from 'swr'
  3. import { useRouter } from 'next/navigation'
  4. import { useTranslation } from 'react-i18next'
  5. import { omit } from 'lodash-es'
  6. import { ArrowRightIcon } from '@heroicons/react/24/solid'
  7. import {
  8. RiCheckboxCircleFill,
  9. RiErrorWarningFill,
  10. RiLoader2Fill,
  11. RiTerminalBoxLine,
  12. } from '@remixicon/react'
  13. import cn from '@/utils/classnames'
  14. import Button from '@/app/components/base/button'
  15. import type { IndexingStatusResponse } from '@/models/datasets'
  16. import { fetchIndexingStatusBatch as doFetchIndexingStatus, fetchProcessRule } from '@/service/datasets'
  17. import NotionIcon from '@/app/components/base/notion-icon'
  18. import PriorityLabel from '@/app/components/billing/priority-label'
  19. import { Plan } from '@/app/components/billing/type'
  20. import { ZapFast } from '@/app/components/base/icons/src/vender/solid/general'
  21. import UpgradeBtn from '@/app/components/billing/upgrade-btn'
  22. import { useProviderContext } from '@/context/provider-context'
  23. import { sleep } from '@/utils'
  24. import Tooltip from '@/app/components/base/tooltip'
  25. import { useInvalidDocumentList } from '@/service/knowledge/use-document'
  26. import DocumentFileIcon from '@/app/components/datasets/common/document-file-icon'
  27. import RuleDetail from './rule-detail'
  28. import type { IndexingType } from '@/app/components/datasets/create/step-two'
  29. import type { RETRIEVE_METHOD } from '@/types/app'
  30. import { DatasourceType, type InitialDocumentDetail } from '@/models/pipeline'
  31. type EmbeddingProcessProps = {
  32. datasetId: string
  33. batchId: string
  34. documents?: InitialDocumentDetail[]
  35. indexingType?: IndexingType
  36. retrievalMethod?: RETRIEVE_METHOD
  37. }
  38. const EmbeddingProcess = ({
  39. datasetId,
  40. batchId,
  41. documents = [],
  42. indexingType,
  43. retrievalMethod,
  44. }: EmbeddingProcessProps) => {
  45. const { t } = useTranslation()
  46. const { enableBilling, plan } = useProviderContext()
  47. const firstDocument = documents[0]
  48. const [indexingStatusBatchDetail, setIndexingStatusDetail] = useState<IndexingStatusResponse[]>([])
  49. const fetchIndexingStatus = async () => {
  50. const status = await doFetchIndexingStatus({ datasetId, batchId })
  51. setIndexingStatusDetail(status.data)
  52. return status.data
  53. }
  54. const [isStopQuery, setIsStopQuery] = useState(false)
  55. const isStopQueryRef = useRef(isStopQuery)
  56. useEffect(() => {
  57. isStopQueryRef.current = isStopQuery
  58. }, [isStopQuery])
  59. const stopQueryStatus = () => {
  60. setIsStopQuery(true)
  61. }
  62. const startQueryStatus = async () => {
  63. if (isStopQueryRef.current)
  64. return
  65. try {
  66. const indexingStatusBatchDetail = await fetchIndexingStatus()
  67. const isCompleted = indexingStatusBatchDetail.every(indexingStatusDetail => ['completed', 'error', 'paused'].includes(indexingStatusDetail.indexing_status))
  68. if (isCompleted) {
  69. stopQueryStatus()
  70. return
  71. }
  72. await sleep(2500)
  73. await startQueryStatus()
  74. }
  75. catch {
  76. await sleep(2500)
  77. await startQueryStatus()
  78. }
  79. }
  80. useEffect(() => {
  81. setIsStopQuery(false)
  82. startQueryStatus()
  83. return () => {
  84. stopQueryStatus()
  85. }
  86. // eslint-disable-next-line react-hooks/exhaustive-deps
  87. }, [])
  88. // get rule
  89. const { data: ruleDetail } = useSWR({
  90. action: 'fetchProcessRule',
  91. params: { documentId: firstDocument.id },
  92. }, apiParams => fetchProcessRule(omit(apiParams, 'action')), {
  93. revalidateOnFocus: false,
  94. })
  95. const router = useRouter()
  96. const invalidDocumentList = useInvalidDocumentList()
  97. const navToDocumentList = () => {
  98. invalidDocumentList()
  99. router.push(`/datasets/${datasetId}/documents`)
  100. }
  101. const navToApiDocs = () => {
  102. router.push('/datasets?category=api')
  103. }
  104. const isEmbedding = useMemo(() => {
  105. return indexingStatusBatchDetail.some(indexingStatusDetail => ['indexing', 'splitting', 'parsing', 'cleaning'].includes(indexingStatusDetail?.indexing_status || ''))
  106. }, [indexingStatusBatchDetail])
  107. const isEmbeddingCompleted = useMemo(() => {
  108. return indexingStatusBatchDetail.every(indexingStatusDetail => ['completed', 'error', 'paused'].includes(indexingStatusDetail?.indexing_status || ''))
  109. }, [indexingStatusBatchDetail])
  110. const getSourceName = (id: string) => {
  111. const doc = documents.find(document => document.id === id)
  112. return doc?.name
  113. }
  114. const getFileType = (name?: string) => name?.split('.').pop() || 'txt'
  115. const getSourcePercent = (detail: IndexingStatusResponse) => {
  116. const completedCount = detail.completed_segments || 0
  117. const totalCount = detail.total_segments || 0
  118. if (totalCount === 0)
  119. return 0
  120. const percent = Math.round(completedCount * 100 / totalCount)
  121. return percent > 100 ? 100 : percent
  122. }
  123. const getSourceType = (id: string) => {
  124. const doc = documents.find(document => document.id === id)
  125. return doc?.data_source_type
  126. }
  127. const getIcon = (id: string) => {
  128. const doc = documents.find(document => document.id === id)
  129. return doc?.data_source_info.notion_page_icon
  130. }
  131. const isSourceEmbedding = (detail: IndexingStatusResponse) =>
  132. ['indexing', 'splitting', 'parsing', 'cleaning', 'waiting'].includes(detail.indexing_status || '')
  133. return (
  134. <>
  135. <div className='mb-3 flex h-5 items-center'>
  136. <div className='mr-2 flex items-center justify-between text-sm font-medium text-text-secondary'>
  137. {isEmbedding && <div className='flex items-center'>
  138. <RiLoader2Fill className='mr-1 size-4 animate-spin text-text-secondary' />
  139. {t('datasetDocuments.embedding.processing')}
  140. </div>}
  141. {isEmbeddingCompleted && t('datasetDocuments.embedding.completed')}
  142. </div>
  143. </div>
  144. {
  145. enableBilling && plan.type !== Plan.team && (
  146. <div className='mb-3 flex h-14 items-center rounded-xl border-[0.5px] border-black/5 bg-white p-3 shadow-md'>
  147. <div className='flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[#FFF6ED]'>
  148. <ZapFast className='h-4 w-4 text-[#FB6514]' />
  149. </div>
  150. <div className='mx-3 grow text-[13px] font-medium text-gray-700'>
  151. {t('billing.plansCommon.documentProcessingPriorityUpgrade')}
  152. </div>
  153. <UpgradeBtn loc='knowledge-speed-up' />
  154. </div>
  155. )
  156. }
  157. <div className='flex flex-col gap-0.5 pb-2'>
  158. {indexingStatusBatchDetail.map(indexingStatusDetail => (
  159. <div key={indexingStatusDetail.id} className={cn(
  160. 'relative h-[26px] overflow-hidden rounded-md bg-components-progress-bar-bg',
  161. indexingStatusDetail.indexing_status === 'error' && 'bg-state-destructive-hover-alt',
  162. )}>
  163. {isSourceEmbedding(indexingStatusDetail) && (
  164. <div className='absolute left-0 top-0 h-full min-w-0.5 border-r-[2px] border-r-components-progress-bar-progress-highlight bg-components-progress-bar-progress' style={{ width: `${getSourcePercent(indexingStatusDetail)}%` }} />
  165. )}
  166. <div className='z-[1] flex h-full items-center gap-1 pl-[6px] pr-2'>
  167. {getSourceType(indexingStatusDetail.id) === DatasourceType.localFile && (
  168. <DocumentFileIcon
  169. className='size-4 shrink-0'
  170. name={getSourceName(indexingStatusDetail.id)}
  171. extension={getFileType(getSourceName(indexingStatusDetail.id))}
  172. />
  173. )}
  174. {getSourceType(indexingStatusDetail.id) === DatasourceType.onlineDocument && (
  175. <NotionIcon
  176. className='shrink-0'
  177. type='page'
  178. src={getIcon(indexingStatusDetail.id)}
  179. />
  180. )}
  181. <div className='flex w-0 grow items-center gap-1' title={getSourceName(indexingStatusDetail.id)}>
  182. <div className='system-xs-medium truncate text-text-secondary'>
  183. {getSourceName(indexingStatusDetail.id)}
  184. </div>
  185. {
  186. enableBilling && (
  187. <PriorityLabel className='ml-0' />
  188. )
  189. }
  190. </div>
  191. {isSourceEmbedding(indexingStatusDetail) && (
  192. <div className='shrink-0 text-xs text-text-secondary'>{`${getSourcePercent(indexingStatusDetail)}%`}</div>
  193. )}
  194. {indexingStatusDetail.indexing_status === 'error' && (
  195. <Tooltip
  196. popupClassName='px-4 py-[14px] max-w-60 text-sm leading-4 text-text-secondary border-[0.5px] border-components-panel-border rounded-xl'
  197. offset={4}
  198. popupContent={indexingStatusDetail.error}
  199. >
  200. <span>
  201. <RiErrorWarningFill className='size-4 shrink-0 text-text-destructive' />
  202. </span>
  203. </Tooltip>
  204. )}
  205. {indexingStatusDetail.indexing_status === 'completed' && (
  206. <RiCheckboxCircleFill className='size-4 shrink-0 text-text-success' />
  207. )}
  208. </div>
  209. </div>
  210. ))}
  211. </div>
  212. <hr className='my-3 h-[1px] border-0 bg-divider-subtle' />
  213. <RuleDetail
  214. sourceData={ruleDetail}
  215. indexingType={indexingType}
  216. retrievalMethod={retrievalMethod}
  217. />
  218. <div className='my-10 flex items-center gap-2'>
  219. <Button className='w-fit' onClick={navToApiDocs}>
  220. <RiTerminalBoxLine className='mr-2 size-4' />
  221. <span>Access the API</span>
  222. </Button>
  223. <Button className='w-fit' variant='primary' onClick={navToDocumentList}>
  224. <span>{t('datasetCreation.stepThree.navTo')}</span>
  225. <ArrowRightIcon className='ml-2 size-4 stroke-current stroke-1' />
  226. </Button>
  227. </div>
  228. </>
  229. )
  230. }
  231. export default EmbeddingProcess