Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. name = "TestDocument.txt"
  19. blob = b"Sample document content for ingestion test."
  20. res = rag.create_document(ds, name=name, blob=blob)
  21. # Ensure document ingestion was successful
  22. assert res is True, f"Failed to create document, error: {res}"
  23. def test_get_detail_document_with_success(self):
  24. """
  25. Test getting a document's detail with success
  26. """
  27. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  28. doc = rag.get_document(name="TestDocument.txt")
  29. assert isinstance(doc, Document), f"Failed to get dataset, error: {doc}."
  30. assert doc.name == "TestDocument.txt", "Name does not match"
  31. def test_update_document_with_success(self):
  32. """
  33. Test updating a document with success.
  34. """
  35. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  36. doc = rag.get_document(name="TestDocument.txt")
  37. if isinstance(doc, Document):
  38. doc.parser_method = "manual"
  39. doc.name = "manual.txt"
  40. res = doc.save()
  41. assert res is True, f"Failed to update document, error: {res}"
  42. else:
  43. assert False, f"Failed to get document, error: {doc}"
  44. def test_download_document_with_success(self):
  45. """
  46. Test downloading a document with success.
  47. """
  48. # Initialize RAGFlow instance
  49. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  50. # Retrieve a document
  51. doc = rag.get_document(name="TestDocument.txt")
  52. # Check if the retrieved document is of type Document
  53. if isinstance(doc, Document):
  54. # Download the document content and save it to a file
  55. try:
  56. with open("ragflow.txt", "wb+") as file:
  57. file.write(doc.download())
  58. # Print the document object for debugging
  59. print(doc)
  60. # Assert that the download was successful
  61. assert True, "Document downloaded successfully."
  62. except Exception as e:
  63. # If an error occurs, raise an assertion error
  64. assert False, f"Failed to download document, error: {str(e)}"
  65. else:
  66. # If the document retrieval fails, assert failure
  67. assert False, f"Failed to get document, error: {doc}"
  68. def test_list_all_documents_in_dataset_with_success(self):
  69. """
  70. Test list all documents into a dataset with success.
  71. """
  72. # Initialize RAGFlow instance
  73. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  74. # Step 1: Create a new dataset
  75. ds = rag.create_dataset(name="God2")
  76. # Ensure dataset creation was successful
  77. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  78. assert ds.name == "God2", "Dataset name does not match."
  79. # Step 2: Create a new document
  80. # The blob is the actual file content or a placeholder in this case
  81. name1 = "Test Document111.txt"
  82. blob1 = b"Sample document content for ingestion test111."
  83. name2 = "Test Document222.txt"
  84. blob2 = b"Sample document content for ingestion test222."
  85. rag.create_document(ds, name=name1, blob=blob1)
  86. rag.create_document(ds, name=name2, blob=blob2)
  87. for d in ds.list_docs(keywords="test", offset=0, limit=12):
  88. assert isinstance(d, Document)
  89. print(d)
  90. def test_delete_documents_in_dataset_with_success(self):
  91. """
  92. Test list all documents into a dataset with success.
  93. """
  94. # Initialize RAGFlow instance
  95. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  96. # Step 1: Create a new dataset
  97. ds = rag.create_dataset(name="God3")
  98. # Ensure dataset creation was successful
  99. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  100. assert ds.name == "God3", "Dataset name does not match."
  101. # Step 2: Create a new document
  102. # The blob is the actual file content or a placeholder in this case
  103. name1 = "Test Document333.txt"
  104. blob1 = b"Sample document content for ingestion test333."
  105. name2 = "Test Document444.txt"
  106. blob2 = b"Sample document content for ingestion test444."
  107. name3 = 'test.txt'
  108. path = 'test_data/test.txt'
  109. rag.create_document(ds, name=name3, blob=open(path, "rb").read())
  110. rag.create_document(ds, name=name1, blob=blob1)
  111. rag.create_document(ds, name=name2, blob=blob2)
  112. for d in ds.list_docs(keywords="document", offset=0, limit=12):
  113. assert isinstance(d, Document)
  114. d.delete()
  115. print(d)
  116. remaining_docs = ds.list_docs(keywords="rag", offset=0, limit=12)
  117. assert len(remaining_docs) == 0, "Documents were not properly deleted."
  118. def test_parse_and_cancel_document(self):
  119. # Initialize RAGFlow with API key and host address
  120. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  121. # Create a dataset with a specific name
  122. ds = rag.create_dataset(name="God4")
  123. # Define the document name and path
  124. name3 = 'ai.pdf'
  125. path = 'test_data/ai.pdf'
  126. # Create a document in the dataset using the file path
  127. rag.create_document(ds, name=name3, blob=open(path, "rb").read())
  128. # Retrieve the document by name
  129. doc = rag.get_document(name="ai.pdf")
  130. # Initiate asynchronous parsing
  131. doc.async_parse()
  132. # Print message to confirm asynchronous parsing has been initiated
  133. print("Async parsing initiated")
  134. # Use join to wait for parsing to complete and get progress updates
  135. for progress, msg in doc.join(interval=5, timeout=10):
  136. print(progress, msg)
  137. # Assert that the progress is within the valid range (0 to 100)
  138. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  139. # Assert that the message is not empty
  140. assert msg, "Message should not be empty"
  141. # Test cancelling the parsing operation
  142. doc.cancel()
  143. # Print message to confirm parsing has been cancelled successfully
  144. print("Parsing cancelled successfully")
  145. def test_bulk_parse_and_cancel_documents(self):
  146. # Initialize RAGFlow with API key and host address
  147. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  148. # Create a dataset
  149. ds = rag.create_dataset(name="God5")
  150. assert ds is not None, "Dataset creation failed"
  151. assert ds.name == "God5", "Dataset name does not match"
  152. # Prepare a list of file names and paths
  153. documents = [
  154. {'name': 'ai1.pdf', 'path': 'test_data/ai1.pdf'},
  155. {'name': 'ai2.pdf', 'path': 'test_data/ai2.pdf'},
  156. {'name': 'ai3.pdf', 'path': 'test_data/ai3.pdf'}
  157. ]
  158. # Create documents in bulk
  159. for doc_info in documents:
  160. with open(doc_info['path'], "rb") as file:
  161. created_doc = rag.create_document(ds, name=doc_info['name'], blob=file.read())
  162. assert created_doc is not None, f"Failed to create document {doc_info['name']}"
  163. # Retrieve document objects in bulk
  164. docs = [rag.get_document(name=doc_info['name']) for doc_info in documents]
  165. ids = [doc.id for doc in docs]
  166. assert len(docs) == len(documents), "Mismatch between created documents and fetched documents"
  167. # Initiate asynchronous parsing for all documents
  168. rag.async_parse_documents(ids)
  169. print("Async bulk parsing initiated")
  170. # Wait for all documents to finish parsing and check progress
  171. for doc in docs:
  172. for progress, msg in doc.join(interval=5, timeout=10):
  173. print(f"{doc.name}: Progress: {progress}, Message: {msg}")
  174. # Assert that progress is within the valid range
  175. assert 0 <= progress <= 100, f"Invalid progress: {progress} for document {doc.name}"
  176. # Assert that the message is not empty
  177. assert msg, f"Message should not be empty for document {doc.name}"
  178. # If progress reaches 100%, assert that parsing is completed successfully
  179. if progress == 100:
  180. assert "completed" in msg.lower(), f"Document {doc.name} did not complete successfully"
  181. # Cancel parsing for all documents in bulk
  182. cancel_result = rag.async_cancel_parse_documents(ids)
  183. assert cancel_result is None or isinstance(cancel_result, type(None)), "Failed to cancel document parsing"
  184. print("Async bulk parsing cancelled")
  185. def test_parse_document_and_chunk_list(self):
  186. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  187. ds = rag.create_dataset(name="God7")
  188. name='story.txt'
  189. path = 'test_data/story.txt'
  190. # name = "Test Document rag.txt"
  191. # 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."
  192. rag.create_document(ds, name=name, blob=open(path, "rb").read())
  193. doc = rag.get_document(name=name)
  194. doc.async_parse()
  195. # Wait for parsing to complete and get progress updates using join
  196. for progress, msg in doc.join(interval=5, timeout=30):
  197. print(progress, msg)
  198. # Assert that progress is within 0 to 100
  199. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  200. # Assert that the message is not empty
  201. assert msg, "Message should not be empty"
  202. for c in doc.list_chunks(keywords="rag", offset=0, limit=12):
  203. print(c)
  204. assert c is not None, "Chunk is None"
  205. assert "rag" in c['content_with_weight'].lower(), f"Keyword 'rag' not found in chunk content: {c.content}"
  206. def test_add_chunk_to_chunk_list(self):
  207. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  208. doc = rag.get_document(name='story.txt')
  209. chunk = doc.add_chunk(content="assss")
  210. assert chunk is not None, "Chunk is None"
  211. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  212. def test_delete_chunk_of_chunk_list(self):
  213. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  214. doc = rag.get_document(name='story.txt')
  215. chunk = doc.add_chunk(content="assss")
  216. assert chunk is not None, "Chunk is None"
  217. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  218. chunk_num_before=doc.chunk_num
  219. chunk.delete()
  220. assert doc.chunk_num == chunk_num_before-1, "Chunk was not deleted"