Skip to content

Commit 840d442

Browse files
committed
sdks/python: fix linting and formatting issues
1 parent b957194 commit 840d442

9 files changed

Lines changed: 314 additions & 336 deletions

File tree

sdks/python/apache_beam/ml/rag/enrichment/milvus_search.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,21 +28,20 @@
2828

2929
from google.protobuf.json_format import MessageToDict
3030

31-
from apache_beam.ml.rag.types import Chunk
32-
from apache_beam.ml.rag.types import Embedding
33-
from apache_beam.transforms.enrichment import EnrichmentSourceHandler
3431
from pymilvus import AnnSearchRequest
3532
from pymilvus import Hit
3633
from pymilvus import Hits
3734
from pymilvus import MilvusClient
3835
from pymilvus import SearchResult
3936

37+
from apache_beam.ml.rag.types import Chunk
38+
from apache_beam.ml.rag.types import Embedding
39+
from apache_beam.transforms.enrichment import EnrichmentSourceHandler
40+
4041
from apache_beam.ml.rag.types import Chunk
4142
from apache_beam.ml.rag.types import Embedding
4243
from apache_beam.ml.rag.utils import (
43-
MilvusHelpers,
44-
MilvusConnectionConfig,
45-
unpack_dataclass_with_kwargs)
44+
MilvusHelpers, MilvusConnectionConfig, unpack_dataclass_with_kwargs)
4645
from apache_beam.transforms.enrichment import EnrichmentSourceHandler
4746

4847

sdks/python/apache_beam/ml/rag/enrichment/milvus_search_it_test.py

Lines changed: 84 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,11 @@
3838
from apache_beam.ml.rag.types import Content
3939
from apache_beam.ml.rag.types import Embedding
4040
from apache_beam.ml.rag.utils import (
41-
MilvusConnectionConfig,
42-
unpack_dataclass_with_kwargs)
41+
MilvusConnectionConfig, unpack_dataclass_with_kwargs)
4342
from apache_beam.ml.rag.test_utils import (
4443
VectorDBContainerInfo,
45-
MilvusTestHelpers,)
44+
MilvusTestHelpers,
45+
)
4646
from apache_beam.testing.test_pipeline import TestPipeline
4747
from apache_beam.testing.util import assert_that
4848

@@ -124,6 +124,7 @@ def _construct_index_params():
124124

125125
return index_params
126126

127+
127128
@dataclass
128129
class MilvusITDataConstruct:
129130
id: int
@@ -139,6 +140,7 @@ class MilvusITDataConstruct:
139140
def __getitem__(self, key):
140141
return getattr(self, key)
141142

143+
142144
MILVUS_ENRICHMENT_IT_CONFIG = {
143145
"collection_name": "docs_catalog",
144146
"fields": [
@@ -228,70 +230,71 @@ def __getitem__(self, key):
228230
}
229231
}
230232

