index.tsx 29 KB

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