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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. fileList,
  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. fileList: onlineDriveFileList,
  81. selectedFileIds,
  82. selectedOnlineDriveFileList,
  83. clearOnlineDriveData,
  84. } = useOnlineDrive()
  85. const datasourceType = datasource?.nodeData.provider_type
  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 || !fileList.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, fileList.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 { bucket, currentCredentialId, fileList: onlineDriveFileList } = dataSourceStore.getState()
  224. const datasourceInfoList: Record<string, any>[] = []
  225. if (datasourceType === DatasourceType.localFile) {
  226. fileList.forEach((file) => {
  227. const { id, name, type, size, extension, mime_type } = file.file
  228. const documentInfo = {
  229. related_id: id,
  230. name,
  231. type,
  232. size,
  233. extension,
  234. mime_type,
  235. url: '',
  236. transfer_method: TransferMethod.local_file,
  237. credential_id: currentCredentialId,
  238. }
  239. datasourceInfoList.push(documentInfo)
  240. })
  241. }
  242. if (datasourceType === DatasourceType.onlineDocument) {
  243. onlineDocuments.forEach((page) => {
  244. const { workspace_id, ...rest } = page
  245. const documentInfo = {
  246. workspace_id,
  247. page: rest,
  248. credential_id: currentCredentialId,
  249. }
  250. datasourceInfoList.push(documentInfo)
  251. })
  252. }
  253. if (datasourceType === DatasourceType.websiteCrawl) {
  254. websitePages.forEach((websitePage) => {
  255. datasourceInfoList.push({
  256. ...websitePage,
  257. credential_id: currentCredentialId,
  258. })
  259. })
  260. }
  261. if (datasourceType === DatasourceType.onlineDrive) {
  262. if (datasourceType === DatasourceType.onlineDrive) {
  263. selectedFileIds.forEach((id) => {
  264. const file = onlineDriveFileList.find(file => file.id === id)
  265. datasourceInfoList.push({
  266. bucket,
  267. id: file?.id,
  268. type: file?.type,
  269. credential_id: currentCredentialId,
  270. })
  271. })
  272. }
  273. }
  274. await runPublishedPipeline({
  275. pipeline_id: pipelineId!,
  276. inputs: data,
  277. start_node_id: datasource.nodeId,
  278. datasource_type: datasourceType as DatasourceType,
  279. datasource_info_list: datasourceInfoList,
  280. is_preview: false,
  281. }, {
  282. onSuccess: (res) => {
  283. setBatchId((res as PublishedPipelineRunResponse).batch || '')
  284. setDocuments((res as PublishedPipelineRunResponse).documents || [])
  285. handleNextStep()
  286. },
  287. })
  288. }, [dataSourceStore, datasource, datasourceType, fileList, handleNextStep, onlineDocuments, pipelineId, runPublishedPipeline, selectedFileIds, websitePages])
  289. const onClickProcess = useCallback(() => {
  290. isPreview.current = false
  291. formRef.current?.submit()
  292. }, [])
  293. const onClickPreview = useCallback(() => {
  294. isPreview.current = true
  295. formRef.current?.submit()
  296. }, [])
  297. const handleSubmit = useCallback((data: Record<string, any>) => {
  298. isPreview.current ? handlePreviewChunks(data) : handleProcess(data)
  299. }, [handlePreviewChunks, handleProcess])
  300. const handlePreviewFileChange = useCallback((file: DocumentItem) => {
  301. const { previewLocalFileRef } = dataSourceStore.getState()
  302. previewLocalFileRef.current = file
  303. onClickPreview()
  304. }, [dataSourceStore, onClickPreview])
  305. const handlePreviewOnlineDocumentChange = useCallback((page: NotionPage) => {
  306. const { previewOnlineDocumentRef } = dataSourceStore.getState()
  307. previewOnlineDocumentRef.current = page
  308. onClickPreview()
  309. }, [dataSourceStore, onClickPreview])
  310. const handlePreviewWebsiteChange = useCallback((website: CrawlResultItem) => {
  311. const { previewWebsitePageRef } = dataSourceStore.getState()
  312. previewWebsitePageRef.current = website
  313. onClickPreview()
  314. }, [dataSourceStore, onClickPreview])
  315. const handlePreviewOnlineDriveFileChange = useCallback((file: OnlineDriveFile) => {
  316. const { previewOnlineDriveFileRef } = dataSourceStore.getState()
  317. previewOnlineDriveFileRef.current = file
  318. onClickPreview()
  319. }, [dataSourceStore, onClickPreview])
  320. const handleSelectAll = useCallback(() => {
  321. const {
  322. onlineDocuments,
  323. fileList: onlineDriveFileList,
  324. selectedFileIds,
  325. setOnlineDocuments,
  326. setSelectedFileIds,
  327. setSelectedPagesId,
  328. } = dataSourceStore.getState()
  329. if (datasourceType === DatasourceType.onlineDocument) {
  330. const allIds = currentWorkspace?.pages.map(page => page.page_id) || []
  331. if (onlineDocuments.length < allIds.length) {
  332. const selectedPages = Array.from(allIds).map(pageId => PagesMapAndSelectedPagesId[pageId])
  333. setOnlineDocuments(selectedPages)
  334. setSelectedPagesId(new Set(allIds))
  335. }
  336. else {
  337. setOnlineDocuments([])
  338. setSelectedPagesId(new Set())
  339. }
  340. }
  341. if (datasourceType === DatasourceType.onlineDrive) {
  342. const allKeys = onlineDriveFileList.filter((item) => {
  343. return item.type !== 'bucket'
  344. }).map(file => file.id)
  345. if (selectedFileIds.length < allKeys.length)
  346. setSelectedFileIds(allKeys)
  347. else
  348. setSelectedFileIds([])
  349. }
  350. }, [PagesMapAndSelectedPagesId, currentWorkspace?.pages, dataSourceStore, datasourceType])
  351. const clearDataSourceData = useCallback((dataSource: Datasource) => {
  352. if (dataSource.nodeData.provider_type === DatasourceType.onlineDocument)
  353. clearOnlineDocumentData()
  354. else if (dataSource.nodeData.provider_type === DatasourceType.websiteCrawl)
  355. clearWebsiteCrawlData()
  356. else if (dataSource.nodeData.provider_type === DatasourceType.onlineDrive)
  357. clearOnlineDriveData()
  358. }, [])
  359. const handleSwitchDataSource = useCallback((dataSource: Datasource) => {
  360. const {
  361. setCurrentCredentialId,
  362. currentNodeIdRef,
  363. } = dataSourceStore.getState()
  364. clearDataSourceData(dataSource)
  365. setCurrentCredentialId('')
  366. currentNodeIdRef.current = dataSource.nodeId
  367. setDatasource(dataSource)
  368. }, [dataSourceStore])
  369. const handleCredentialChange = useCallback((credentialId: string) => {
  370. const { setCurrentCredentialId } = dataSourceStore.getState()
  371. clearDataSourceData(datasource!)
  372. setCurrentCredentialId(credentialId)
  373. }, [dataSourceStore, datasource])
  374. if (isFetchingPipelineInfo) {
  375. return (
  376. <Loading type='app' />
  377. )
  378. }
  379. return (
  380. <div
  381. 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'
  382. >
  383. <div className='h-full min-w-0 flex-1'>
  384. <div className='flex h-full flex-col px-14'>
  385. <LeftHeader
  386. steps={steps}
  387. title={t('datasetPipeline.addDocuments.title')}
  388. currentStep={currentStep}
  389. />
  390. <div className='grow overflow-y-auto'>
  391. {
  392. currentStep === 1 && (
  393. <div className='flex flex-col gap-y-5 pt-4'>
  394. <DataSourceOptions
  395. datasourceNodeId={datasource?.nodeId || ''}
  396. onSelect={handleSwitchDataSource}
  397. pipelineNodes={(pipelineInfo?.graph.nodes || []) as Node<DataSourceNodeType>[]}
  398. />
  399. {datasourceType === DatasourceType.localFile && (
  400. <LocalFile
  401. allowedExtensions={datasource!.nodeData.fileExtensions || []}
  402. notSupportBatchUpload={notSupportBatchUpload}
  403. />
  404. )}
  405. {datasourceType === DatasourceType.onlineDocument && (
  406. <OnlineDocuments
  407. nodeId={datasource!.nodeId}
  408. nodeData={datasource!.nodeData}
  409. onCredentialChange={handleCredentialChange}
  410. />
  411. )}
  412. {datasourceType === DatasourceType.websiteCrawl && (
  413. <WebsiteCrawl
  414. nodeId={datasource!.nodeId}
  415. nodeData={datasource!.nodeData}
  416. onCredentialChange={handleCredentialChange}
  417. />
  418. )}
  419. {datasourceType === DatasourceType.onlineDrive && (
  420. <OnlineDrive
  421. nodeId={datasource!.nodeId}
  422. nodeData={datasource!.nodeData}
  423. onCredentialChange={handleCredentialChange}
  424. />
  425. )}
  426. {isShowVectorSpaceFull && (
  427. <VectorSpaceFull />
  428. )}
  429. <Actions
  430. showSelect={showSelect}
  431. totalOptions={totalOptions}
  432. selectedOptions={selectedOptions}
  433. onSelectAll={handleSelectAll}
  434. disabled={nextBtnDisabled}
  435. handleNextStep={handleNextStep}
  436. tip={tip}
  437. />
  438. </div>
  439. )
  440. }
  441. {
  442. currentStep === 2 && (
  443. <ProcessDocuments
  444. ref={formRef}
  445. dataSourceNodeId={datasource!.nodeId}
  446. isRunning={isPending}
  447. onProcess={onClickProcess}
  448. onPreview={onClickPreview}
  449. onSubmit={handleSubmit}
  450. onBack={handleBackStep}
  451. />
  452. )
  453. }
  454. {
  455. currentStep === 3 && (
  456. <Processing
  457. batchId={batchId}
  458. documents={documents}
  459. />
  460. )
  461. }
  462. </div>
  463. </div>
  464. </div>
  465. {/* Preview */}
  466. {
  467. currentStep === 1 && (
  468. <div className='h-full min-w-0 flex-1'>
  469. <div className='flex h-full flex-col pl-2 pt-2'>
  470. {currentLocalFile && (
  471. <FilePreview
  472. file={currentLocalFile}
  473. hidePreview={hidePreviewLocalFile}
  474. />
  475. )}
  476. {currentDocument && (
  477. <OnlineDocumentPreview
  478. datasourceNodeId={datasource!.nodeId}
  479. currentPage={currentDocument}
  480. hidePreview={hidePreviewOnlineDocument}
  481. />
  482. )}
  483. {currentWebsite && (
  484. <WebsitePreview
  485. currentWebsite={currentWebsite}
  486. hidePreview={hideWebsitePreview}
  487. />
  488. )}
  489. </div>
  490. </div>
  491. )
  492. }
  493. {
  494. currentStep === 2 && (
  495. <div className='h-full min-w-0 flex-1'>
  496. <div className='flex h-full flex-col pl-2 pt-2'>
  497. <ChunkPreview
  498. dataSourceType={datasourceType as DatasourceType}
  499. localFiles={fileList.map(file => file.file)}
  500. onlineDocuments={onlineDocuments}
  501. websitePages={websitePages}
  502. onlineDriveFiles={selectedOnlineDriveFileList}
  503. isIdle={isIdle}
  504. isPending={isPending && isPreview.current}
  505. estimateData={estimateData}
  506. onPreview={onClickPreview}
  507. handlePreviewFileChange={handlePreviewFileChange}
  508. handlePreviewOnlineDocumentChange={handlePreviewOnlineDocumentChange}
  509. handlePreviewWebsitePageChange={handlePreviewWebsiteChange}
  510. handlePreviewOnlineDriveFileChange={handlePreviewOnlineDriveFileChange}
  511. />
  512. </div>
  513. </div>
  514. )
  515. }
  516. </div>
  517. )
  518. }
  519. const CreateFormPipelineWrapper = () => {
  520. return (
  521. <DataSourceProvider>
  522. <CreateFormPipeline />
  523. </DataSourceProvider>
  524. )
  525. }
  526. export default CreateFormPipelineWrapper