您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

t_document.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. from ragflow import RAGFlow, DataSet, Document, Chunk
  2. from common import API_KEY, HOST_ADDRESS
  3. from test_sdkbase import TestSdk
  4. class TestDocument(TestSdk):
  5. def test_upload_document_with_success(self):
  6. """
  7. Test ingesting a document into a dataset with success.
  8. """
  9. # Initialize RAGFlow instance
  10. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  11. # Step 1: Create a new dataset
  12. ds = rag.create_dataset(name="God")
  13. # Ensure dataset creation was successful
  14. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  15. assert ds.name == "God", "Dataset name does not match."
  16. # Step 2: Create a new document
  17. # The blob is the actual file content or a placeholder in this case
  18. blob = b"Sample document content for ingestion test."
  19. blob_2 = b"test_2."
  20. list_1 = []
  21. list_1.append({"name":"Test_1.txt",
  22. "blob":blob})
  23. list_1.append({"name":"Test_2.txt",
  24. "blob":blob_2})
  25. res = ds.upload_documents(list_1)
  26. # Ensure document ingestion was successful
  27. assert res is None, f"Failed to create document, error: {res}"
  28. def test_update_document_with_success(self):
  29. """
  30. Test updating a document with success.
  31. Update name or chunk_method are supported
  32. """
  33. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  34. ds = rag.list_datasets(name="God")
  35. ds = ds[0]
  36. doc = ds.list_documents()
  37. doc = doc[0]
  38. if isinstance(doc, Document):
  39. res = doc.update({"chunk_method":"manual","name":"manual.txt"})
  40. assert res is None, f"Failed to update document, error: {res}"
  41. else:
  42. assert False, f"Failed to get document, error: {doc}"
  43. def test_download_document_with_success(self):
  44. """
  45. Test downloading a document with success.
  46. """
  47. # Initialize RAGFlow instance
  48. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  49. # Retrieve a document
  50. ds = rag.list_datasets(name="God")
  51. ds = ds[0]
  52. doc = ds.list_documents(name="manual.txt")
  53. doc = doc[0]
  54. # Check if the retrieved document is of type Document
  55. if isinstance(doc, Document):
  56. # Download the document content and save it to a file
  57. with open("./ragflow.txt", "wb+") as file:
  58. file.write(doc.download())
  59. # Print the document object for debugging
  60. print(doc)
  61. # Assert that the download was successful
  62. assert True, f"Failed to download document, error: {doc}"
  63. else:
  64. # If the document retrieval fails, assert failure
  65. assert False, f"Failed to get document, error: {doc}"
  66. def test_list_documents_in_dataset_with_success(self):
  67. """
  68. Test list all documents into a dataset with success.
  69. """
  70. # Initialize RAGFlow instance
  71. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  72. # Step 1: Create a new dataset
  73. ds = rag.create_dataset(name="God2")
  74. # Ensure dataset creation was successful
  75. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  76. assert ds.name == "God2", "Dataset name does not match."
  77. # Step 2: Create a new document
  78. # The blob is the actual file content or a placeholder in this case
  79. name1 = "Test Document111.txt"
  80. blob1 = b"Sample document content for ingestion test111."
  81. name2 = "Test Document222.txt"
  82. blob2 = b"Sample document content for ingestion test222."
  83. list_1 = [{"name":name1,"blob":blob1},{"name":name2,"blob":blob2}]
  84. ds.upload_documents(list_1)
  85. for d in ds.list_documents(keywords="test", offset=0, limit=12):
  86. assert isinstance(d, Document), "Failed to upload documents"
  87. def test_delete_documents_in_dataset_with_success(self):
  88. """
  89. Test list all documents into a dataset with success.
  90. """
  91. # Initialize RAGFlow instance
  92. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  93. # Step 1: Create a new dataset
  94. ds = rag.create_dataset(name="God3")
  95. # Ensure dataset creation was successful
  96. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  97. assert ds.name == "God3", "Dataset name does not match."
  98. # Step 2: Create a new document
  99. # The blob is the actual file content or a placeholder in this case
  100. name1 = "Test Document333.txt"
  101. blob1 = b"Sample document content for ingestion test333."
  102. name2 = "Test Document444.txt"
  103. blob2 = b"Sample document content for ingestion test444."
  104. ds.upload_documents([{"name":name1,"blob":blob1},{"name":name2,"blob":blob2}])
  105. for d in ds.list_documents(keywords="document", offset=0, limit=12):
  106. assert isinstance(d, Document)
  107. ds.delete_documents([d.id])
  108. remaining_docs = ds.list_documents(keywords="rag", offset=0, limit=12)
  109. assert len(remaining_docs) == 0, "Documents were not properly deleted."
  110. def test_parse_and_cancel_document(self):
  111. # Initialize RAGFlow with API key and host address
  112. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  113. # Create a dataset with a specific name
  114. ds = rag.create_dataset(name="God4")
  115. # Define the document name and path
  116. name3 = 'westworld.pdf'
  117. path = './test_data/westworld.pdf'
  118. # Create a document in the dataset using the file path
  119. ds.upload_documents({"name":name3, "blob":open(path, "rb").read()})
  120. # Retrieve the document by name
  121. doc = rag.list_documents(name="westworld.pdf")
  122. doc = doc[0]
  123. ds.async_parse_documents(document_ids=[])
  124. # Print message to confirm asynchronous parsing has been initiated
  125. print("Async parsing initiated")
  126. # Use join to wait for parsing to complete and get progress updates
  127. for progress, msg in doc.join(interval=5, timeout=10):
  128. print(progress, msg)
  129. # Assert that the progress is within the valid range (0 to 100)
  130. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  131. # Assert that the message is not empty
  132. assert msg, "Message should not be empty"
  133. # Test cancelling the parsing operation
  134. doc.cancel()
  135. # Print message to confirm parsing has been cancelled successfully
  136. print("Parsing cancelled successfully")
  137. def test_bulk_parse_and_cancel_documents(self):
  138. # Initialize RAGFlow with API key and host address
  139. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  140. # Create a dataset
  141. ds = rag.create_dataset(name="God5")
  142. assert ds is not None, "Dataset creation failed"
  143. assert ds.name == "God5", "Dataset name does not match"
  144. # Prepare a list of file names and paths
  145. documents = [
  146. {'name': 'test1.txt', 'path': 'test_data/test1.txt'},
  147. {'name': 'test2.txt', 'path': 'test_data/test2.txt'},
  148. {'name': 'test3.txt', 'path': 'test_data/test3.txt'}
  149. ]
  150. # Create documents in bulk
  151. for doc_info in documents:
  152. with open(doc_info['path'], "rb") as file:
  153. created_doc = rag.create_document(ds, name=doc_info['name'], blob=file.read())
  154. assert created_doc is not None, f"Failed to create document {doc_info['name']}"
  155. # Retrieve document objects in bulk
  156. docs = [rag.get_document(name=doc_info['name']) for doc_info in documents]
  157. ids = [doc.id for doc in docs]
  158. assert len(docs) == len(documents), "Mismatch between created documents and fetched documents"
  159. # Initiate asynchronous parsing for all documents
  160. rag.async_parse_documents(ids)
  161. print("Async bulk parsing initiated")
  162. # Wait for all documents to finish parsing and check progress
  163. for doc in docs:
  164. for progress, msg in doc.join(interval=5, timeout=10):
  165. print(f"{doc.name}: Progress: {progress}, Message: {msg}")
  166. # Assert that progress is within the valid range
  167. assert 0 <= progress <= 100, f"Invalid progress: {progress} for document {doc.name}"
  168. # Assert that the message is not empty
  169. assert msg, f"Message should not be empty for document {doc.name}"
  170. # If progress reaches 100%, assert that parsing is completed successfully
  171. if progress == 100:
  172. assert "completed" in msg.lower(), f"Document {doc.name} did not complete successfully"
  173. # Cancel parsing for all documents in bulk
  174. cancel_result = rag.async_cancel_parse_documents(ids)
  175. assert cancel_result is None or isinstance(cancel_result, type(None)), "Failed to cancel document parsing"
  176. print("Async bulk parsing cancelled")
  177. def test_parse_document_and_chunk_list(self):
  178. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  179. ds = rag.create_dataset(name="God7")
  180. name = 'story.txt'
  181. path = 'test_data/story.txt'
  182. # name = "Test Document rag.txt"
  183. # blob = " Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps.Sample document content for rag test66. rag wonderful apple os documents apps.Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps."
  184. rag.create_document(ds, name=name, blob=open(path, "rb").read())
  185. doc = rag.get_document(name=name)
  186. doc.async_parse()
  187. # Wait for parsing to complete and get progress updates using join
  188. for progress, msg in doc.join(interval=5, timeout=30):
  189. print(progress, msg)
  190. # Assert that progress is within 0 to 100
  191. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  192. # Assert that the message is not empty
  193. assert msg, "Message should not be empty"
  194. for c in doc.list_chunks(keywords="rag", offset=0, limit=12):
  195. print(c)
  196. assert c is not None, "Chunk is None"
  197. assert "rag" in c['content_with_weight'].lower(), f"Keyword 'rag' not found in chunk content: {c.content}"
  198. def test_add_chunk_to_chunk_list(self):
  199. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  200. doc = rag.get_document(name='story.txt')
  201. chunk = doc.add_chunk(content="assssdd")
  202. assert chunk is not None, "Chunk is None"
  203. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  204. def test_delete_chunk_of_chunk_list(self):
  205. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  206. doc = rag.get_document(name='story.txt')
  207. chunk = doc.add_chunk(content="assssdd")
  208. assert chunk is not None, "Chunk is None"
  209. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  210. doc = rag.get_document(name='story.txt')
  211. chunk_count_before = doc.chunk_count
  212. chunk.delete()
  213. doc = rag.get_document(name='story.txt')
  214. assert doc.chunk_count == chunk_count_before - 1, "Chunk was not deleted"
  215. def test_update_chunk_content(self):
  216. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  217. doc = rag.get_document(name='story.txt')
  218. chunk = doc.add_chunk(content="assssddd")
  219. assert chunk is not None, "Chunk is None"
  220. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  221. chunk.content = "ragflow123"
  222. res = chunk.save()
  223. assert res is True, f"Failed to update chunk content, error: {res}"
  224. def test_update_chunk_available(self):
  225. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  226. doc = rag.get_document(name='story.txt')
  227. chunk = doc.add_chunk(content="ragflow")
  228. assert chunk is not None, "Chunk is None"
  229. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  230. chunk.available = 0
  231. res = chunk.save()
  232. assert res is True, f"Failed to update chunk status, error: {res}"
  233. def test_retrieval_chunks(self):
  234. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  235. ds = rag.create_dataset(name="God8")
  236. name = 'ragflow_test.txt'
  237. path = 'test_data/ragflow_test.txt'
  238. rag.create_document(ds, name=name, blob=open(path, "rb").read())
  239. doc = rag.get_document(name=name)
  240. doc.async_parse()
  241. # Wait for parsing to complete and get progress updates using join
  242. for progress, msg in doc.join(interval=5, timeout=30):
  243. print(progress, msg)
  244. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  245. assert msg, "Message should not be empty"
  246. for c in rag.retrieval(question="What's ragflow?",
  247. datasets=[ds.id], documents=[doc],
  248. offset=0, limit=6, similarity_threshold=0.1,
  249. vector_similarity_weight=0.3,
  250. top_k=1024
  251. ):
  252. print(c)
  253. assert c is not None, "Chunk is None"
  254. assert "ragflow" in c.content.lower(), f"Keyword 'rag' not found in chunk content: {c.content}"