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.

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