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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. 'use client'
  2. import { useCallback, useMemo, useRef, useState } from 'react'
  3. import DataSourceOptions from './data-source-options'
  4. import type { CrawlResultItem, DocumentItem, CustomFile as File, FileIndexingEstimateResponse } from '@/models/datasets'
  5. import LocalFile from '@/app/components/datasets/documents/create-from-pipeline/data-source/local-file'
  6. import { useProviderContextSelector } from '@/context/provider-context'
  7. import type { NotionPage } from '@/models/common'
  8. import OnlineDocuments from '@/app/components/datasets/documents/create-from-pipeline/data-source/online-documents'
  9. import VectorSpaceFull from '@/app/components/billing/vector-space-full'
  10. import WebsiteCrawl from '@/app/components/datasets/documents/create-from-pipeline/data-source/website-crawl'
  11. import OnlineDrive from '@/app/components/datasets/documents/create-from-pipeline/data-source/online-drive'
  12. import Actions from './actions'
  13. import { useTranslation } from 'react-i18next'
  14. import type { Datasource } from '@/app/components/rag-pipeline/components/panel/test-run/types'
  15. import LeftHeader from './left-header'
  16. import { usePublishedPipelineInfo, useRunPublishedPipeline } from '@/service/use-pipeline'
  17. import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
  18. import Loading from '@/app/components/base/loading'
  19. import type { Node } from '@/app/components/workflow/types'
  20. import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-source/types'
  21. import FilePreview from './preview/file-preview'
  22. import OnlineDocumentPreview from './preview/online-document-preview'
  23. import WebsitePreview from './preview/web-preview'
  24. import ProcessDocuments from './process-documents'
  25. import ChunkPreview from './preview/chunk-preview'
  26. import Processing from './processing'
  27. import type {
  28. InitialDocumentDetail,
  29. OnlineDriveFile,
  30. PublishedPipelineRunPreviewResponse,
  31. PublishedPipelineRunResponse,
  32. } from '@/models/pipeline'
  33. import { DatasourceType } from '@/models/pipeline'
  34. import { TransferMethod } from '@/types/app'
  35. import { useAddDocumentsSteps, useLocalFile, useOnlineDocument, useOnlineDrive, useWebsiteCrawl } from './hooks'
  36. import DataSourceProvider from './data-source/store/provider'
  37. import { useDataSourceStore } from './data-source/store'
  38. import { useFileUploadConfig } from '@/service/use-common'
  39. const CreateFormPipeline = () => {
  40. const { t } = useTranslation()
  41. const plan = useProviderContextSelector(state => state.plan)
  42. const enableBilling = useProviderContextSelector(state => state.enableBilling)
  43. const pipelineId = useDatasetDetailContextWithSelector(s => s.dataset?.pipeline_id)
  44. const [datasource, setDatasource] = useState<Datasource>()
  45. const [estimateData, setEstimateData] = useState<FileIndexingEstimateResponse | undefined>(undefined)
  46. const [batchId, setBatchId] = useState('')
  47. const [documents, setDocuments] = useState<InitialDocumentDetail[]>([])
  48. const dataSourceStore = useDataSourceStore()
  49. const isPreview = useRef(false)
  50. const formRef = useRef<any>(null)
  51. const { data: pipelineInfo, isFetching: isFetchingPipelineInfo } = usePublishedPipelineInfo(pipelineId || '')
  52. const { data: fileUploadConfigResponse } = useFileUploadConfig()
  53. const {
  54. steps,
  55. currentStep,
  56. handleNextStep,
  57. handleBackStep,
  58. } = useAddDocumentsSteps()
  59. const {
  60. localFileList,
  61. allFileLoaded,
  62. currentLocalFile,
  63. hidePreviewLocalFile,
  64. } = useLocalFile()
  65. const {
  66. currentWorkspace,
  67. onlineDocuments,
  68. currentDocument,
  69. PagesMapAndSelectedPagesId,
  70. hidePreviewOnlineDocument,
  71. clearOnlineDocumentData,
  72. } = useOnlineDocument()
  73. const {
  74. websitePages,
  75. currentWebsite,
  76. hideWebsitePreview,
  77. clearWebsiteCrawlData,
  78. } = useWebsiteCrawl()
  79. const {
  80. onlineDriveFileList,
  81. selectedFileIds,
  82. selectedOnlineDriveFileList,
  83. clearOnlineDriveData,
  84. } = useOnlineDrive()
  85. const datasourceType = useMemo(() => datasource?.nodeData.provider_type, [datasource])
  86. const isVectorSpaceFull = plan.usage.vectorSpace >= plan.total.vectorSpace
  87. const isShowVectorSpaceFull = useMemo(() => {
  88. if (!datasource)
  89. return false
  90. if (datasourceType === DatasourceType.localFile)
  91. return allFileLoaded && isVectorSpaceFull && enableBilling
  92. if (datasourceType === DatasourceType.onlineDocument)
  93. return onlineDocuments.length > 0 && isVectorSpaceFull && enableBilling
  94. if (datasourceType === DatasourceType.websiteCrawl)
  95. return websitePages.length > 0 && isVectorSpaceFull && enableBilling
  96. if (datasourceType === DatasourceType.onlineDrive)
  97. return onlineDriveFileList.length > 0 && isVectorSpaceFull && enableBilling
  98. return false
  99. }, [allFileLoaded, datasource, datasourceType, enableBilling, isVectorSpaceFull, onlineDocuments.length, onlineDriveFileList.length, websitePages.length])
  100. const notSupportBatchUpload = enableBilling && plan.type === 'sandbox'
  101. const nextBtnDisabled = useMemo(() => {
  102. if (!datasource) return true
  103. if (datasourceType === DatasourceType.localFile)
  104. return isShowVectorSpaceFull || !localFileList.length || !allFileLoaded
  105. if (datasourceType === DatasourceType.onlineDocument)
  106. return isShowVectorSpaceFull || !onlineDocuments.length
  107. if (datasourceType === DatasourceType.websiteCrawl)
  108. return isShowVectorSpaceFull || !websitePages.length
  109. if (datasourceType === DatasourceType.onlineDrive)
  110. return isShowVectorSpaceFull || !selectedFileIds.length
  111. return false
  112. }, [datasource, datasourceType, isShowVectorSpaceFull, localFileList.length, allFileLoaded, onlineDocuments.length, websitePages.length, selectedFileIds.length])
  113. const fileUploadConfig = useMemo(() => fileUploadConfigResponse ?? {
  114. file_size_limit: 15,
  115. batch_count_limit: 5,
  116. }, [fileUploadConfigResponse])
  117. const showSelect = useMemo(() => {
  118. if (datasourceType === DatasourceType.onlineDocument) {
  119. const pagesCount = currentWorkspace?.pages.length ?? 0
  120. return pagesCount > 0
  121. }
  122. if (datasourceType === DatasourceType.onlineDrive) {
  123. const isBucketList = onlineDriveFileList.some(file => file.type === 'bucket')
  124. return !isBucketList && onlineDriveFileList.filter((item) => {
  125. return item.type !== 'bucket'
  126. }).length > 0
  127. }
  128. }, [currentWorkspace?.pages.length, datasourceType, onlineDriveFileList])
  129. const totalOptions = useMemo(() => {
  130. if (datasourceType === DatasourceType.onlineDocument)
  131. return currentWorkspace?.pages.length
  132. if (datasourceType === DatasourceType.onlineDrive) {
  133. return onlineDriveFileList.filter((item) => {
  134. return item.type !== 'bucket'
  135. }).length
  136. }
  137. }, [currentWorkspace?.pages.length, datasourceType, onlineDriveFileList])
  138. const selectedOptions = useMemo(() => {
  139. if (datasourceType === DatasourceType.onlineDocument)
  140. return onlineDocuments.length
  141. if (datasourceType === DatasourceType.onlineDrive)
  142. return selectedFileIds.length
  143. }, [datasourceType, onlineDocuments.length, selectedFileIds.length])
  144. const tip = useMemo(() => {
  145. if (datasourceType === DatasourceType.onlineDocument)
  146. return t('datasetPipeline.addDocuments.selectOnlineDocumentTip', { count: 50 })
  147. if (datasourceType === DatasourceType.onlineDrive) {
  148. return t('datasetPipeline.addDocuments.selectOnlineDriveTip', {
  149. count: fileUploadConfig.batch_count_limit,
  150. fileSize: fileUploadConfig.file_size_limit,
  151. })
  152. }
  153. return ''
  154. }, [datasourceType, fileUploadConfig.batch_count_limit, fileUploadConfig.file_size_limit, t])
  155. const { mutateAsync: runPublishedPipeline, isIdle, isPending } = useRunPublishedPipeline()
  156. const handlePreviewChunks = useCallback(async (data: Record<string, any>) => {
  157. if (!datasource)
  158. return
  159. const {
  160. previewLocalFileRef,
  161. previewOnlineDocumentRef,
  162. previewWebsitePageRef,
  163. previewOnlineDriveFileRef,
  164. currentCredentialId,
  165. } = dataSourceStore.getState()
  166. const datasourceInfoList: Record<string, any>[] = []
  167. if (datasourceType === DatasourceType.localFile) {
  168. const { id, name, type, size, extension, mime_type } = previewLocalFileRef.current as File
  169. const documentInfo = {
  170. related_id: id,
  171. name,
  172. type,
  173. size,
  174. extension,
  175. mime_type,
  176. url: '',
  177. transfer_method: TransferMethod.local_file,
  178. credential_id: currentCredentialId,
  179. }
  180. datasourceInfoList.push(documentInfo)
  181. }
  182. if (datasourceType === DatasourceType.onlineDocument) {
  183. const { workspace_id, ...rest } = previewOnlineDocumentRef.current!
  184. const documentInfo = {
  185. workspace_id,
  186. page: rest,
  187. credential_id: currentCredentialId,
  188. }
  189. datasourceInfoList.push(documentInfo)
  190. }
  191. if (datasourceType === DatasourceType.websiteCrawl) {
  192. datasourceInfoList.push({
  193. ...previewWebsitePageRef.current!,
  194. credential_id: currentCredentialId,
  195. })
  196. }
  197. if (datasourceType === DatasourceType.onlineDrive) {
  198. const { bucket } = dataSourceStore.getState()
  199. const { id, type } = previewOnlineDriveFileRef.current!
  200. datasourceInfoList.push({
  201. bucket,
  202. id,
  203. type,
  204. credential_id: currentCredentialId,
  205. })
  206. }
  207. await runPublishedPipeline({
  208. pipeline_id: pipelineId!,
  209. inputs: data,
  210. start_node_id: datasource.nodeId,
  211. datasource_type: datasourceType as DatasourceType,
  212. datasource_info_list: datasourceInfoList,
  213. is_preview: true,
  214. }, {
  215. onSuccess: (res) => {
  216. setEstimateData((res as PublishedPipelineRunPreviewResponse).data.outputs)
  217. },
  218. })
  219. }, [datasource, datasourceType, runPublishedPipeline, pipelineId, dataSourceStore])
  220. const handleProcess = useCallback(async (data: Record<string, any>) => {
  221. if (!datasource)
  222. return
  223. const { currentCredentialId } = dataSourceStore.getState()
  224. const datasourceInfoList: Record<string, any>[] = []
  225. if (datasourceType === DatasourceType.localFile) {
  226. const {
  227. localFileList,
  228. } = dataSourceStore.getState()
  229. localFileList.forEach((file) => {
  230. const { id, name, type, size, extension, mime_type } = file.file
  231. const documentInfo = {
  232. related_id: id,
  233. name,
  234. type,
  235. size,
  236. extension,
  237. mime_type,
  238. url: '',
  239. transfer_method: TransferMethod.local_file,
  240. credential_id: currentCredentialId,
  241. }
  242. datasourceInfoList.push(documentInfo)
  243. })
  244. }
  245. if (datasourceType === DatasourceType.onlineDocument) {
  246. const {
  247. onlineDocuments,
  248. } = dataSourceStore.getState()
  249. onlineDocuments.forEach((page) => {
  250. const { workspace_id, ...rest } = page
  251. const documentInfo = {
  252. workspace_id,
  253. page: rest,
  254. credential_id: currentCredentialId,
  255. }
  256. datasourceInfoList.push(documentInfo)
  257. })
  258. }
  259. if (datasourceType === DatasourceType.websiteCrawl) {
  260. const {
  261. websitePages,
  262. } = dataSourceStore.getState()
  263. websitePages.forEach((websitePage) => {
  264. datasourceInfoList.push({
  265. ...websitePage,
  266. credential_id: currentCredentialId,
  267. })
  268. })
  269. }
  270. if (datasourceType === DatasourceType.onlineDrive) {
  271. const {
  272. bucket,
  273. selectedFileIds,
  274. onlineDriveFileList,
  275. } = dataSourceStore.getState()
  276. selectedFileIds.forEach((id) => {
  277. const file = onlineDriveFileList.find(file => file.id === id)
  278. datasourceInfoList.push({
  279. bucket,
  280. id: file?.id,
  281. type: file?.type,
  282. credential_id: currentCredentialId,
  283. })
  284. })
  285. }
  286. await runPublishedPipeline({
  287. pipeline_id: pipelineId!,
  288. inputs: data,
  289. start_node_id: datasource.nodeId,
  290. datasource_type: datasourceType as DatasourceType,
  291. datasource_info_list: datasourceInfoList,
  292. is_preview: false,
  293. }, {
  294. onSuccess: (res) => {
  295. setBatchId((res as PublishedPipelineRunResponse).batch || '')
  296. setDocuments((res as PublishedPipelineRunResponse).documents || [])
  297. handleNextStep()
  298. },
  299. })
  300. }, [dataSourceStore, datasource, datasourceType, handleNextStep, pipelineId, runPublishedPipeline])
  301. const onClickProcess = useCallback(() => {
  302. isPreview.current = false
  303. formRef.current?.submit()
  304. }, [])
  305. const onClickPreview = useCallback(() => {
  306. isPreview.current = true
  307. formRef.current?.submit()
  308. }, [])
  309. const handleSubmit = useCallback((data: Record<string, any>) => {
  310. isPreview.current ? handlePreviewChunks(data) : handleProcess(data)
  311. }, [handlePreviewChunks, handleProcess])
  312. const handlePreviewFileChange = useCallback((file: DocumentItem) => {
  313. const { previewLocalFileRef } = dataSourceStore.getState()
  314. previewLocalFileRef.current = file
  315. onClickPreview()
  316. }, [dataSourceStore, onClickPreview])
  317. const handlePreviewOnlineDocumentChange = useCallback((page: NotionPage) => {
  318. const { previewOnlineDocumentRef } = dataSourceStore.getState()
  319. previewOnlineDocumentRef.current = page
  320. onClickPreview()
  321. }, [dataSourceStore, onClickPreview])
  322. const handlePreviewWebsiteChange = useCallback((website: CrawlResultItem) => {
  323. const { previewWebsitePageRef } = dataSourceStore.getState()
  324. previewWebsitePageRef.current = website
  325. onClickPreview()
  326. }, [dataSourceStore, onClickPreview])
  327. const handlePreviewOnlineDriveFileChange = useCallback((file: OnlineDriveFile) => {
  328. const { previewOnlineDriveFileRef } = dataSourceStore.getState()
  329. previewOnlineDriveFileRef.current = file
  330. onClickPreview()
  331. }, [dataSourceStore, onClickPreview])
  332. const handleSelectAll = useCallback(() => {
  333. const {
  334. onlineDocuments,
  335. onlineDriveFileList,
  336. selectedFileIds,
  337. setOnlineDocuments,
  338. setSelectedFileIds,
  339. setSelectedPagesId,
  340. } = dataSourceStore.getState()
  341. if (datasourceType === DatasourceType.onlineDocument) {
  342. const allIds = currentWorkspace?.pages.map(page => page.page_id) || []
  343. if (onlineDocuments.length < allIds.length) {
  344. const selectedPages = Array.from(allIds).map(pageId => PagesMapAndSelectedPagesId[pageId])
  345. setOnlineDocuments(selectedPages)
  346. setSelectedPagesId(new Set(allIds))
  347. }
  348. else {
  349. setOnlineDocuments([])
  350. setSelectedPagesId(new Set())
  351. }
  352. }
  353. if (datasourceType === DatasourceType.onlineDrive) {
  354. const allKeys = onlineDriveFileList.filter((item) => {
  355. return item.type !== 'bucket'
  356. }).map(file => file.id)
  357. if (selectedFileIds.length < allKeys.length)
  358. setSelectedFileIds(allKeys)
  359. else
  360. setSelectedFileIds([])
  361. }
  362. }, [PagesMapAndSelectedPagesId, currentWorkspace?.pages, dataSourceStore, datasourceType])
  363. const clearDataSourceData = useCallback((dataSource: Datasource) => {
  364. if (dataSource.nodeData.provider_type === DatasourceType.onlineDocument)
  365. clearOnlineDocumentData()
  366. else if (dataSource.nodeData.provider_type === DatasourceType.websiteCrawl)
  367. clearWebsiteCrawlData()
  368. else if (dataSource.nodeData.provider_type === DatasourceType.onlineDrive)
  369. clearOnlineDriveData()
  370. }, [])
  371. const handleSwitchDataSource = useCallback((dataSource: Datasource) => {
  372. const {
  373. setCurrentCredentialId,
  374. currentNodeIdRef,
  375. } = dataSourceStore.getState()
  376. clearDataSourceData(dataSource)
  377. setCurrentCredentialId('')
  378. currentNodeIdRef.current = dataSource.nodeId
  379. setDatasource(dataSource)
  380. }, [dataSourceStore])
  381. const handleCredentialChange = useCallback((credentialId: string) => {
  382. const { setCurrentCredentialId } = dataSourceStore.getState()
  383. clearDataSourceData(datasource!)
  384. setCurrentCredentialId(credentialId)
  385. }, [dataSourceStore, datasource])
  386. if (isFetchingPipelineInfo) {
  387. return (
  388. <Loading type='app' />
  389. )
  390. }
  391. return (
  392. <div
  393. className='relative flex h-[calc(100vh-56px)] w-full min-w-[1024px] overflow-x-auto rounded-t-2xl border-t border-effects-highlight bg-background-default-subtle'
  394. >
  395. <div className='h-full min-w-0 flex-1'>
  396. <div className='flex h-full flex-col px-14'>
  397. <LeftHeader
  398. steps={steps}
  399. title={t('datasetPipeline.addDocuments.title')}
  400. currentStep={currentStep}
  401. />
  402. <div className='grow overflow-y-auto'>
  403. {
  404. currentStep === 1 && (
  405. <div className='flex flex-col gap-y-5 pt-4'>
  406. <DataSourceOptions
  407. datasourceNodeId={datasource?.nodeId || ''}
  408. onSelect={handleSwitchDataSource}
  409. pipelineNodes={(pipelineInfo?.graph.nodes || []) as Node<DataSourceNodeType>[]}
  410. />
  411. {datasourceType === DatasourceType.localFile && (
  412. <LocalFile
  413. allowedExtensions={datasource!.nodeData.fileExtensions || []}
  414. notSupportBatchUpload={notSupportBatchUpload}
  415. />
  416. )}
  417. {datasourceType === DatasourceType.onlineDocument && (
  418. <OnlineDocuments
  419. nodeId={datasource!.nodeId}
  420. nodeData={datasource!.nodeData}
  421. onCredentialChange={handleCredentialChange}
  422. />
  423. )}
  424. {datasourceType === DatasourceType.websiteCrawl && (
  425. <WebsiteCrawl
  426. nodeId={datasource!.nodeId}
  427. nodeData={datasource!.nodeData}
  428. onCredentialChange={handleCredentialChange}
  429. />
  430. )}
  431. {datasourceType === DatasourceType.onlineDrive && (
  432. <OnlineDrive
  433. nodeId={datasource!.nodeId}
  434. nodeData={datasource!.nodeData}
  435. onCredentialChange={handleCredentialChange}
  436. />
  437. )}
  438. {isShowVectorSpaceFull && (
  439. <VectorSpaceFull />
  440. )}
  441. <Actions
  442. showSelect={showSelect}
  443. totalOptions={totalOptions}
  444. selectedOptions={selectedOptions}
  445. onSelectAll={handleSelectAll}
  446. disabled={nextBtnDisabled}
  447. handleNextStep={handleNextStep}
  448. tip={tip}
  449. />
  450. </div>
  451. )
  452. }
  453. {
  454. currentStep === 2 && (
  455. <ProcessDocuments
  456. ref={formRef}
  457. dataSourceNodeId={datasource!.nodeId}
  458. isRunning={isPending}
  459. onProcess={onClickProcess}
  460. onPreview={onClickPreview}
  461. onSubmit={handleSubmit}
  462. onBack={handleBackStep}
  463. />
  464. )
  465. }
  466. {
  467. currentStep === 3 && (
  468. <Processing
  469. batchId={batchId}
  470. documents={documents}
  471. />
  472. )
  473. }
  474. </div>
  475. </div>
  476. </div>
  477. {/* Preview */}
  478. {
  479. currentStep === 1 && (
  480. <div className='h-full min-w-0 flex-1'>
  481. <div className='flex h-full flex-col pl-2 pt-2'>
  482. {currentLocalFile && (
  483. <FilePreview
  484. file={currentLocalFile}
  485. hidePreview={hidePreviewLocalFile}
  486. />
  487. )}
  488. {currentDocument && (
  489. <OnlineDocumentPreview
  490. datasourceNodeId={datasource!.nodeId}
  491. currentPage={currentDocument}
  492. hidePreview={hidePreviewOnlineDocument}
  493. />
  494. )}
  495. {currentWebsite && (
  496. <WebsitePreview
  497. currentWebsite={currentWebsite}
  498. hidePreview={hideWebsitePreview}
  499. />
  500. )}
  501. </div>
  502. </div>
  503. )
  504. }
  505. {
  506. currentStep === 2 && (
  507. <div className='h-full min-w-0 flex-1'>
  508. <div className='flex h-full flex-col pl-2 pt-2'>
  509. <ChunkPreview
  510. dataSourceType={datasourceType as DatasourceType}
  511. localFiles={localFileList.map(file => file.file)}
  512. onlineDocuments={onlineDocuments}
  513. websitePages={websitePages}
  514. onlineDriveFiles={selectedOnlineDriveFileList}
  515. isIdle={isIdle}
  516. isPending={isPending && isPreview.current}
  517. estimateData={estimateData}
  518. onPreview={onClickPreview}
  519. handlePreviewFileChange={handlePreviewFileChange}
  520. handlePreviewOnlineDocumentChange={handlePreviewOnlineDocumentChange}
  521. handlePreviewWebsitePageChange={handlePreviewWebsiteChange}
  522. handlePreviewOnlineDriveFileChange={handlePreviewOnlineDriveFileChange}
  523. />
  524. </div>
  525. </div>
  526. )
  527. }
  528. </div>
  529. )
  530. }
  531. const CreateFormPipelineWrapper = () => {
  532. return (
  533. <DataSourceProvider>
  534. <CreateFormPipeline />
  535. </DataSourceProvider>
  536. )
  537. }
  538. export default CreateFormPipelineWrapper