index.tsx 19 KB

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