index.tsx 29 KB

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