233+
231234
def initialize_db_with_data(connc_params: MilvusConnectionConfig):
232-
# Open the connection to the milvus db.
233-
config = unpack_dataclass_with_kwargs(connc_params)
234-
config["alias"] = f"milvus_conn_{uuid.uuid4().hex[:8]}"
235-
client = MilvusClient(**config)
236-
237-
# Configure schema.
238-
field_schemas: List[FieldSchema] = cast(
239-
List[FieldSchema], MILVUS_ENRICHMENT_IT_CONFIG["fields"])
240-
schema = CollectionSchema(
241-
fields=field_schemas,
242-
functions=MILVUS_ENRICHMENT_IT_CONFIG["functions"])
243-
244-
# Create collection with the schema.
245-
collection_name = MILVUS_ENRICHMENT_IT_CONFIG["collection_name"]
246-
index_function: Callable[[], IndexParams] = cast(
247-
Callable[[], IndexParams], MILVUS_ENRICHMENT_IT_CONFIG["index"])
248-
client.create_collection(
249-
collection_name=collection_name,
250-
schema=schema,
251-
index_params=index_function())
252-
253-
# Assert that collection was created.
254-
collection_error = f"Expected collection '{collection_name}' to be created."
255-
assert client.has_collection(collection_name), collection_error
256-
257-
# Gather all fields we have excluding 'sparse_embedding_bm25' special field.
258-
fields = [field.name for field in field_schemas]
259-
260-
# Prep data for indexing. Currently we can't insert sparse vectors for BM25
261-
# sparse embedding field as it would be automatically generated by Milvus
262-
# through the registered BM25 function.
263-
data_ready_to_index = []
264-
for doc in MILVUS_ENRICHMENT_IT_CONFIG["corpus"]:
265-
item = {}
266-
for field in fields:
267-
if field.startswith("dense_embedding"):
268-
item[field] = doc["dense_embedding"]
269-
elif field == "sparse_embedding_inner_product":
270-
item[field] = doc["sparse_embedding"]
271-
elif field == "sparse_embedding_bm25":
272-
# It is automatically generated by Milvus from content field.
273-
continue
274-
else:
275-
item[field] = doc[field]
276-
data_ready_to_index.append(item)
277-
278-
# Index data.
279-
result = client.insert(
280-
collection_name=collection_name, data=data_ready_to_index)
281-
282-
# Assert that the intended data has been properly indexed.
283-
insertion_err = f'failed to insert the {result["insert_count"]} data points'
284-
assert result["insert_count"] == len(data_ready_to_index), insertion_err
285-
286-
# Release the collection from memory. It will be loaded lazily when the
287-
# enrichment handler is invoked.
288-
client.release_collection(collection_name)
289-
290-
# Close the connection to the Milvus database, as no further preparation
291-
# operations are needed before executing the enrichment handler.
292-
client.close()
293-
294-
return collection_name
235+
# Open the connection to the milvus db.
236+
config = unpack_dataclass_with_kwargs(connc_params)
237+
config["alias"] = f"milvus_conn_{uuid.uuid4().hex[:8]}"
238+
client = MilvusClient(**config)
239+
240+
# Configure schema.
241+
field_schemas: List[FieldSchema] = cast(
242+
List[FieldSchema], MILVUS_ENRICHMENT_IT_CONFIG["fields"])
243+
schema = CollectionSchema(
244+
fields=field_schemas, functions=MILVUS_ENRICHMENT_IT_CONFIG["functions"])
245+
246+
# Create collection with the schema.
247+
collection_name = MILVUS_ENRICHMENT_IT_CONFIG["collection_name"]
248+
index_function: Callable[[], IndexParams] = cast(
249+
Callable[[], IndexParams], MILVUS_ENRICHMENT_IT_CONFIG["index"])
250+
client.create_collection(
251+
collection_name=collection_name,
252+
schema=schema,
253+
index_params=index_function())
254+
255+
# Assert that collection was created.
256+
collection_error = f"Expected collection '{collection_name}' to be created."
257+
assert client.has_collection(collection_name), collection_error
258+
259+
# Gather all fields we have excluding 'sparse_embedding_bm25' special field.
260+
fields = [field.name for field in field_schemas]
261+
262+
# Prep data for indexing. Currently we can't insert sparse vectors for BM25
263+
# sparse embedding field as it would be automatically generated by Milvus
264+
# through the registered BM25 function.
265+
data_ready_to_index = []
266+
for doc in MILVUS_ENRICHMENT_IT_CONFIG["corpus"]:
267+
item = {}
268+
for field in fields:
269+
if field.startswith("dense_embedding"):
270+
item[field] = doc["dense_embedding"]
271+
elif field == "sparse_embedding_inner_product":
272+
item[field] = doc["sparse_embedding"]
273+
elif field == "sparse_embedding_bm25":
274+
# It is automatically generated by Milvus from content field.
275+
continue
276+
else:
277+
item[field] = doc[field]
278+
data_ready_to_index.append(item)
279+
280+
# Index data.
281+
result = client.insert(
282+
collection_name=collection_name, data=data_ready_to_index)
283+
284+
# Assert that the intended data has been properly indexed.
285+
insertion_err = f'failed to insert the {result["insert_count"]} data points'
286+
assert result["insert_count"] == len(data_ready_to_index), insertion_err
287+
288+
# Release the collection from memory. It will be loaded lazily when the
289+
# enrichment handler is invoked.
290+
client.release_collection(collection_name)
291+
292+
# Close the connection to the Milvus database, as no further preparation
293+
# operations are needed before executing the enrichment handler.
294+
client.close()
295+
296+
return collection_name
297+
295298

