index.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /* eslint-disable no-mixed-operators */
  2. 'use client'
  3. import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useBoolean } from 'ahooks'
  6. import { XMarkIcon } from '@heroicons/react/20/solid'
  7. import cn from 'classnames'
  8. import Link from 'next/link'
  9. import PreviewItem from './preview-item'
  10. import s from './index.module.css'
  11. import type { CreateDocumentReq, File, FullDocumentDetail, FileIndexingEstimateResponse as IndexingEstimateResponse, PreProcessingRule, Rules, createDocumentResponse } from '@/models/datasets'
  12. import {
  13. createDocument,
  14. createFirstDocument,
  15. fetchFileIndexingEstimate as didFetchFileIndexingEstimate,
  16. fetchDefaultProcessRule,
  17. } from '@/service/datasets'
  18. import Button from '@/app/components/base/button'
  19. import Loading from '@/app/components/base/loading'
  20. import Toast from '@/app/components/base/toast'
  21. import { formatNumber } from '@/utils/format'
  22. type StepTwoProps = {
  23. isSetting?: boolean
  24. documentDetail?: FullDocumentDetail
  25. hasSetAPIKEY: boolean
  26. onSetting: () => void
  27. datasetId?: string
  28. indexingType?: string
  29. file?: File
  30. onStepChange?: (delta: number) => void
  31. updateIndexingTypeCache?: (type: string) => void
  32. updateResultCache?: (res: createDocumentResponse) => void
  33. onSave?: () => void
  34. onCancel?: () => void
  35. }
  36. enum SegmentType {
  37. AUTO = 'automatic',
  38. CUSTOM = 'custom',
  39. }
  40. enum IndexingType {
  41. QUALIFIED = 'high_quality',
  42. ECONOMICAL = 'economy',
  43. }
  44. const StepTwo = ({
  45. isSetting,
  46. documentDetail,
  47. hasSetAPIKEY,
  48. onSetting,
  49. datasetId,
  50. indexingType,
  51. file,
  52. onStepChange,
  53. updateIndexingTypeCache,
  54. updateResultCache,
  55. onSave,
  56. onCancel,
  57. }: StepTwoProps) => {
  58. const { t } = useTranslation()
  59. const scrollRef = useRef<HTMLDivElement>(null)
  60. const [scrolled, setScrolled] = useState(false)
  61. const previewScrollRef = useRef<HTMLDivElement>(null)
  62. const [previewScrolled, setPreviewScrolled] = useState(false)
  63. const [segmentationType, setSegmentationType] = useState<SegmentType>(SegmentType.AUTO)
  64. const [segmentIdentifier, setSegmentIdentifier] = useState('\\n')
  65. const [max, setMax] = useState(1000)
  66. const [rules, setRules] = useState<PreProcessingRule[]>([])
  67. const [defaultConfig, setDefaultConfig] = useState<Rules>()
  68. const hasSetIndexType = !!indexingType
  69. const [indexType, setIndexType] = useState<IndexingType>(
  70. indexingType
  71. || hasSetAPIKEY
  72. ? IndexingType.QUALIFIED
  73. : IndexingType.ECONOMICAL,
  74. )
  75. const [showPreview, { setTrue: setShowPreview, setFalse: hidePreview }] = useBoolean()
  76. const [customFileIndexingEstimate, setCustomFileIndexingEstimate] = useState<IndexingEstimateResponse | null>(null)
  77. const [automaticFileIndexingEstimate, setAutomaticFileIndexingEstimate] = useState<IndexingEstimateResponse | null>(null)
  78. const fileIndexingEstimate = (() => {
  79. return segmentationType === SegmentType.AUTO ? automaticFileIndexingEstimate : customFileIndexingEstimate
  80. })()
  81. const scrollHandle = (e: any) => {
  82. if (e.target.scrollTop > 0)
  83. setScrolled(true)
  84. else
  85. setScrolled(false)
  86. }
  87. const previewScrollHandle = (e: any) => {
  88. if (e.target.scrollTop > 0)
  89. setPreviewScrolled(true)
  90. else
  91. setPreviewScrolled(false)
  92. }
  93. const getFileName = (name: string) => {
  94. const arr = name.split('.')
  95. return arr.slice(0, -1).join('.')
  96. }
  97. const getRuleName = (key: string) => {
  98. if (key === 'remove_extra_spaces')
  99. return t('datasetCreation.stepTwo.removeExtraSpaces')
  100. if (key === 'remove_urls_emails')
  101. return t('datasetCreation.stepTwo.removeUrlEmails')
  102. if (key === 'remove_stopwords')
  103. return t('datasetCreation.stepTwo.removeStopwords')
  104. }
  105. const ruleChangeHandle = (id: string) => {
  106. const newRules = rules.map((rule) => {
  107. if (rule.id === id) {
  108. return {
  109. id: rule.id,
  110. enabled: !rule.enabled,
  111. }
  112. }
  113. return rule
  114. })
  115. setRules(newRules)
  116. }
  117. const resetRules = () => {
  118. if (defaultConfig) {
  119. setSegmentIdentifier(defaultConfig.segmentation.separator === '\n' ? '\\n' : defaultConfig.segmentation.separator || '\\n')
  120. setMax(defaultConfig.segmentation.max_tokens)
  121. setRules(defaultConfig.pre_processing_rules)
  122. }
  123. }
  124. const fetchFileIndexingEstimate = async () => {
  125. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  126. const res = await didFetchFileIndexingEstimate(getFileIndexingEstimateParams())
  127. if (segmentationType === SegmentType.CUSTOM)
  128. setCustomFileIndexingEstimate(res)
  129. else
  130. setAutomaticFileIndexingEstimate(res)
  131. }
  132. const confirmChangeCustomConfig = async () => {
  133. setCustomFileIndexingEstimate(null)
  134. setShowPreview()
  135. await fetchFileIndexingEstimate()
  136. }
  137. const getIndexing_technique = () => indexingType || indexType
  138. const getProcessRule = () => {
  139. const processRule: any = {
  140. rules: {}, // api will check this. It will be removed after api refactored.
  141. mode: segmentationType,
  142. }
  143. if (segmentationType === SegmentType.CUSTOM) {
  144. const ruleObj = {
  145. pre_processing_rules: rules,
  146. segmentation: {
  147. separator: segmentIdentifier === '\\n' ? '\n' : segmentIdentifier,
  148. max_tokens: max,
  149. },
  150. }
  151. processRule.rules = ruleObj
  152. }
  153. return processRule
  154. }
  155. const getFileIndexingEstimateParams = () => {
  156. const params = {
  157. file_id: file?.id,
  158. dataset_id: datasetId,
  159. indexing_technique: getIndexing_technique(),
  160. process_rule: getProcessRule(),
  161. }
  162. return params
  163. }
  164. const getCreationParams = () => {
  165. let params
  166. if (isSetting) {
  167. params = {
  168. original_document_id: documentDetail?.id,
  169. process_rule: getProcessRule(),
  170. } as CreateDocumentReq
  171. }
  172. else {
  173. params = {
  174. data_source: {
  175. type: 'upload_file',
  176. info: file?.id,
  177. name: file?.name,
  178. },
  179. indexing_technique: getIndexing_technique(),
  180. process_rule: getProcessRule(),
  181. } as CreateDocumentReq
  182. }
  183. return params
  184. }
  185. const getRules = async () => {
  186. try {
  187. const res = await fetchDefaultProcessRule({ url: '/datasets/process-rule' })
  188. const separator = res.rules.segmentation.separator
  189. setSegmentIdentifier(separator === '\n' ? '\\n' : separator || '\\n')
  190. setMax(res.rules.segmentation.max_tokens)
  191. setRules(res.rules.pre_processing_rules)
  192. setDefaultConfig(res.rules)
  193. }
  194. catch (err) {
  195. console.log(err)
  196. }
  197. }
  198. const getRulesFromDetail = () => {
  199. if (documentDetail) {
  200. const rules = documentDetail.dataset_process_rule.rules
  201. const separator = rules.segmentation.separator
  202. const max = rules.segmentation.max_tokens
  203. setSegmentIdentifier(separator === '\n' ? '\\n' : separator || '\\n')
  204. setMax(max)
  205. setRules(rules.pre_processing_rules)
  206. setDefaultConfig(rules)
  207. }
  208. }
  209. const getDefaultMode = () => {
  210. if (documentDetail)
  211. setSegmentationType(documentDetail.dataset_process_rule.mode)
  212. }
  213. const createHandle = async () => {
  214. try {
  215. let res
  216. const params = getCreationParams()
  217. if (!datasetId) {
  218. res = await createFirstDocument({
  219. body: params,
  220. })
  221. updateIndexingTypeCache && updateIndexingTypeCache(indexType)
  222. updateResultCache && updateResultCache(res)
  223. }
  224. else {
  225. res = await createDocument({
  226. datasetId,
  227. body: params,
  228. })
  229. updateIndexingTypeCache && updateIndexingTypeCache(indexType)
  230. updateResultCache && updateResultCache({
  231. document: res,
  232. })
  233. }
  234. onStepChange && onStepChange(+1)
  235. isSetting && onSave && onSave()
  236. }
  237. catch (err) {
  238. Toast.notify({
  239. type: 'error',
  240. message: `${err}`,
  241. })
  242. }
  243. }
  244. useEffect(() => {
  245. // fetch rules
  246. if (!isSetting) {
  247. getRules()
  248. }
  249. else {
  250. getRulesFromDetail()
  251. getDefaultMode()
  252. }
  253. }, [])
  254. useEffect(() => {
  255. scrollRef.current?.addEventListener('scroll', scrollHandle)
  256. return () => {
  257. scrollRef.current?.removeEventListener('scroll', scrollHandle)
  258. }
  259. }, [])
  260. useLayoutEffect(() => {
  261. if (showPreview) {
  262. previewScrollRef.current?.addEventListener('scroll', previewScrollHandle)
  263. return () => {
  264. previewScrollRef.current?.removeEventListener('scroll', previewScrollHandle)
  265. }
  266. }
  267. }, [showPreview])
  268. useEffect(() => {
  269. // get indexing type by props
  270. if (indexingType)
  271. setIndexType(indexingType as IndexingType)
  272. else
  273. setIndexType(hasSetAPIKEY ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
  274. }, [hasSetAPIKEY, indexingType, datasetId])
  275. useEffect(() => {
  276. if (segmentationType === SegmentType.AUTO) {
  277. setAutomaticFileIndexingEstimate(null)
  278. setShowPreview()
  279. fetchFileIndexingEstimate()
  280. }
  281. else {
  282. hidePreview()
  283. setCustomFileIndexingEstimate(null)
  284. }
  285. }, [segmentationType, indexType])
  286. return (
  287. <div className='flex w-full h-full'>
  288. <div ref={scrollRef} className='relative h-full w-full overflow-y-scroll'>
  289. <div className={cn(s.pageHeader, scrolled && s.fixed)}>{t('datasetCreation.steps.two')}</div>
  290. <div className={cn(s.form)}>
  291. <div className={s.label}>{t('datasetCreation.stepTwo.segmentation')}</div>
  292. <div className='max-w-[640px]'>
  293. <div
  294. className={cn(
  295. s.radioItem,
  296. s.segmentationItem,
  297. segmentationType === SegmentType.AUTO && s.active,
  298. )}
  299. onClick={() => setSegmentationType(SegmentType.AUTO)}
  300. >
  301. <span className={cn(s.typeIcon, s.auto)} />
  302. <span className={cn(s.radio)} />
  303. <div className={s.typeHeader}>
  304. <div className={s.title}>{t('datasetCreation.stepTwo.auto')}</div>
  305. <div className={s.tip}>{t('datasetCreation.stepTwo.autoDescription')}</div>
  306. </div>
  307. </div>
  308. <div
  309. className={cn(
  310. s.radioItem,
  311. s.segmentationItem,
  312. segmentationType === SegmentType.CUSTOM && s.active,
  313. segmentationType === SegmentType.CUSTOM && s.custom,
  314. )}
  315. onClick={() => setSegmentationType(SegmentType.CUSTOM)}
  316. >
  317. <span className={cn(s.typeIcon, s.customize)} />
  318. <span className={cn(s.radio)} />
  319. <div className={s.typeHeader}>
  320. <div className={s.title}>{t('datasetCreation.stepTwo.custom')}</div>
  321. <div className={s.tip}>{t('datasetCreation.stepTwo.customDescription')}</div>
  322. </div>
  323. {segmentationType === SegmentType.CUSTOM && (
  324. <div className={s.typeFormBody}>
  325. <div className={s.formRow}>
  326. <div className='w-full'>
  327. <div className={s.label}>{t('datasetCreation.stepTwo.separator')}</div>
  328. <input
  329. type="text"
  330. className={s.input}
  331. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={segmentIdentifier}
  332. onChange={e => setSegmentIdentifier(e.target.value)}
  333. />
  334. </div>
  335. </div>
  336. <div className={s.formRow}>
  337. <div className='w-full'>
  338. <div className={s.label}>{t('datasetCreation.stepTwo.maxLength')}</div>
  339. <input
  340. type="number"
  341. className={s.input}
  342. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={max}
  343. onChange={e => setMax(Number(e.target.value))}
  344. />
  345. </div>
  346. </div>
  347. <div className={s.formRow}>
  348. <div className='w-full'>
  349. <div className={s.label}>{t('datasetCreation.stepTwo.rules')}</div>
  350. {rules.map(rule => (
  351. <div key={rule.id} className={s.ruleItem}>
  352. <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" />
  353. <label htmlFor={rule.id} className="ml-2 text-sm font-normal cursor-pointer text-gray-800">{getRuleName(rule.id)}</label>
  354. </div>
  355. ))}
  356. </div>
  357. </div>
  358. <div className={s.formFooter}>
  359. <Button type="primary" className={cn(s.button, '!h-8 text-primary-600')} onClick={confirmChangeCustomConfig}>{t('datasetCreation.stepTwo.preview')}</Button>
  360. <Button className={cn(s.button, 'ml-2 !h-8')} onClick={resetRules}>{t('datasetCreation.stepTwo.reset')}</Button>
  361. </div>
  362. </div>
  363. )}
  364. </div>
  365. </div>
  366. <div className={s.label}>{t('datasetCreation.stepTwo.indexMode')}</div>
  367. <div className='max-w-[640px]'>
  368. <div className='flex items-center gap-3'>
  369. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.QUALIFIED)) && (
  370. <div
  371. className={cn(
  372. s.radioItem,
  373. s.indexItem,
  374. !hasSetAPIKEY && s.disabled,
  375. !hasSetIndexType && indexType === IndexingType.QUALIFIED && s.active,
  376. hasSetIndexType && s.disabled,
  377. hasSetIndexType && '!w-full',
  378. )}
  379. onClick={() => {
  380. if (hasSetAPIKEY)
  381. setIndexType(IndexingType.QUALIFIED)
  382. }}
  383. >
  384. <span className={cn(s.typeIcon, s.qualified)} />
  385. {!hasSetIndexType && <span className={cn(s.radio)} />}
  386. <div className={s.typeHeader}>
  387. <div className={s.title}>
  388. {t('datasetCreation.stepTwo.qualified')}
  389. {!hasSetIndexType && <span className={s.recommendTag}>{t('datasetCreation.stepTwo.recommend')}</span>}
  390. </div>
  391. <div className={s.tip}>{t('datasetCreation.stepTwo.qualifiedTip')}</div>
  392. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  393. {
  394. fileIndexingEstimate
  395. ? (
  396. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.tokens)} tokens(<span className='text-yellow-500'>${formatNumber(fileIndexingEstimate.total_price)}</span>)</div>
  397. )
  398. : (
  399. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  400. )
  401. }
  402. </div>
  403. {!hasSetAPIKEY && (
  404. <div className={s.warningTip}>
  405. <span>{t('datasetCreation.stepTwo.warning')}&nbsp;</span>
  406. <span className={s.click} onClick={onSetting}>{t('datasetCreation.stepTwo.click')}</span>
  407. </div>
  408. )}
  409. </div>
  410. )}
  411. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.ECONOMICAL)) && (
  412. <div
  413. className={cn(
  414. s.radioItem,
  415. s.indexItem,
  416. !hasSetIndexType && indexType === IndexingType.ECONOMICAL && s.active,
  417. hasSetIndexType && s.disabled,
  418. hasSetIndexType && '!w-full',
  419. )}
  420. onClick={() => !hasSetIndexType && setIndexType(IndexingType.ECONOMICAL)}
  421. >
  422. <span className={cn(s.typeIcon, s.economical)} />
  423. {!hasSetIndexType && <span className={cn(s.radio)} />}
  424. <div className={s.typeHeader}>
  425. <div className={s.title}>{t('datasetCreation.stepTwo.economical')}</div>
  426. <div className={s.tip}>{t('datasetCreation.stepTwo.economicalTip')}</div>
  427. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  428. <div className='text-xs font-medium text-gray-800'>0 tokens</div>
  429. </div>
  430. </div>
  431. )}
  432. </div>
  433. {hasSetIndexType && (
  434. <div className='mt-2 text-xs text-gray-500 font-medium'>
  435. {t('datasetCreation.stepTwo.indexSettedTip')}
  436. <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
  437. </div>
  438. )}
  439. <div className={s.file}>
  440. <div className={s.fileContent}>
  441. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.fileName')}</div>
  442. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  443. <span className={cn(s.fileIcon, file && s[file.extension])} />
  444. {getFileName(file?.name || '')}
  445. </div>
  446. </div>
  447. <div className={s.divider} />
  448. <div className={s.fileContent}>
  449. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateSegment')}</div>
  450. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  451. {
  452. fileIndexingEstimate
  453. ? (
  454. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.total_segments)} </div>
  455. )
  456. : (
  457. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  458. )
  459. }
  460. </div>
  461. </div>
  462. </div>
  463. {!isSetting
  464. ? (
  465. <div className='flex items-center mt-8 py-2'>
  466. <Button onClick={() => onStepChange && onStepChange(-1)}>{t('datasetCreation.stepTwo.lastStep')}</Button>
  467. <div className={s.divider} />
  468. <Button type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.nextStep')}</Button>
  469. </div>
  470. )
  471. : (
  472. <div className='flex items-center mt-8 py-2'>
  473. <Button type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.save')}</Button>
  474. <Button className='ml-2' onClick={onCancel}>{t('datasetCreation.stepTwo.cancel')}</Button>
  475. </div>
  476. )}
  477. </div>
  478. </div>
  479. </div>
  480. {(showPreview)
  481. ? (
  482. <div ref={previewScrollRef} className={cn(s.previewWrap, 'relativeh-full overflow-y-scroll border-l border-[#F2F4F7]')}>
  483. <div className={cn(s.previewHeader, previewScrolled && `${s.fixed} pb-3`, ' flex items-center justify-between px-8')}>
  484. <span>{t('datasetCreation.stepTwo.previewTitle')}</span>
  485. <div className='flex items-center justify-center w-6 h-6 cursor-pointer' onClick={hidePreview}>
  486. <XMarkIcon className='h-4 w-4'></XMarkIcon>
  487. </div>
  488. </div>
  489. <div className='my-4 px-8 space-y-4'>
  490. {fileIndexingEstimate?.preview
  491. ? (
  492. <>
  493. {fileIndexingEstimate?.preview.map((item, index) => (
  494. <PreviewItem key={item} content={item} index={index + 1} />
  495. ))}
  496. </>
  497. )
  498. : <div className='flex items-center justify-center h-[200px]'><Loading type='area'></Loading></div>
  499. }
  500. </div>
  501. </div>
  502. )
  503. : (<div className={cn(s.sideTip)}>
  504. <div className={s.tipCard}>
  505. <span className={s.icon} />
  506. <div className={s.title}>{t('datasetCreation.stepTwo.sideTipTitle')}</div>
  507. <div className={s.content}>
  508. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP1')}</p>
  509. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP2')}</p>
  510. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP3')}</p>
  511. <p>{t('datasetCreation.stepTwo.sideTipP4')}</p>
  512. </div>
  513. </div>
  514. </div>)}
  515. </div>
  516. )
  517. }
  518. export default StepTwo