index.tsx 30 KB

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