296299
@pytest.mark.uses_testcontainer
297300
@unittest.skipUnless(
@@ -401,9 +404,8 @@ def test_empty_input_chunks(self):
401404
with TestPipeline(is_integration_test=True) as p:
402405
result = (p | beam.Create(test_chunks) | Enrichment(handler))
403406
assert_that(
404-
result,
405-
lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
406-
actual, expected_chunks))
407+
result, lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
408+
actual, expected_chunks))
407409

408410
def test_filtered_search_with_cosine_similarity_and_batching(self):
409411
test_chunks = [
@@ -530,9 +532,8 @@ def test_filtered_search_with_cosine_similarity_and_batching(self):
530532
with TestPipeline(is_integration_test=True) as p:
531533
result = (p | beam.Create(test_chunks) | Enrichment(handler))
532534
assert_that(
533-
result,
534-
lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
535-
actual, expected_chunks))
535+
result, lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
536+
actual, expected_chunks))
536537

537538
def test_filtered_search_with_bm25_full_text_and_batching(self):
538539
test_chunks = [
@@ -636,9 +637,8 @@ def test_filtered_search_with_bm25_full_text_and_batching(self):
636637
with TestPipeline(is_integration_test=True) as p:
637638
result = (p | beam.Create(test_chunks) | Enrichment(handler))
638639
assert_that(
639-
result,
640-
lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
641-
actual, expected_chunks))
640+
result, lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
641+
actual, expected_chunks))
642642

643643
def test_vector_search_with_euclidean_distance(self):
644644
test_chunks = [
@@ -778,9 +778,8 @@ def test_vector_search_with_euclidean_distance(self):
778778
with TestPipeline(is_integration_test=True) as p:
779779
result = (p | beam.Create(test_chunks) | Enrichment(handler))
780780
assert_that(
781-
result,
782-
lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
783-
actual, expected_chunks))
781+
result, lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
782+
actual, expected_chunks))
784783

785784
def test_vector_search_with_inner_product_similarity(self):
786785
test_chunks = [
@@ -919,9 +918,8 @@ def test_vector_search_with_inner_product_similarity(self):
919918
with TestPipeline(is_integration_test=True) as p:
920919
result = (p | beam.Create(test_chunks) | Enrichment(handler))
921920
assert_that(
922-
result,
923-
lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
924-
actual, expected_chunks))
921+
result, lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
922+
actual, expected_chunks))
925923

926924
def test_keyword_search_with_inner_product_sparse_embedding(self):
927925
test_chunks = [
@@ -985,9 +983,8 @@ def test_keyword_search_with_inner_product_sparse_embedding(self):
985983
with TestPipeline(is_integration_test=True) as p:
986984
result = (p | beam.Create(test_chunks) | Enrichment(handler))
987985
assert_that(
988-
result,
989-
lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
990-
actual, expected_chunks))
986+
result, lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
987+
actual, expected_chunks))
991988

992989
def test_hybrid_search(self):
993990
test_chunks = [
@@ -1059,10 +1056,9 @@ def test_hybrid_search(self):
10591056
with TestPipeline(is_integration_test=True) as p:
10601057
result = (p | beam.Create(test_chunks) | Enrichment(handler))
10611058
assert_that(
1062-
result,
1063-
lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
1064-
actual, expected_chunks))
1059+
result, lambda actual: MilvusTestHelpers.assert_chunks_equivalent(
1060+
actual, expected_chunks))
10651061

10661062

10671063
if __name__ == '__main__':
1068-
unittest.main()
1064+
unittest.main()

