index.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. /* eslint-disable no-mixed-operators */
  2. 'use client'
  3. import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useBoolean } from 'ahooks'
  6. import { XMarkIcon } from '@heroicons/react/20/solid'
  7. import cn from 'classnames'
  8. import Link from 'next/link'
  9. import { groupBy } from 'lodash-es'
  10. import PreviewItem, { PreviewType } from './preview-item'
  11. import s from './index.module.css'
  12. import type { CreateDocumentReq, File, FullDocumentDetail, FileIndexingEstimateResponse as IndexingEstimateResponse, NotionInfo, PreProcessingRule, Rules, createDocumentResponse } from '@/models/datasets'
  13. import {
  14. createDocument,
  15. createFirstDocument,
  16. fetchFileIndexingEstimate as didFetchFileIndexingEstimate,
  17. fetchDefaultProcessRule,
  18. } from '@/service/datasets'
  19. import Button from '@/app/components/base/button'
  20. import Loading from '@/app/components/base/loading'
  21. import Toast from '@/app/components/base/toast'
  22. import { formatNumber } from '@/utils/format'
  23. import type { DataSourceNotionPage } from '@/models/common'
  24. import { DataSourceType } from '@/models/datasets'
  25. import NotionIcon from '@/app/components/base/notion-icon'
  26. import Switch from '@/app/components/base/switch'
  27. import { MessageChatSquare } from '@/app/components/base/icons/src/public/common'
  28. import { useDatasetDetailContext } from '@/context/dataset-detail'
  29. type Page = DataSourceNotionPage & { workspace_id: string }
  30. type StepTwoProps = {
  31. isSetting?: boolean
  32. documentDetail?: FullDocumentDetail
  33. hasSetAPIKEY: boolean
  34. onSetting: () => void
  35. datasetId?: string
  36. indexingType?: string
  37. dataSourceType: DataSourceType
  38. files: File[]
  39. notionPages?: Page[]
  40. onStepChange?: (delta: number) => void
  41. updateIndexingTypeCache?: (type: string) => void
  42. updateResultCache?: (res: createDocumentResponse) => void
  43. onSave?: () => void
  44. onCancel?: () => void
  45. }
  46. enum SegmentType {
  47. AUTO = 'automatic',
  48. CUSTOM = 'custom',
  49. }
  50. enum IndexingType {
  51. QUALIFIED = 'high_quality',
  52. ECONOMICAL = 'economy',
  53. }
  54. enum DocForm {
  55. TEXT = 'text_model',
  56. QA = 'qa_model',
  57. }
  58. const StepTwo = ({
  59. isSetting,
  60. documentDetail,
  61. hasSetAPIKEY,
  62. onSetting,
  63. datasetId,
  64. indexingType,
  65. dataSourceType,
  66. files,
  67. notionPages = [],
  68. onStepChange,
  69. updateIndexingTypeCache,
  70. updateResultCache,
  71. onSave,
  72. onCancel,
  73. }: StepTwoProps) => {
  74. const { t } = useTranslation()
  75. const { mutateDatasetRes } = useDatasetDetailContext()
  76. const scrollRef = useRef<HTMLDivElement>(null)
  77. const [scrolled, setScrolled] = useState(false)
  78. const previewScrollRef = useRef<HTMLDivElement>(null)
  79. const [previewScrolled, setPreviewScrolled] = useState(false)
  80. const [segmentationType, setSegmentationType] = useState<SegmentType>(SegmentType.AUTO)
  81. const [segmentIdentifier, setSegmentIdentifier] = useState('\\n')
  82. const [max, setMax] = useState(1000)
  83. const [rules, setRules] = useState<PreProcessingRule[]>([])
  84. const [defaultConfig, setDefaultConfig] = useState<Rules>()
  85. const hasSetIndexType = !!indexingType
  86. const [indexType, setIndexType] = useState<IndexingType>(
  87. indexingType
  88. || hasSetAPIKEY
  89. ? IndexingType.QUALIFIED
  90. : IndexingType.ECONOMICAL,
  91. )
  92. const [docForm, setDocForm] = useState<DocForm | string>(
  93. datasetId && documentDetail ? documentDetail.doc_form : DocForm.TEXT,
  94. )
  95. const [previewSwitched, setPreviewSwitched] = useState(false)
  96. const [showPreview, { setTrue: setShowPreview, setFalse: hidePreview }] = useBoolean()
  97. const [customFileIndexingEstimate, setCustomFileIndexingEstimate] = useState<IndexingEstimateResponse | null>(null)
  98. const [automaticFileIndexingEstimate, setAutomaticFileIndexingEstimate] = useState<IndexingEstimateResponse | null>(null)
  99. const fileIndexingEstimate = (() => {
  100. return segmentationType === SegmentType.AUTO ? automaticFileIndexingEstimate : customFileIndexingEstimate
  101. })()
  102. const scrollHandle = (e: any) => {
  103. if (e.target.scrollTop > 0)
  104. setScrolled(true)
  105. else
  106. setScrolled(false)
  107. }
  108. const previewScrollHandle = (e: any) => {
  109. if (e.target.scrollTop > 0)
  110. setPreviewScrolled(true)
  111. else
  112. setPreviewScrolled(false)
  113. }
  114. const getFileName = (name: string) => {
  115. const arr = name.split('.')
  116. return arr.slice(0, -1).join('.')
  117. }
  118. const getRuleName = (key: string) => {
  119. if (key === 'remove_extra_spaces')
  120. return t('datasetCreation.stepTwo.removeExtraSpaces')
  121. if (key === 'remove_urls_emails')
  122. return t('datasetCreation.stepTwo.removeUrlEmails')
  123. if (key === 'remove_stopwords')
  124. return t('datasetCreation.stepTwo.removeStopwords')
  125. }
  126. const ruleChangeHandle = (id: string) => {
  127. const newRules = rules.map((rule) => {
  128. if (rule.id === id) {
  129. return {
  130. id: rule.id,
  131. enabled: !rule.enabled,
  132. }
  133. }
  134. return rule
  135. })
  136. setRules(newRules)
  137. }
  138. const resetRules = () => {
  139. if (defaultConfig) {
  140. setSegmentIdentifier(defaultConfig.segmentation.separator === '\n' ? '\\n' : defaultConfig.segmentation.separator || '\\n')
  141. setMax(defaultConfig.segmentation.max_tokens)
  142. setRules(defaultConfig.pre_processing_rules)
  143. }
  144. }
  145. const fetchFileIndexingEstimate = async (docForm = DocForm.TEXT) => {
  146. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  147. const res = await didFetchFileIndexingEstimate(getFileIndexingEstimateParams(docForm))
  148. if (segmentationType === SegmentType.CUSTOM)
  149. setCustomFileIndexingEstimate(res)
  150. else
  151. setAutomaticFileIndexingEstimate(res)
  152. }
  153. const confirmChangeCustomConfig = () => {
  154. setCustomFileIndexingEstimate(null)
  155. setShowPreview()
  156. fetchFileIndexingEstimate()
  157. setPreviewSwitched(false)
  158. }
  159. const getIndexing_technique = () => indexingType || indexType
  160. const getProcessRule = () => {
  161. const processRule: any = {
  162. rules: {}, // api will check this. It will be removed after api refactored.
  163. mode: segmentationType,
  164. }
  165. if (segmentationType === SegmentType.CUSTOM) {
  166. const ruleObj = {
  167. pre_processing_rules: rules,
  168. segmentation: {
  169. separator: segmentIdentifier === '\\n' ? '\n' : segmentIdentifier,
  170. max_tokens: max,
  171. },
  172. }
  173. processRule.rules = ruleObj
  174. }
  175. return processRule
  176. }
  177. const getNotionInfo = () => {
  178. const workspacesMap = groupBy(notionPages, 'workspace_id')
  179. const workspaces = Object.keys(workspacesMap).map((workspaceId) => {
  180. return {
  181. workspaceId,
  182. pages: workspacesMap[workspaceId],
  183. }
  184. })
  185. return workspaces.map((workspace) => {
  186. return {
  187. workspace_id: workspace.workspaceId,
  188. pages: workspace.pages.map((page) => {
  189. const { page_id, page_name, page_icon, type } = page
  190. return {
  191. page_id,
  192. page_name,
  193. page_icon,
  194. type,
  195. }
  196. }),
  197. }
  198. }) as NotionInfo[]
  199. }
  200. const getFileIndexingEstimateParams = (docForm: DocForm) => {
  201. let params
  202. if (dataSourceType === DataSourceType.FILE) {
  203. params = {
  204. info_list: {
  205. data_source_type: dataSourceType,
  206. file_info_list: {
  207. file_ids: files.map(file => file.id),
  208. },
  209. },
  210. indexing_technique: getIndexing_technique(),
  211. process_rule: getProcessRule(),
  212. doc_form: docForm,
  213. }
  214. }
  215. if (dataSourceType === DataSourceType.NOTION) {
  216. params = {
  217. info_list: {
  218. data_source_type: dataSourceType,
  219. notion_info_list: getNotionInfo(),
  220. },
  221. indexing_technique: getIndexing_technique(),
  222. process_rule: getProcessRule(),
  223. doc_form: docForm,
  224. }
  225. }
  226. return params
  227. }
  228. const getCreationParams = () => {
  229. let params
  230. if (isSetting) {
  231. params = {
  232. original_document_id: documentDetail?.id,
  233. doc_form: docForm,
  234. process_rule: getProcessRule(),
  235. } as CreateDocumentReq
  236. }
  237. else {
  238. params = {
  239. data_source: {
  240. type: dataSourceType,
  241. info_list: {
  242. data_source_type: dataSourceType,
  243. },
  244. },
  245. indexing_technique: getIndexing_technique(),
  246. process_rule: getProcessRule(),
  247. doc_form: docForm,
  248. } as CreateDocumentReq
  249. if (dataSourceType === DataSourceType.FILE) {
  250. params.data_source.info_list.file_info_list = {
  251. file_ids: files.map(file => file.id),
  252. }
  253. }
  254. if (dataSourceType === DataSourceType.NOTION)
  255. params.data_source.info_list.notion_info_list = getNotionInfo()
  256. }
  257. return params
  258. }
  259. const getRules = async () => {
  260. try {
  261. const res = await fetchDefaultProcessRule({ url: '/datasets/process-rule' })
  262. const separator = res.rules.segmentation.separator
  263. setSegmentIdentifier(separator === '\n' ? '\\n' : separator || '\\n')
  264. setMax(res.rules.segmentation.max_tokens)
  265. setRules(res.rules.pre_processing_rules)
  266. setDefaultConfig(res.rules)
  267. }
  268. catch (err) {
  269. console.log(err)
  270. }
  271. }
  272. const getRulesFromDetail = () => {
  273. if (documentDetail) {
  274. const rules = documentDetail.dataset_process_rule.rules
  275. const separator = rules.segmentation.separator
  276. const max = rules.segmentation.max_tokens
  277. setSegmentIdentifier(separator === '\n' ? '\\n' : separator || '\\n')
  278. setMax(max)
  279. setRules(rules.pre_processing_rules)
  280. setDefaultConfig(rules)
  281. }
  282. }
  283. const getDefaultMode = () => {
  284. if (documentDetail)
  285. setSegmentationType(documentDetail.dataset_process_rule.mode)
  286. }
  287. const createHandle = async () => {
  288. try {
  289. let res
  290. const params = getCreationParams()
  291. if (!datasetId) {
  292. res = await createFirstDocument({
  293. body: params,
  294. })
  295. updateIndexingTypeCache && updateIndexingTypeCache(indexType)
  296. updateResultCache && updateResultCache(res)
  297. }
  298. else {
  299. res = await createDocument({
  300. datasetId,
  301. body: params,
  302. })
  303. updateIndexingTypeCache && updateIndexingTypeCache(indexType)
  304. updateResultCache && updateResultCache(res)
  305. }
  306. if (mutateDatasetRes)
  307. mutateDatasetRes()
  308. onStepChange && onStepChange(+1)
  309. isSetting && onSave && onSave()
  310. }
  311. catch (err) {
  312. Toast.notify({
  313. type: 'error',
  314. message: `${err}`,
  315. })
  316. }
  317. }
  318. const handleSwitch = (state: boolean) => {
  319. if (state)
  320. setDocForm(DocForm.QA)
  321. else
  322. setDocForm(DocForm.TEXT)
  323. }
  324. const changeToEconomicalType = () => {
  325. if (!hasSetIndexType) {
  326. setIndexType(IndexingType.ECONOMICAL)
  327. setDocForm(DocForm.TEXT)
  328. }
  329. }
  330. const previewSwitch = async () => {
  331. setPreviewSwitched(true)
  332. if (segmentationType === SegmentType.AUTO)
  333. setAutomaticFileIndexingEstimate(null)
  334. else
  335. setCustomFileIndexingEstimate(null)
  336. await fetchFileIndexingEstimate(DocForm.QA)
  337. }
  338. useEffect(() => {
  339. // fetch rules
  340. if (!isSetting) {
  341. getRules()
  342. }
  343. else {
  344. getRulesFromDetail()
  345. getDefaultMode()
  346. }
  347. }, [])
  348. useEffect(() => {
  349. scrollRef.current?.addEventListener('scroll', scrollHandle)
  350. return () => {
  351. scrollRef.current?.removeEventListener('scroll', scrollHandle)
  352. }
  353. }, [])
  354. useLayoutEffect(() => {
  355. if (showPreview) {
  356. previewScrollRef.current?.addEventListener('scroll', previewScrollHandle)
  357. return () => {
  358. previewScrollRef.current?.removeEventListener('scroll', previewScrollHandle)
  359. }
  360. }
  361. }, [showPreview])
  362. useEffect(() => {
  363. if (indexingType === IndexingType.ECONOMICAL && docForm === DocForm.QA)
  364. setDocForm(DocForm.TEXT)
  365. }, [indexingType, docForm])
  366. useEffect(() => {
  367. // get indexing type by props
  368. if (indexingType)
  369. setIndexType(indexingType as IndexingType)
  370. else
  371. setIndexType(hasSetAPIKEY ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
  372. }, [hasSetAPIKEY, indexingType, datasetId])
  373. useEffect(() => {
  374. if (segmentationType === SegmentType.AUTO) {
  375. setAutomaticFileIndexingEstimate(null)
  376. setShowPreview()
  377. fetchFileIndexingEstimate()
  378. setPreviewSwitched(false)
  379. }
  380. else {
  381. hidePreview()
  382. setCustomFileIndexingEstimate(null)
  383. setPreviewSwitched(false)
  384. }
  385. }, [segmentationType, indexType])
  386. return (
  387. <div className='flex w-full h-full'>
  388. <div ref={scrollRef} className='relative h-full w-full overflow-y-scroll'>
  389. <div className={cn(s.pageHeader, scrolled && s.fixed)}>{t('datasetCreation.steps.two')}</div>
  390. <div className={cn(s.form)}>
  391. <div className={s.label}>{t('datasetCreation.stepTwo.segmentation')}</div>
  392. <div className='max-w-[640px]'>
  393. <div
  394. className={cn(
  395. s.radioItem,
  396. s.segmentationItem,
  397. segmentationType === SegmentType.AUTO && s.active,
  398. )}
  399. onClick={() => setSegmentationType(SegmentType.AUTO)}
  400. >
  401. <span className={cn(s.typeIcon, s.auto)} />
  402. <span className={cn(s.radio)} />
  403. <div className={s.typeHeader}>
  404. <div className={s.title}>{t('datasetCreation.stepTwo.auto')}</div>
  405. <div className={s.tip}>{t('datasetCreation.stepTwo.autoDescription')}</div>
  406. </div>
  407. </div>
  408. <div
  409. className={cn(
  410. s.radioItem,
  411. s.segmentationItem,
  412. segmentationType === SegmentType.CUSTOM && s.active,
  413. segmentationType === SegmentType.CUSTOM && s.custom,
  414. )}
  415. onClick={() => setSegmentationType(SegmentType.CUSTOM)}
  416. >
  417. <span className={cn(s.typeIcon, s.customize)} />
  418. <span className={cn(s.radio)} />
  419. <div className={s.typeHeader}>
  420. <div className={s.title}>{t('datasetCreation.stepTwo.custom')}</div>
  421. <div className={s.tip}>{t('datasetCreation.stepTwo.customDescription')}</div>
  422. </div>
  423. {segmentationType === SegmentType.CUSTOM && (
  424. <div className={s.typeFormBody}>
  425. <div className={s.formRow}>
  426. <div className='w-full'>
  427. <div className={s.label}>{t('datasetCreation.stepTwo.separator')}</div>
  428. <input
  429. type="text"
  430. className={s.input}
  431. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={segmentIdentifier}
  432. onChange={e => setSegmentIdentifier(e.target.value)}
  433. />
  434. </div>
  435. </div>
  436. <div className={s.formRow}>
  437. <div className='w-full'>
  438. <div className={s.label}>{t('datasetCreation.stepTwo.maxLength')}</div>
  439. <input
  440. type="number"
  441. className={s.input}
  442. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={max}
  443. onChange={e => setMax(Number(e.target.value))}
  444. />
  445. </div>
  446. </div>
  447. <div className={s.formRow}>
  448. <div className='w-full'>
  449. <div className={s.label}>{t('datasetCreation.stepTwo.rules')}</div>
  450. {rules.map(rule => (
  451. <div key={rule.id} className={s.ruleItem}>
  452. <input id={rule.id} type="checkbox" defaultChecked={rule.enabled} onChange={() => ruleChangeHandle(rule.id)} className="w-4 h-4 rounded border-gray-300 text-blue-700 focus:ring-blue-700" />
  453. <label htmlFor={rule.id} className="ml-2 text-sm font-normal cursor-pointer text-gray-800">{getRuleName(rule.id)}</label>
  454. </div>
  455. ))}
  456. </div>
  457. </div>
  458. <div className={s.formFooter}>
  459. <Button type="primary" className={cn(s.button, '!h-8 text-primary-600')} onClick={confirmChangeCustomConfig}>{t('datasetCreation.stepTwo.preview')}</Button>
  460. <Button className={cn(s.button, 'ml-2 !h-8')} onClick={resetRules}>{t('datasetCreation.stepTwo.reset')}</Button>
  461. </div>
  462. </div>
  463. )}
  464. </div>
  465. </div>
  466. <div className={s.label}>{t('datasetCreation.stepTwo.indexMode')}</div>
  467. <div className='max-w-[640px]'>
  468. <div className='flex items-center gap-3'>
  469. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.QUALIFIED)) && (
  470. <div
  471. className={cn(
  472. s.radioItem,
  473. s.indexItem,
  474. !hasSetAPIKEY && s.disabled,
  475. !hasSetIndexType && indexType === IndexingType.QUALIFIED && s.active,
  476. hasSetIndexType && s.disabled,
  477. hasSetIndexType && '!w-full',
  478. )}
  479. onClick={() => {
  480. if (hasSetAPIKEY)
  481. setIndexType(IndexingType.QUALIFIED)
  482. }}
  483. >
  484. <span className={cn(s.typeIcon, s.qualified)} />
  485. {!hasSetIndexType && <span className={cn(s.radio)} />}
  486. <div className={s.typeHeader}>
  487. <div className={s.title}>
  488. {t('datasetCreation.stepTwo.qualified')}
  489. {!hasSetIndexType && <span className={s.recommendTag}>{t('datasetCreation.stepTwo.recommend')}</span>}
  490. </div>
  491. <div className={s.tip}>{t('datasetCreation.stepTwo.qualifiedTip')}</div>
  492. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  493. {
  494. fileIndexingEstimate
  495. ? (
  496. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.tokens)} tokens(<span className='text-yellow-500'>${formatNumber(fileIndexingEstimate.total_price)}</span>)</div>
  497. )
  498. : (
  499. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  500. )
  501. }
  502. </div>
  503. {!hasSetAPIKEY && (
  504. <div className={s.warningTip}>
  505. <span>{t('datasetCreation.stepTwo.warning')}&nbsp;</span>
  506. <span className={s.click} onClick={onSetting}>{t('datasetCreation.stepTwo.click')}</span>
  507. </div>
  508. )}
  509. </div>
  510. )}
  511. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.ECONOMICAL)) && (
  512. <div
  513. className={cn(
  514. s.radioItem,
  515. s.indexItem,
  516. !hasSetIndexType && indexType === IndexingType.ECONOMICAL && s.active,
  517. hasSetIndexType && s.disabled,
  518. hasSetIndexType && '!w-full',
  519. )}
  520. onClick={changeToEconomicalType}
  521. >
  522. <span className={cn(s.typeIcon, s.economical)} />
  523. {!hasSetIndexType && <span className={cn(s.radio)} />}
  524. <div className={s.typeHeader}>
  525. <div className={s.title}>{t('datasetCreation.stepTwo.economical')}</div>
  526. <div className={s.tip}>{t('datasetCreation.stepTwo.economicalTip')}</div>
  527. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  528. <div className='text-xs font-medium text-gray-800'>0 tokens</div>
  529. </div>
  530. </div>
  531. )}
  532. </div>
  533. {hasSetIndexType && (
  534. <div className='mt-2 text-xs text-gray-500 font-medium'>
  535. {t('datasetCreation.stepTwo.indexSettedTip')}
  536. <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
  537. </div>
  538. )}
  539. {indexType === IndexingType.QUALIFIED && (
  540. <div className='flex justify-between items-center mt-3 px-5 py-4 rounded-xl bg-gray-50 border border-gray-100'>
  541. <div className='flex justify-center items-center w-8 h-8 rounded-lg bg-indigo-50'>
  542. <MessageChatSquare className='w-4 h-4' />
  543. </div>
  544. <div className='grow mx-3'>
  545. <div className='mb-[2px] text-md font-medium text-gray-900'>{t('datasetCreation.stepTwo.QATitle')}</div>
  546. <div className='text-[13px] leading-[18px] text-gray-500'>{t('datasetCreation.stepTwo.QATip')}</div>
  547. </div>
  548. <div className='shrink-0'>
  549. <Switch
  550. defaultValue={docForm === DocForm.QA}
  551. onChange={handleSwitch}
  552. size='md'
  553. />
  554. </div>
  555. </div>
  556. )}
  557. <div className={s.source}>
  558. <div className={s.sourceContent}>
  559. {dataSourceType === DataSourceType.FILE && (
  560. <>
  561. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.fileSource')}</div>
  562. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  563. <span className={cn(s.fileIcon, files.length && s[files[0].extension])} />
  564. {getFileName(files[0].name || '')}
  565. {files.length > 1 && (
  566. <span className={s.sourceCount}>
  567. <span>{t('datasetCreation.stepTwo.other')}</span>
  568. <span>{files.length - 1}</span>
  569. <span>{t('datasetCreation.stepTwo.fileUnit')}</span>
  570. </span>
  571. )}
  572. </div>
  573. </>
  574. )}
  575. {dataSourceType === DataSourceType.NOTION && (
  576. <>
  577. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.notionSource')}</div>
  578. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  579. <NotionIcon
  580. className='shrink-0 mr-1'
  581. type='page'
  582. src={notionPages[0]?.page_icon}
  583. />
  584. {notionPages[0]?.page_name}
  585. {notionPages.length > 1 && (
  586. <span className={s.sourceCount}>
  587. <span>{t('datasetCreation.stepTwo.other')}</span>
  588. <span>{notionPages.length - 1}</span>
  589. <span>{t('datasetCreation.stepTwo.notionUnit')}</span>
  590. </span>
  591. )}
  592. </div>
  593. </>
  594. )}
  595. </div>
  596. <div className={s.divider} />
  597. <div className={s.segmentCount}>
  598. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateSegment')}</div>
  599. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  600. {
  601. fileIndexingEstimate
  602. ? (
  603. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.total_segments)} </div>
  604. )
  605. : (
  606. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  607. )
  608. }
  609. </div>
  610. </div>
  611. </div>
  612. {!isSetting
  613. ? (
  614. <div className='flex items-center mt-8 py-2'>
  615. <Button onClick={() => onStepChange && onStepChange(-1)}>{t('datasetCreation.stepTwo.lastStep')}</Button>
  616. <div className={s.divider} />
  617. <Button type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.nextStep')}</Button>
  618. </div>
  619. )
  620. : (
  621. <div className='flex items-center mt-8 py-2'>
  622. <Button type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.save')}</Button>
  623. <Button className='ml-2' onClick={onCancel}>{t('datasetCreation.stepTwo.cancel')}</Button>
  624. </div>
  625. )}
  626. </div>
  627. </div>
  628. </div>
  629. {(showPreview)
  630. ? (
  631. <div ref={previewScrollRef} className={cn(s.previewWrap, 'relativeh-full overflow-y-scroll border-l border-[#F2F4F7]')}>
  632. <div className={cn(s.previewHeader, previewScrolled && `${s.fixed} pb-3`)}>
  633. <div className='flex items-center justify-between px-8'>
  634. <div className='grow flex items-center'>
  635. <div>{t('datasetCreation.stepTwo.previewTitle')}</div>
  636. {docForm === DocForm.QA && !previewSwitched && (
  637. <Button className='ml-2 !h-[26px] !py-[3px] !px-2 !text-xs !font-medium !text-primary-600' onClick={previewSwitch}>{t('datasetCreation.stepTwo.previewButton')}</Button>
  638. )}
  639. </div>
  640. <div className='flex items-center justify-center w-6 h-6 cursor-pointer' onClick={hidePreview}>
  641. <XMarkIcon className='h-4 w-4'></XMarkIcon>
  642. </div>
  643. </div>
  644. {docForm === DocForm.QA && !previewSwitched && (
  645. <div className='px-8 pr-12 text-xs text-gray-500'>
  646. <span>{t('datasetCreation.stepTwo.previewSwitchTipStart')}</span>
  647. <span className='text-amber-600'>{t('datasetCreation.stepTwo.previewSwitchTipEnd')}</span>
  648. </div>
  649. )}
  650. </div>
  651. <div className='my-4 px-8 space-y-4'>
  652. {previewSwitched && docForm === DocForm.QA && fileIndexingEstimate?.qa_preview && (
  653. <>
  654. {fileIndexingEstimate?.qa_preview.map((item, index) => (
  655. <PreviewItem type={PreviewType.QA} key={item.question} qa={item} index={index + 1} />
  656. ))}
  657. </>
  658. )}
  659. {(docForm === DocForm.TEXT || !previewSwitched) && fileIndexingEstimate?.preview && (
  660. <>
  661. {fileIndexingEstimate?.preview.map((item, index) => (
  662. <PreviewItem type={PreviewType.TEXT} key={item} content={item} index={index + 1} />
  663. ))}
  664. </>
  665. )}
  666. {previewSwitched && docForm === DocForm.QA && !fileIndexingEstimate?.qa_preview && (
  667. <div className='flex items-center justify-center h-[200px]'>
  668. <Loading type='area' />
  669. </div>
  670. )}
  671. {!previewSwitched && !fileIndexingEstimate?.preview && (
  672. <div className='flex items-center justify-center h-[200px]'>
  673. <Loading type='area' />
  674. </div>
  675. )}
  676. </div>
  677. </div>
  678. )
  679. : (<div className={cn(s.sideTip)}>
  680. <div className={s.tipCard}>
  681. <span className={s.icon} />
  682. <div className={s.title}>{t('datasetCreation.stepTwo.sideTipTitle')}</div>
  683. <div className={s.content}>
  684. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP1')}</p>
  685. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP2')}</p>
  686. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP3')}</p>
  687. <p>{t('datasetCreation.stepTwo.sideTipP4')}</p>
  688. </div>
  689. </div>
  690. </div>)}
  691. </div>
  692. )
  693. }
  694. export default StepTwo