index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import type { FC } 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 { useTranslation } from 'react-i18next'
  6. import { omit } from 'lodash-es'
  7. import { ArrowRightIcon } from '@heroicons/react/24/solid'
  8. import {
  9. RiErrorWarningFill,
  10. } from '@remixicon/react'
  11. import s from './index.module.css'
  12. import cn from '@/utils/classnames'
  13. import { FieldInfo } from '@/app/components/datasets/documents/detail/metadata'
  14. import Button from '@/app/components/base/button'
  15. import type { FullDocumentDetail, IndexingStatusResponse, ProcessRuleResponse } from '@/models/datasets'
  16. import { fetchIndexingStatusBatch as doFetchIndexingStatus, fetchProcessRule } from '@/service/datasets'
  17. import { DataSourceType } from '@/models/datasets'
  18. import NotionIcon from '@/app/components/base/notion-icon'
  19. import PriorityLabel from '@/app/components/billing/priority-label'
  20. import { Plan } from '@/app/components/billing/type'
  21. import { ZapFast } from '@/app/components/base/icons/src/vender/solid/general'
  22. import UpgradeBtn from '@/app/components/billing/upgrade-btn'
  23. import { useProviderContext } from '@/context/provider-context'
  24. import Tooltip from '@/app/components/base/tooltip'
  25. import { sleep } from '@/utils'
  26. type Props = {
  27. datasetId: string
  28. batchId: string
  29. documents?: FullDocumentDetail[]
  30. indexingType?: string
  31. }
  32. const RuleDetail: FC<{ sourceData?: ProcessRuleResponse }> = ({ sourceData }) => {
  33. const { t } = useTranslation()
  34. const segmentationRuleMap = {
  35. mode: t('datasetDocuments.embedding.mode'),
  36. segmentLength: t('datasetDocuments.embedding.segmentLength'),
  37. textCleaning: t('datasetDocuments.embedding.textCleaning'),
  38. }
  39. const getRuleName = (key: string) => {
  40. if (key === 'remove_extra_spaces')
  41. return t('datasetCreation.stepTwo.removeExtraSpaces')
  42. if (key === 'remove_urls_emails')
  43. return t('datasetCreation.stepTwo.removeUrlEmails')
  44. if (key === 'remove_stopwords')
  45. return t('datasetCreation.stepTwo.removeStopwords')
  46. }
  47. const getValue = useCallback((field: string) => {
  48. let value: string | number | undefined = '-'
  49. switch (field) {
  50. case 'mode':
  51. value = sourceData?.mode === 'automatic' ? (t('datasetDocuments.embedding.automatic') as string) : (t('datasetDocuments.embedding.custom') as string)
  52. break
  53. case 'segmentLength':
  54. value = sourceData?.rules?.segmentation?.max_tokens
  55. break
  56. default:
  57. value = sourceData?.mode === 'automatic'
  58. ? (t('datasetDocuments.embedding.automatic') as string)
  59. // eslint-disable-next-line array-callback-return
  60. : sourceData?.rules?.pre_processing_rules?.map((rule) => {
  61. if (rule.enabled)
  62. return getRuleName(rule.id)
  63. }).filter(Boolean).join(';')
  64. break
  65. }
  66. return value
  67. }, [sourceData])
  68. return <div className='flex flex-col pt-8 pb-10 first:mt-0'>
  69. {Object.keys(segmentationRuleMap).map((field) => {
  70. return <FieldInfo
  71. key={field}
  72. label={segmentationRuleMap[field as keyof typeof segmentationRuleMap]}
  73. displayedValue={String(getValue(field))}
  74. />
  75. })}
  76. </div>
  77. }
  78. const EmbeddingProcess: FC<Props> = ({ datasetId, batchId, documents = [], indexingType }) => {
  79. const { t } = useTranslation()
  80. const { enableBilling, plan } = useProviderContext()
  81. const getFirstDocument = documents[0]
  82. const [indexingStatusBatchDetail, setIndexingStatusDetail] = useState<IndexingStatusResponse[]>([])
  83. const fetchIndexingStatus = async () => {
  84. const status = await doFetchIndexingStatus({ datasetId, batchId })
  85. setIndexingStatusDetail(status.data)
  86. return status.data
  87. }
  88. const [isStopQuery, setIsStopQuery] = useState(false)
  89. const isStopQueryRef = useRef(isStopQuery)
  90. useEffect(() => {
  91. isStopQueryRef.current = isStopQuery
  92. }, [isStopQuery])
  93. const stopQueryStatus = () => {
  94. setIsStopQuery(true)
  95. }
  96. const startQueryStatus = async () => {
  97. if (isStopQueryRef.current)
  98. return
  99. try {
  100. const indexingStatusBatchDetail = await fetchIndexingStatus()
  101. const isCompleted = indexingStatusBatchDetail.every(indexingStatusDetail => ['completed', 'error', 'paused'].includes(indexingStatusDetail.indexing_status))
  102. if (isCompleted) {
  103. stopQueryStatus()
  104. return
  105. }
  106. await sleep(2500)
  107. await startQueryStatus()
  108. }
  109. catch (e) {
  110. await sleep(2500)
  111. await startQueryStatus()
  112. }
  113. }
  114. useEffect(() => {
  115. startQueryStatus()
  116. return () => {
  117. stopQueryStatus()
  118. }
  119. // eslint-disable-next-line react-hooks/exhaustive-deps
  120. }, [])
  121. // get rule
  122. const { data: ruleDetail } = useSWR({
  123. action: 'fetchProcessRule',
  124. params: { documentId: getFirstDocument.id },
  125. }, apiParams => fetchProcessRule(omit(apiParams, 'action')), {
  126. revalidateOnFocus: false,
  127. })
  128. const router = useRouter()
  129. const navToDocumentList = () => {
  130. router.push(`/datasets/${datasetId}/documents`)
  131. }
  132. const isEmbedding = useMemo(() => {
  133. return indexingStatusBatchDetail.some(indexingStatusDetail => ['indexing', 'splitting', 'parsing', 'cleaning'].includes(indexingStatusDetail?.indexing_status || ''))
  134. }, [indexingStatusBatchDetail])
  135. const isEmbeddingCompleted = useMemo(() => {
  136. return indexingStatusBatchDetail.every(indexingStatusDetail => ['completed', 'error', 'paused'].includes(indexingStatusDetail?.indexing_status || ''))
  137. }, [indexingStatusBatchDetail])
  138. const getSourceName = (id: string) => {
  139. const doc = documents.find(document => document.id === id)
  140. return doc?.name
  141. }
  142. const getFileType = (name?: string) => name?.split('.').pop() || 'txt'
  143. const getSourcePercent = (detail: IndexingStatusResponse) => {
  144. const completedCount = detail.completed_segments || 0
  145. const totalCount = detail.total_segments || 0
  146. if (totalCount === 0)
  147. return 0
  148. const percent = Math.round(completedCount * 100 / totalCount)
  149. return percent > 100 ? 100 : percent
  150. }
  151. const getSourceType = (id: string) => {
  152. const doc = documents.find(document => document.id === id)
  153. return doc?.data_source_type as DataSourceType
  154. }
  155. const getIcon = (id: string) => {
  156. const doc = documents.find(document => document.id === id)
  157. return doc?.data_source_info.notion_page_icon
  158. }
  159. const isSourceEmbedding = (detail: IndexingStatusResponse) => ['indexing', 'splitting', 'parsing', 'cleaning', 'waiting'].includes(detail.indexing_status || '')
  160. return (
  161. <>
  162. <div className='h-5 flex items-center mb-5'>
  163. <div className={s.embeddingStatus}>
  164. {isEmbedding && t('datasetDocuments.embedding.processing')}
  165. {isEmbeddingCompleted && t('datasetDocuments.embedding.completed')}
  166. </div>
  167. </div>
  168. {
  169. enableBilling && plan.type !== Plan.team && (
  170. <div className='flex items-center mb-3 p-3 h-14 bg-white border-[0.5px] border-black/5 shadow-md rounded-xl'>
  171. <div className='shrink-0 flex items-center justify-center w-8 h-8 bg-[#FFF6ED] rounded-lg'>
  172. <ZapFast className='w-4 h-4 text-[#FB6514]' />
  173. </div>
  174. <div className='grow mx-3 text-[13px] font-medium text-gray-700'>
  175. {t('billing.plansCommon.documentProcessingPriorityUpgrade')}
  176. </div>
  177. <UpgradeBtn loc='knowledge-speed-up' />
  178. </div>
  179. )
  180. }
  181. <div className={s.progressContainer}>
  182. {indexingStatusBatchDetail.map(indexingStatusDetail => (
  183. <div key={indexingStatusDetail.id} className={cn(
  184. s.sourceItem,
  185. indexingStatusDetail.indexing_status === 'error' && s.error,
  186. indexingStatusDetail.indexing_status === 'completed' && s.success,
  187. )}>
  188. {isSourceEmbedding(indexingStatusDetail) && (
  189. <div className={s.progressbar} style={{ width: `${getSourcePercent(indexingStatusDetail)}%` }} />
  190. )}
  191. <div className={`${s.info} grow`}>
  192. {getSourceType(indexingStatusDetail.id) === DataSourceType.FILE && (
  193. <div className={cn(s.fileIcon, s[getFileType(getSourceName(indexingStatusDetail.id))])} />
  194. )}
  195. {getSourceType(indexingStatusDetail.id) === DataSourceType.NOTION && (
  196. <NotionIcon
  197. className='shrink-0 mr-1'
  198. type='page'
  199. src={getIcon(indexingStatusDetail.id)}
  200. />
  201. )}
  202. <div className={`${s.name} truncate`} title={getSourceName(indexingStatusDetail.id)}>{getSourceName(indexingStatusDetail.id)}</div>
  203. {
  204. enableBilling && (
  205. <PriorityLabel />
  206. )
  207. }
  208. </div>
  209. <div className='shrink-0'>
  210. {isSourceEmbedding(indexingStatusDetail) && (
  211. <div className={s.percent}>{`${getSourcePercent(indexingStatusDetail)}%`}</div>
  212. )}
  213. {indexingStatusDetail.indexing_status === 'error' && indexingStatusDetail.error && (
  214. <Tooltip
  215. popupContent={(
  216. <div className='max-w-[400px]'>
  217. {indexingStatusDetail.error}
  218. </div>
  219. )}
  220. >
  221. <div className={cn(s.percent, s.error, 'flex items-center')}>
  222. Error
  223. <RiErrorWarningFill className='ml-1 w-4 h-4' />
  224. </div>
  225. </Tooltip>
  226. )}
  227. {indexingStatusDetail.indexing_status === 'error' && !indexingStatusDetail.error && (
  228. <div className={cn(s.percent, s.error, 'flex items-center')}>
  229. Error
  230. </div>
  231. )}
  232. {indexingStatusDetail.indexing_status === 'completed' && (
  233. <div className={cn(s.percent, s.success)}>100%</div>
  234. )}
  235. </div>
  236. </div>
  237. ))}
  238. </div>
  239. <RuleDetail sourceData={ruleDetail} />
  240. <div className='flex items-center gap-2 mt-10'>
  241. <Button className='w-fit' variant='primary' onClick={navToDocumentList}>
  242. <span>{t('datasetCreation.stepThree.navTo')}</span>
  243. <ArrowRightIcon className='h-4 w-4 ml-2 stroke-current stroke-1' />
  244. </Button>
  245. </div>
  246. </>
  247. )
  248. }
  249. export default EmbeddingProcess