sdks/python/apache_beam/ml/rag/enrichment/milvus_search_test.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@
2323
from apache_beam.ml.rag.types import Embedding
2424
from apache_beam.ml.rag.types import Content
2525
from apache_beam.ml.rag.utils import (
26-
MilvusConnectionConfig,
27-
unpack_dataclass_with_kwargs)
26+
MilvusConnectionConfig, unpack_dataclass_with_kwargs)
2827
from apache_beam.ml.rag.enrichment.milvus_search import (
2928
MilvusSearchEnrichmentHandler,
3029
MilvusSearchParameters,
@@ -81,8 +80,7 @@ def test_invalid_connection_parameters(self):
8180
def test_invalid_search_parameters(self, create_params, expected_error_msg):
8281
"""Test validation errors for invalid general search parameters."""
8382
with self.assertRaises(ValueError) as context:
84-
connection_params = MilvusConnectionConfig(
85-
uri="http://localhost:19530")
83+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
8684
search_params = create_params()
8785
collection_load_params = MilvusCollectionLoadParameters()
8886

@@ -138,8 +136,7 @@ class TestMilvusVectorSearchEnrichment(unittest.TestCase):
138136
def test_invalid_search_parameters(self, create_params, expected_error_msg):
139137
"""Test validation errors for invalid vector search parameters."""
140138
with self.assertRaises(ValueError) as context:
141-
connection_params = MilvusConnectionConfig(
142-
uri="http://localhost:19530")
139+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
143140
vector_search_params = create_params()
144141
search_params = MilvusSearchParameters(
145142
collection_name="test_collection",
@@ -157,8 +154,7 @@ def test_missing_dense_embedding(self):
157154
with self.assertRaises(ValueError) as context:
158155
chunk = Chunk(
159156
id=1, content=None, embedding=Embedding(dense_embedding=None))
160-
connection_params = MilvusConnectionConfig(
161-
uri="http://localhost:19530")
157+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
162158
vector_search_params = VectorSearchParameters(anns_field="embedding")
163159
search_params = MilvusSearchParameters(
164160
collection_name="test_collection",
@@ -194,8 +190,7 @@ class TestMilvusKeywordSearchEnrichment(unittest.TestCase):
194190
def test_invalid_search_parameters(self, create_params, expected_error_msg):
195191
"""Test validation errors for invalid keyword search parameters."""
196192
with self.assertRaises(ValueError) as context:
197-
connection_params = MilvusConnectionConfig(
198-
uri="http://localhost:19530")
193+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
199194
keyword_search_params = create_params()
200195
search_params = MilvusSearchParameters(
201196
collection_name="test_collection",
@@ -215,8 +210,7 @@ def test_missing_text_content_and_sparse_embedding(self):
215210
id=1,
216211
content=Content(text=None),
217212
embedding=Embedding(sparse_embedding=None))
218-
connection_params = MilvusConnectionConfig(
219-
uri="http://localhost:19530")
213+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
220214
vector_search_params = VectorSearchParameters(anns_field="embedding")
221215
search_params = MilvusSearchParameters(
222216
collection_name="test_collection",
@@ -241,8 +235,7 @@ def test_missing_text_content_only(self):
241235
content=Content(text=None),
242236
embedding=Embedding(
243237
sparse_embedding=([1, 2, 3, 4], [0.05, 0.41, 0.05, 0.41])))
244-
connection_params = MilvusConnectionConfig(
245-
uri="http://localhost:19530")
238+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
246239
vector_search_params = VectorSearchParameters(anns_field="embedding")
247240
search_params = MilvusSearchParameters(
248241
collection_name="test_collection",
@@ -263,8 +256,7 @@ def test_missing_sparse_embedding_only(self):
263256
id=1,
264257
content=Content(text="what is apache beam?"),
265258
embedding=Embedding(sparse_embedding=None))
266-
connection_params = MilvusConnectionConfig(
267-
uri="http://localhost:19530")
259+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
268260
vector_search_params = VectorSearchParameters(anns_field="embedding")
269261
search_params = MilvusSearchParameters(
270262
collection_name="test_collection",
@@ -323,8 +315,7 @@ class TestMilvusHybridSearchEnrichment(unittest.TestCase):
323315
def test_invalid_search_parameters(self, create_params, expected_error_msg):
324316
"""Test validation errors for invalid hybrid search parameters."""
325317
with self.assertRaises(ValueError) as context:
326-
connection_params = MilvusConnectionConfig(
327-
uri="http://localhost:19530")
318+
connection_params = MilvusConnectionConfig(uri="http://localhost:19530")
328319
hybrid_search_params = create_params()
329320
search_params = MilvusSearchParameters(
330321
collection_name="test_collection",

0 commit comments

Comments
 (0)