Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import { IDocumentInfo } from '@/interfaces/database/document';
  2. import { IChunk, IKnowledgeFile } from '@/interfaces/database/knowledge';
  3. import { IChangeParserConfigRequestBody } from '@/interfaces/request/document';
  4. import chatService from '@/services/chat-service';
  5. import kbService from '@/services/knowledge-service';
  6. import { api_host } from '@/utils/api';
  7. import { buildChunkHighlights } from '@/utils/document-util';
  8. import { useMutation, useQuery } from '@tanstack/react-query';
  9. import { UploadFile } from 'antd';
  10. import { useCallback, useMemo, useState } from 'react';
  11. import { IHighlight } from 'react-pdf-highlighter';
  12. import { useDispatch, useSelector } from 'umi';
  13. import { useGetKnowledgeSearchParams } from './route-hook';
  14. import { useOneNamespaceEffectsLoading } from './store-hooks';
  15. export const useGetDocumentUrl = (documentId?: string) => {
  16. const getDocumentUrl = useCallback(
  17. (id?: string) => {
  18. return `${api_host}/document/get/${documentId || id}`;
  19. },
  20. [documentId],
  21. );
  22. return getDocumentUrl;
  23. };
  24. export const useGetChunkHighlights = (selectedChunk: IChunk) => {
  25. const [size, setSize] = useState({ width: 849, height: 1200 });
  26. const highlights: IHighlight[] = useMemo(() => {
  27. return buildChunkHighlights(selectedChunk, size);
  28. }, [selectedChunk, size]);
  29. const setWidthAndHeight = (width: number, height: number) => {
  30. setSize((pre) => {
  31. if (pre.height !== height || pre.width !== width) {
  32. return { height, width };
  33. }
  34. return pre;
  35. });
  36. };
  37. return { highlights, setWidthAndHeight };
  38. };
  39. export const useFetchDocumentList = () => {
  40. const { knowledgeId } = useGetKnowledgeSearchParams();
  41. const dispatch = useDispatch();
  42. const fetchKfList = useCallback(() => {
  43. return dispatch<any>({
  44. type: 'kFModel/getKfList',
  45. payload: {
  46. kb_id: knowledgeId,
  47. },
  48. });
  49. }, [dispatch, knowledgeId]);
  50. return fetchKfList;
  51. };
  52. export const useSetDocumentStatus = () => {
  53. const dispatch = useDispatch();
  54. const { knowledgeId } = useGetKnowledgeSearchParams();
  55. const setDocumentStatus = useCallback(
  56. (status: boolean, documentId: string) => {
  57. dispatch({
  58. type: 'kFModel/updateDocumentStatus',
  59. payload: {
  60. doc_id: documentId,
  61. status: Number(status),
  62. kb_id: knowledgeId,
  63. },
  64. });
  65. },
  66. [dispatch, knowledgeId],
  67. );
  68. return setDocumentStatus;
  69. };
  70. export const useSelectDocumentList = () => {
  71. const list: IKnowledgeFile[] = useSelector(
  72. (state: any) => state.kFModel.data,
  73. );
  74. return list;
  75. };
  76. export const useSaveDocumentName = () => {
  77. const dispatch = useDispatch();
  78. const { knowledgeId } = useGetKnowledgeSearchParams();
  79. const saveName = useCallback(
  80. (documentId: string, name: string) => {
  81. return dispatch<any>({
  82. type: 'kFModel/document_rename',
  83. payload: {
  84. doc_id: documentId,
  85. name: name,
  86. kb_id: knowledgeId,
  87. },
  88. });
  89. },
  90. [dispatch, knowledgeId],
  91. );
  92. return saveName;
  93. };
  94. export const useCreateDocument = () => {
  95. const dispatch = useDispatch();
  96. const { knowledgeId } = useGetKnowledgeSearchParams();
  97. const createDocument = useCallback(
  98. (name: string) => {
  99. try {
  100. return dispatch<any>({
  101. type: 'kFModel/document_create',
  102. payload: {
  103. name,
  104. kb_id: knowledgeId,
  105. },
  106. });
  107. } catch (errorInfo) {
  108. console.log('Failed:', errorInfo);
  109. }
  110. },
  111. [dispatch, knowledgeId],
  112. );
  113. return createDocument;
  114. };
  115. export const useSetDocumentParser = () => {
  116. const dispatch = useDispatch();
  117. const { knowledgeId } = useGetKnowledgeSearchParams();
  118. const setDocumentParser = useCallback(
  119. (
  120. parserId: string,
  121. documentId: string,
  122. parserConfig: IChangeParserConfigRequestBody,
  123. ) => {
  124. try {
  125. return dispatch<any>({
  126. type: 'kFModel/document_change_parser',
  127. payload: {
  128. parser_id: parserId,
  129. doc_id: documentId,
  130. kb_id: knowledgeId,
  131. parser_config: parserConfig,
  132. },
  133. });
  134. } catch (errorInfo) {
  135. console.log('Failed:', errorInfo);
  136. }
  137. },
  138. [dispatch, knowledgeId],
  139. );
  140. return setDocumentParser;
  141. };
  142. export const useRemoveDocument = () => {
  143. const dispatch = useDispatch();
  144. const { knowledgeId } = useGetKnowledgeSearchParams();
  145. const removeDocument = useCallback(
  146. (documentIds: string[]) => {
  147. try {
  148. return dispatch<any>({
  149. type: 'kFModel/document_rm',
  150. payload: {
  151. doc_id: documentIds,
  152. kb_id: knowledgeId,
  153. },
  154. });
  155. } catch (errorInfo) {
  156. console.log('Failed:', errorInfo);
  157. }
  158. },
  159. [dispatch, knowledgeId],
  160. );
  161. return removeDocument;
  162. };
  163. export const useUploadDocument = () => {
  164. const dispatch = useDispatch();
  165. const { knowledgeId } = useGetKnowledgeSearchParams();
  166. const uploadDocument = useCallback(
  167. (fileList: UploadFile[]) => {
  168. try {
  169. return dispatch<any>({
  170. type: 'kFModel/upload_document',
  171. payload: {
  172. fileList,
  173. kb_id: knowledgeId,
  174. },
  175. });
  176. } catch (errorInfo) {
  177. console.log('Failed:', errorInfo);
  178. }
  179. },
  180. [dispatch, knowledgeId],
  181. );
  182. return uploadDocument;
  183. };
  184. export const useWebCrawl = () => {
  185. const dispatch = useDispatch();
  186. const { knowledgeId } = useGetKnowledgeSearchParams();
  187. return useCallback(
  188. (name: string, url: string) => {
  189. try {
  190. return dispatch<any>({
  191. type: 'kFModel/web_crawl',
  192. payload: {
  193. name,
  194. url,
  195. kb_id: knowledgeId,
  196. },
  197. });
  198. } catch (errorInfo) {
  199. console.log('Failed:', errorInfo);
  200. }
  201. },
  202. [dispatch],
  203. );
  204. };
  205. export const useRunDocument = () => {
  206. const dispatch = useDispatch();
  207. const runDocumentByIds = useCallback(
  208. (payload: any) => {
  209. try {
  210. return dispatch<any>({
  211. type: 'kFModel/document_run',
  212. payload,
  213. });
  214. } catch (errorInfo) {
  215. console.log('Failed:', errorInfo);
  216. }
  217. },
  218. [dispatch],
  219. );
  220. return runDocumentByIds;
  221. };
  222. export const useSelectRunDocumentLoading = () => {
  223. const loading = useOneNamespaceEffectsLoading('kFModel', ['document_run']);
  224. return loading;
  225. };
  226. export const useFetchDocumentInfosByIds = () => {
  227. const [ids, setDocumentIds] = useState<string[]>([]);
  228. const { data } = useQuery<IDocumentInfo[]>({
  229. queryKey: ['fetchDocumentInfos', ids],
  230. enabled: ids.length > 0,
  231. initialData: [],
  232. queryFn: async () => {
  233. const { data } = await kbService.document_infos({ doc_ids: ids });
  234. if (data.retcode === 0) {
  235. return data.data;
  236. }
  237. return [];
  238. },
  239. });
  240. return { data, setDocumentIds };
  241. };
  242. export const useFetchDocumentThumbnailsByIds = () => {
  243. const [ids, setDocumentIds] = useState<string[]>([]);
  244. const { data } = useQuery<Record<string, string>>({
  245. queryKey: ['fetchDocumentThumbnails', ids],
  246. enabled: ids.length > 0,
  247. initialData: {},
  248. queryFn: async () => {
  249. const { data } = await kbService.document_thumbnails({ doc_ids: ids });
  250. if (data.retcode === 0) {
  251. return data.data;
  252. }
  253. return {};
  254. },
  255. });
  256. return { data, setDocumentIds };
  257. };
  258. export const useRemoveNextDocument = () => {
  259. // const queryClient = useQueryClient();
  260. const {
  261. data,
  262. isPending: loading,
  263. mutateAsync,
  264. } = useMutation({
  265. mutationKey: ['removeDocument'],
  266. mutationFn: async (documentId: string) => {
  267. const data = await kbService.document_rm({ doc_id: documentId });
  268. // if (data.retcode === 0) {
  269. // queryClient.invalidateQueries({ queryKey: ['fetchFlowList'] });
  270. // }
  271. return data;
  272. },
  273. });
  274. return { data, loading, removeDocument: mutateAsync };
  275. };
  276. export const useDeleteDocument = () => {
  277. // const queryClient = useQueryClient();
  278. const {
  279. data,
  280. isPending: loading,
  281. mutateAsync,
  282. } = useMutation({
  283. mutationKey: ['deleteDocument'],
  284. mutationFn: async (documentIds: string[]) => {
  285. const data = await kbService.document_delete({ doc_ids: documentIds });
  286. // if (data.retcode === 0) {
  287. // queryClient.invalidateQueries({ queryKey: ['fetchFlowList'] });
  288. // }
  289. return data;
  290. },
  291. });
  292. return { data, loading, deleteDocument: mutateAsync };
  293. };
  294. export const useUploadAndParseDocument = (uploadMethod: string) => {
  295. const {
  296. data,
  297. isPending: loading,
  298. mutateAsync,
  299. } = useMutation({
  300. mutationKey: ['uploadAndParseDocument'],
  301. mutationFn: async ({
  302. conversationId,
  303. fileList,
  304. }: {
  305. conversationId: string;
  306. fileList: UploadFile[];
  307. }) => {
  308. const formData = new FormData();
  309. formData.append('conversation_id', conversationId);
  310. fileList.forEach((file: UploadFile) => {
  311. formData.append('file', file as any);
  312. });
  313. if (uploadMethod === 'upload_and_parse') {
  314. const data = await kbService.upload_and_parse(formData);
  315. return data?.data;
  316. }
  317. const data = await chatService.uploadAndParseExternal(formData);
  318. return data?.data;
  319. },
  320. });
  321. return { data, loading, uploadAndParseDocument: mutateAsync };
  322. };