Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

t_document.py 14KB

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