index.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. if (isCreating)
  299. return
  300. setIsCreating(true)
  301. try {
  302. let res
  303. const params = getCreationParams()
  304. setIsCreating(true)
  305. if (!datasetId) {
  306. res = await createFirstDocument({
  307. body: params,
  308. })
  309. updateIndexingTypeCache && updateIndexingTypeCache(indexType)
  310. updateResultCache && updateResultCache(res)
  311. }
  312. else {
  313. res = await createDocument({
  314. datasetId,
  315. body: params,
  316. })
  317. updateIndexingTypeCache && updateIndexingTypeCache(indexType)
  318. updateResultCache && updateResultCache(res)
  319. }
  320. if (mutateDatasetRes)
  321. mutateDatasetRes()
  322. onStepChange && onStepChange(+1)
  323. isSetting && onSave && onSave()
  324. }
  325. catch (err) {
  326. Toast.notify({
  327. type: 'error',
  328. message: `${err}`,
  329. })
  330. }
  331. finally {
  332. setIsCreating(false)
  333. }
  334. }
  335. const handleSwitch = (state: boolean) => {
  336. if (state)
  337. setDocForm(DocForm.QA)
  338. else
  339. setDocForm(DocForm.TEXT)
  340. }
  341. const handleSelect = (language: string) => {
  342. setDocLanguage(language)
  343. }
  344. const changeToEconomicalType = () => {
  345. if (!hasSetIndexType) {
  346. setIndexType(IndexingType.ECONOMICAL)
  347. setDocForm(DocForm.TEXT)
  348. }
  349. }
  350. const previewSwitch = async () => {
  351. setPreviewSwitched(true)
  352. if (segmentationType === SegmentType.AUTO)
  353. setAutomaticFileIndexingEstimate(null)
  354. else
  355. setCustomFileIndexingEstimate(null)
  356. await fetchFileIndexingEstimate(DocForm.QA)
  357. }
  358. useEffect(() => {
  359. // fetch rules
  360. if (!isSetting) {
  361. getRules()
  362. }
  363. else {
  364. getRulesFromDetail()
  365. getDefaultMode()
  366. }
  367. }, [])
  368. useEffect(() => {
  369. scrollRef.current?.addEventListener('scroll', scrollHandle)
  370. return () => {
  371. scrollRef.current?.removeEventListener('scroll', scrollHandle)
  372. }
  373. }, [])
  374. useLayoutEffect(() => {
  375. if (showPreview) {
  376. previewScrollRef.current?.addEventListener('scroll', previewScrollHandle)
  377. return () => {
  378. previewScrollRef.current?.removeEventListener('scroll', previewScrollHandle)
  379. }
  380. }
  381. }, [showPreview])
  382. useEffect(() => {
  383. if (indexingType === IndexingType.ECONOMICAL && docForm === DocForm.QA)
  384. setDocForm(DocForm.TEXT)
  385. }, [indexingType, docForm])
  386. useEffect(() => {
  387. // get indexing type by props
  388. if (indexingType)
  389. setIndexType(indexingType as IndexingType)
  390. else
  391. setIndexType(hasSetAPIKEY ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
  392. }, [hasSetAPIKEY, indexingType, datasetId])
  393. useEffect(() => {
  394. if (segmentationType === SegmentType.AUTO) {
  395. setAutomaticFileIndexingEstimate(null)
  396. setShowPreview()
  397. fetchFileIndexingEstimate()
  398. setPreviewSwitched(false)
  399. }
  400. else {
  401. hidePreview()
  402. setCustomFileIndexingEstimate(null)
  403. setPreviewSwitched(false)
  404. }
  405. }, [segmentationType, indexType])
  406. return (
  407. <div className='flex w-full h-full'>
  408. <div ref={scrollRef} className='relative h-full w-full overflow-y-scroll'>
  409. <div className={cn(s.pageHeader, scrolled && s.fixed)}>{t('datasetCreation.steps.two')}</div>
  410. <div className={cn(s.form)}>
  411. <div className={s.label}>{t('datasetCreation.stepTwo.segmentation')}</div>
  412. <div className='max-w-[640px]'>
  413. <div
  414. className={cn(
  415. s.radioItem,
  416. s.segmentationItem,
  417. segmentationType === SegmentType.AUTO && s.active,
  418. )}
  419. onClick={() => setSegmentationType(SegmentType.AUTO)}
  420. >
  421. <span className={cn(s.typeIcon, s.auto)} />
  422. <span className={cn(s.radio)} />
  423. <div className={s.typeHeader}>
  424. <div className={s.title}>{t('datasetCreation.stepTwo.auto')}</div>
  425. <div className={s.tip}>{t('datasetCreation.stepTwo.autoDescription')}</div>
  426. </div>
  427. </div>
  428. <div
  429. className={cn(
  430. s.radioItem,
  431. s.segmentationItem,
  432. segmentationType === SegmentType.CUSTOM && s.active,
  433. segmentationType === SegmentType.CUSTOM && s.custom,
  434. )}
  435. onClick={() => setSegmentationType(SegmentType.CUSTOM)}
  436. >
  437. <span className={cn(s.typeIcon, s.customize)} />
  438. <span className={cn(s.radio)} />
  439. <div className={s.typeHeader}>
  440. <div className={s.title}>{t('datasetCreation.stepTwo.custom')}</div>
  441. <div className={s.tip}>{t('datasetCreation.stepTwo.customDescription')}</div>
  442. </div>
  443. {segmentationType === SegmentType.CUSTOM && (
  444. <div className={s.typeFormBody}>
  445. <div className={s.formRow}>
  446. <div className='w-full'>
  447. <div className={s.label}>{t('datasetCreation.stepTwo.separator')}</div>
  448. <input
  449. type="text"
  450. className={s.input}
  451. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={segmentIdentifier}
  452. onChange={e => setSegmentIdentifier(e.target.value)}
  453. />
  454. </div>
  455. </div>
  456. <div className={s.formRow}>
  457. <div className='w-full'>
  458. <div className={s.label}>{t('datasetCreation.stepTwo.maxLength')}</div>
  459. <input
  460. type="number"
  461. className={s.input}
  462. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''}
  463. value={max}
  464. min={1}
  465. onChange={e => setMax(parseInt(e.target.value.replace(/^0+/, ''), 10))}
  466. />
  467. </div>
  468. </div>
  469. <div className={s.formRow}>
  470. <div className='w-full'>
  471. <div className={s.label}>{t('datasetCreation.stepTwo.rules')}</div>
  472. {rules.map(rule => (
  473. <div key={rule.id} className={s.ruleItem}>
  474. <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" />
  475. <label htmlFor={rule.id} className="ml-2 text-sm font-normal cursor-pointer text-gray-800">{getRuleName(rule.id)}</label>
  476. </div>
  477. ))}
  478. </div>
  479. </div>
  480. <div className={s.formFooter}>
  481. <Button type="primary" className={cn(s.button, '!h-8 text-primary-600')} onClick={confirmChangeCustomConfig}>{t('datasetCreation.stepTwo.preview')}</Button>
  482. <Button className={cn(s.button, 'ml-2 !h-8')} onClick={resetRules}>{t('datasetCreation.stepTwo.reset')}</Button>
  483. </div>
  484. </div>
  485. )}
  486. </div>
  487. </div>
  488. <div className={s.label}>{t('datasetCreation.stepTwo.indexMode')}</div>
  489. <div className='max-w-[640px]'>
  490. <div className='flex items-center gap-3'>
  491. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.QUALIFIED)) && (
  492. <div
  493. className={cn(
  494. s.radioItem,
  495. s.indexItem,
  496. !hasSetAPIKEY && s.disabled,
  497. !hasSetIndexType && indexType === IndexingType.QUALIFIED && s.active,
  498. hasSetIndexType && s.disabled,
  499. hasSetIndexType && '!w-full',
  500. )}
  501. onClick={() => {
  502. if (hasSetAPIKEY)
  503. setIndexType(IndexingType.QUALIFIED)
  504. }}
  505. >
  506. <span className={cn(s.typeIcon, s.qualified)} />
  507. {!hasSetIndexType && <span className={cn(s.radio)} />}
  508. <div className={s.typeHeader}>
  509. <div className={s.title}>
  510. {t('datasetCreation.stepTwo.qualified')}
  511. {!hasSetIndexType && <span className={s.recommendTag}>{t('datasetCreation.stepTwo.recommend')}</span>}
  512. </div>
  513. <div className={s.tip}>{t('datasetCreation.stepTwo.qualifiedTip')}</div>
  514. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  515. {
  516. fileIndexingEstimate
  517. ? (
  518. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.tokens)} tokens(<span className='text-yellow-500'>${formatNumber(fileIndexingEstimate.total_price)}</span>)</div>
  519. )
  520. : (
  521. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  522. )
  523. }
  524. </div>
  525. {!hasSetAPIKEY && (
  526. <div className={s.warningTip}>
  527. <span>{t('datasetCreation.stepTwo.warning')}&nbsp;</span>
  528. <span className={s.click} onClick={onSetting}>{t('datasetCreation.stepTwo.click')}</span>
  529. </div>
  530. )}
  531. </div>
  532. )}
  533. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.ECONOMICAL)) && (
  534. <div
  535. className={cn(
  536. s.radioItem,
  537. s.indexItem,
  538. !hasSetIndexType && indexType === IndexingType.ECONOMICAL && s.active,
  539. hasSetIndexType && s.disabled,
  540. hasSetIndexType && '!w-full',
  541. )}
  542. onClick={changeToEconomicalType}
  543. >
  544. <span className={cn(s.typeIcon, s.economical)} />
  545. {!hasSetIndexType && <span className={cn(s.radio)} />}
  546. <div className={s.typeHeader}>
  547. <div className={s.title}>{t('datasetCreation.stepTwo.economical')}</div>
  548. <div className={s.tip}>{t('datasetCreation.stepTwo.economicalTip')}</div>
  549. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  550. <div className='text-xs font-medium text-gray-800'>0 tokens</div>
  551. </div>
  552. </div>
  553. )}
  554. </div>
  555. {hasSetIndexType && (
  556. <div className='mt-2 text-xs text-gray-500 font-medium'>
  557. {t('datasetCreation.stepTwo.indexSettedTip')}
  558. <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
  559. </div>
  560. )}
  561. {IS_CE_EDITION && indexType === IndexingType.QUALIFIED && (
  562. <div className='mt-3 rounded-xl bg-gray-50 border border-gray-100'>
  563. <div className='flex justify-between items-center px-5 py-4'>
  564. <div className='flex justify-center items-center w-8 h-8 rounded-lg bg-indigo-50'>
  565. <MessageChatSquare className='w-4 h-4' />
  566. </div>
  567. <div className='grow mx-3'>
  568. <div className='mb-[2px] text-md font-medium text-gray-900'>{t('datasetCreation.stepTwo.QATitle')}</div>
  569. <div className='inline-flex items-center text-[13px] leading-[18px] text-gray-500'>
  570. <span className='pr-1'>{t('datasetCreation.stepTwo.QALanguage')}</span>
  571. <LanguageSelect currentLanguage={docLanguage} onSelect={handleSelect} />
  572. </div>
  573. </div>
  574. <div className='shrink-0'>
  575. <Switch
  576. defaultValue={docForm === DocForm.QA}
  577. onChange={handleSwitch}
  578. size='md'
  579. />
  580. </div>
  581. </div>
  582. {docForm === DocForm.QA && !QATipHide && (
  583. <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'>
  584. {t('datasetCreation.stepTwo.QATip')}
  585. <XClose className='w-4 h-4 text-gray-500 cursor-pointer' onClick={() => setQATipHide(true)} />
  586. </div>
  587. )}
  588. </div>
  589. )}
  590. <div className={s.source}>
  591. <div className={s.sourceContent}>
  592. {dataSourceType === DataSourceType.FILE && (
  593. <>
  594. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.fileSource')}</div>
  595. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  596. <span className={cn(s.fileIcon, files.length && s[files[0].extension || ''])} />
  597. {getFileName(files[0].name || '')}
  598. {files.length > 1 && (
  599. <span className={s.sourceCount}>
  600. <span>{t('datasetCreation.stepTwo.other')}</span>
  601. <span>{files.length - 1}</span>
  602. <span>{t('datasetCreation.stepTwo.fileUnit')}</span>
  603. </span>
  604. )}
  605. </div>
  606. </>
  607. )}
  608. {dataSourceType === DataSourceType.NOTION && (
  609. <>
  610. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.notionSource')}</div>
  611. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  612. <NotionIcon
  613. className='shrink-0 mr-1'
  614. type='page'
  615. src={notionPages[0]?.page_icon}
  616. />
  617. {notionPages[0]?.page_name}
  618. {notionPages.length > 1 && (
  619. <span className={s.sourceCount}>
  620. <span>{t('datasetCreation.stepTwo.other')}</span>
  621. <span>{notionPages.length - 1}</span>
  622. <span>{t('datasetCreation.stepTwo.notionUnit')}</span>
  623. </span>
  624. )}
  625. </div>
  626. </>
  627. )}
  628. </div>
  629. <div className={s.divider} />
  630. <div className={s.segmentCount}>
  631. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateSegment')}</div>
  632. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  633. {
  634. fileIndexingEstimate
  635. ? (
  636. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.total_segments)} </div>
  637. )
  638. : (
  639. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  640. )
  641. }
  642. </div>
  643. </div>
  644. </div>
  645. {!isSetting
  646. ? (
  647. <div className='flex items-center mt-8 py-2'>
  648. <Button onClick={() => onStepChange && onStepChange(-1)}>{t('datasetCreation.stepTwo.lastStep')}</Button>
  649. <div className={s.divider} />
  650. <Button loading={isCreating} type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.nextStep')}</Button>
  651. </div>
  652. )
  653. : (
  654. <div className='flex items-center mt-8 py-2'>
  655. <Button loading={isCreating} type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.save')}</Button>
  656. <Button className='ml-2' onClick={onCancel}>{t('datasetCreation.stepTwo.cancel')}</Button>
  657. </div>
  658. )}
  659. </div>
  660. </div>
  661. </div>
  662. {(showPreview)
  663. ? (
  664. <div ref={previewScrollRef} className={cn(s.previewWrap, 'relativeh-full overflow-y-scroll border-l border-[#F2F4F7]')}>
  665. <div className={cn(s.previewHeader, previewScrolled && `${s.fixed} pb-3`)}>
  666. <div className='flex items-center justify-between px-8'>
  667. <div className='grow flex items-center'>
  668. <div>{t('datasetCreation.stepTwo.previewTitle')}</div>
  669. {docForm === DocForm.QA && !previewSwitched && (
  670. <Button className='ml-2 !h-[26px] !py-[3px] !px-2 !text-xs !font-medium !text-primary-600' onClick={previewSwitch}>{t('datasetCreation.stepTwo.previewButton')}</Button>
  671. )}
  672. </div>
  673. <div className='flex items-center justify-center w-6 h-6 cursor-pointer' onClick={hidePreview}>
  674. <XMarkIcon className='h-4 w-4'></XMarkIcon>
  675. </div>
  676. </div>
  677. {docForm === DocForm.QA && !previewSwitched && (
  678. <div className='px-8 pr-12 text-xs text-gray-500'>
  679. <span>{t('datasetCreation.stepTwo.previewSwitchTipStart')}</span>
  680. <span className='text-amber-600'>{t('datasetCreation.stepTwo.previewSwitchTipEnd')}</span>
  681. </div>
  682. )}
  683. </div>
  684. <div className='my-4 px-8 space-y-4'>
  685. {previewSwitched && docForm === DocForm.QA && fileIndexingEstimate?.qa_preview && (
  686. <>
  687. {fileIndexingEstimate?.qa_preview.map((item, index) => (
  688. <PreviewItem type={PreviewType.QA} key={item.question} qa={item} index={index + 1} />
  689. ))}
  690. </>
  691. )}
  692. {(docForm === DocForm.TEXT || !previewSwitched) && fileIndexingEstimate?.preview && (
  693. <>
  694. {fileIndexingEstimate?.preview.map((item, index) => (
  695. <PreviewItem type={PreviewType.TEXT} key={item} content={item} index={index + 1} />
  696. ))}
  697. </>
  698. )}
  699. {previewSwitched && docForm === DocForm.QA && !fileIndexingEstimate?.qa_preview && (
  700. <div className='flex items-center justify-center h-[200px]'>
  701. <Loading type='area' />
  702. </div>
  703. )}
  704. {!previewSwitched && !fileIndexingEstimate?.preview && (
  705. <div className='flex items-center justify-center h-[200px]'>
  706. <Loading type='area' />
  707. </div>
  708. )}
  709. </div>
  710. </div>
  711. )
  712. : (<div className={cn(s.sideTip)}>
  713. <div className={s.tipCard}>
  714. <span className={s.icon} />
  715. <div className={s.title}>{t('datasetCreation.stepTwo.sideTipTitle')}</div>
  716. <div className={s.content}>
  717. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP1')}</p>
  718. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP2')}</p>
  719. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP3')}</p>
  720. <p>{t('datasetCreation.stepTwo.sideTipP4')}</p>
  721. </div>
  722. </div>
  723. </div>)}
  724. </div>
  725. )
  726. }
  727. export default StepTwo