cocoindex 0.1.38__cp311-cp311-win_amd64.whl → 0.1.39__cp311-cp311-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cocoindex/__init__.py CHANGED
@@ -2,13 +2,14 @@
2
2
  Cocoindex is a framework for building and running indexing pipelines.
3
3
  """
4
4
  from . import functions, query, sources, storages, cli
5
- from .flow import FlowBuilder, DataScope, DataSlice, Flow, flow_def
5
+ from .flow import FlowBuilder, DataScope, DataSlice, Flow, flow_def, transform_flow
6
6
  from .flow import EvaluateAndDumpOptions, GeneratedField
7
7
  from .flow import update_all_flows_async, FlowLiveUpdater, FlowLiveUpdaterOptions
8
8
  from .llm import LlmSpec, LlmApiType
9
9
  from .index import VectorSimilarityMetric, VectorIndexDef, IndexOptions
10
10
  from .auth_registry import AuthEntryReference, add_auth_entry, ref_auth_entry
11
11
  from .lib import *
12
- from .setting import *
12
+ from .setting import DatabaseConnectionSpec, Settings, ServerSettings
13
+ from .setting import get_app_namespace
13
14
  from ._engine import OpArgSchema
14
15
  from .typing import Float32, Float64, LocalDateTime, OffsetDateTime, Range, Vector, Json
Binary file
cocoindex/convert.py CHANGED
@@ -44,7 +44,7 @@ def make_engine_value_decoder(
44
44
 
45
45
  src_type_kind = src_type['kind']
46
46
 
47
- if dst_annotation is inspect.Parameter.empty:
47
+ if dst_annotation is None or dst_annotation is inspect.Parameter.empty or dst_annotation is Any:
48
48
  if src_type_kind == 'Struct' or src_type_kind in TABLE_TYPES:
49
49
  raise ValueError(f"Missing type annotation for `{''.join(field_path)}`."
50
50
  f"It's required for {src_type_kind} type.")
cocoindex/flow.py CHANGED
@@ -8,8 +8,9 @@ import asyncio
8
8
  import re
9
9
  import inspect
10
10
  import datetime
11
+ import functools
11
12
 
12
- from typing import Any, Callable, Sequence, TypeVar
13
+ from typing import Any, Callable, Sequence, TypeVar, Generic, get_args, get_origin, Type, NamedTuple
13
14
  from threading import Lock
14
15
  from enum import Enum
15
16
  from dataclasses import dataclass
@@ -20,7 +21,7 @@ from . import _engine
20
21
  from . import index
21
22
  from . import op
22
23
  from . import setting
23
- from .convert import dump_engine_object
24
+ from .convert import dump_engine_object, encode_engine_value, make_engine_value_decoder
24
25
  from .typing import encode_enriched_type
25
26
  from .runtime import execution_context
26
27
 
@@ -123,7 +124,7 @@ class _DataSliceState:
123
124
  # TODO: We'll support this by an identity transformer or "aliasing" in the future.
124
125
  raise ValueError("DataSlice is already attached to a field")
125
126
 
126
- class DataSlice:
127
+ class DataSlice(Generic[T]):
127
128
  """A data slice represents a slice of data in a flow. It's readonly."""
128
129
 
129
130
  _state: _DataSliceState
@@ -183,11 +184,11 @@ class DataSlice:
183
184
  name, prefix=_to_snake_case(_spec_kind(fn_spec))+'_'),
184
185
  ))
185
186
 
186
- def call(self, func: Callable[[DataSlice], T]) -> T:
187
+ def call(self, func: Callable[[DataSlice], T], *args, **kwargs) -> T:
187
188
  """
188
189
  Call a function with the data slice.
189
190
  """
190
- return func(self)
191
+ return func(self, *args, **kwargs)
191
192
 
192
193
  def _data_slice_state(data_slice: DataSlice) -> _DataSliceState:
193
194
  return data_slice._state # pylint: disable=protected-access
@@ -642,27 +643,67 @@ async def update_all_flows_async(options: FlowLiveUpdaterOptions) -> dict[str, _
642
643
  all_stats = await asyncio.gather(*(_update_flow(name, fl) for (name, fl) in fls.items()))
643
644
  return dict(all_stats)
644
645
 
645
- _transient_flow_name_builder = _NameBuilder()
646
- class TransientFlow:
646
+ def _get_data_slice_annotation_type(data_slice_type: Type[DataSlice[T]]) -> Type[T] | None:
647
+ type_args = get_args(data_slice_type)
648
+ if data_slice_type is DataSlice:
649
+ return None
650
+ if get_origin(data_slice_type) != DataSlice or len(type_args) != 1:
651
+ raise ValueError(f"Expect a DataSlice[T] type, but got {data_slice_type}")
652
+ return type_args[0]
653
+
654
+ _transform_flow_name_builder = _NameBuilder()
655
+
656
+ class TransformFlowInfo(NamedTuple):
657
+ engine_flow: _engine.TransientFlow
658
+ result_decoder: Callable[[Any], T]
659
+
660
+ class TransformFlow(Generic[T]):
647
661
  """
648
662
  A transient transformation flow that transforms in-memory data.
649
663
  """
650
- _engine_flow: _engine.TransientFlow
664
+ _flow_fn: Callable[..., DataSlice[T]]
665
+ _flow_name: str
666
+ _flow_arg_types: list[Any]
667
+ _param_names: list[str]
668
+
669
+ _lazy_lock: asyncio.Lock
670
+ _lazy_flow_info: TransformFlowInfo | None = None
651
671
 
652
672
  def __init__(
653
- self, flow_fn: Callable[..., DataSlice],
673
+ self, flow_fn: Callable[..., DataSlice[T]],
654
674
  flow_arg_types: Sequence[Any], /, name: str | None = None):
675
+ self._flow_fn = flow_fn
676
+ self._flow_name = _transform_flow_name_builder.build_name(name, prefix="_transform_flow_")
677
+ self._flow_arg_types = list(flow_arg_types)
678
+ self._lazy_lock = asyncio.Lock()
679
+
680
+ def __call__(self, *args, **kwargs) -> DataSlice[T]:
681
+ return self._flow_fn(*args, **kwargs)
655
682
 
656
- flow_builder_state = _FlowBuilderState(
657
- name=_transient_flow_name_builder.build_name(name, prefix="_transient_flow_"))
658
- sig = inspect.signature(flow_fn)
659
- if len(sig.parameters) != len(flow_arg_types):
683
+ @property
684
+ def _flow_info(self) -> TransformFlowInfo:
685
+ if self._lazy_flow_info is not None:
686
+ return self._lazy_flow_info
687
+ return execution_context.run(self._flow_info_async())
688
+
689
+ async def _flow_info_async(self) -> TransformFlowInfo:
690
+ if self._lazy_flow_info is not None:
691
+ return self._lazy_flow_info
692
+ async with self._lazy_lock:
693
+ if self._lazy_flow_info is None:
694
+ self._lazy_flow_info = await self._build_flow_info_async()
695
+ return self._lazy_flow_info
696
+
697
+ async def _build_flow_info_async(self) -> TransformFlowInfo:
698
+ flow_builder_state = _FlowBuilderState(name=self._flow_name)
699
+ sig = inspect.signature(self._flow_fn)
700
+ if len(sig.parameters) != len(self._flow_arg_types):
660
701
  raise ValueError(
661
702
  f"Number of parameters in the flow function ({len(sig.parameters)}) "
662
- "does not match the number of argument types ({len(flow_arg_types)})")
703
+ f"does not match the number of argument types ({len(self._flow_arg_types)})")
663
704
 
664
705
  kwargs: dict[str, DataSlice] = {}
665
- for (param_name, param), param_type in zip(sig.parameters.items(), flow_arg_types):
706
+ for (param_name, param), param_type in zip(sig.parameters.items(), self._flow_arg_types):
666
707
  if param.kind not in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
667
708
  inspect.Parameter.KEYWORD_ONLY):
668
709
  raise ValueError(f"Parameter {param_name} is not a parameter can be passed by name")
@@ -670,20 +711,68 @@ class TransientFlow:
670
711
  param_name, encode_enriched_type(param_type))
671
712
  kwargs[param_name] = DataSlice(_DataSliceState(flow_builder_state, engine_ds))
672
713
 
673
- output = flow_fn(**kwargs)
714
+ output = self._flow_fn(**kwargs)
674
715
  flow_builder_state.engine_flow_builder.set_direct_output(
675
716
  _data_slice_state(output).engine_data_slice)
676
- self._engine_flow = flow_builder_state.engine_flow_builder.build_transient_flow(
677
- execution_context.event_loop)
717
+ engine_flow = await flow_builder_state.engine_flow_builder.build_transient_flow_async(execution_context.event_loop)
718
+ self._param_names = list(sig.parameters.keys())
719
+
720
+ engine_return_type = _data_slice_state(output).engine_data_slice.data_type().schema()
721
+ python_return_type = _get_data_slice_annotation_type(sig.return_annotation)
722
+ result_decoder = make_engine_value_decoder([], engine_return_type['type'], python_return_type)
723
+
724
+ return TransformFlowInfo(engine_flow, result_decoder)
678
725
 
679
726
  def __str__(self):
680
- return str(self._engine_flow)
727
+ return str(self._flow_info.engine_flow)
681
728
 
682
729
  def __repr__(self):
683
- return repr(self._engine_flow)
730
+ return repr(self._flow_info.engine_flow)
684
731
 
685
732
  def internal_flow(self) -> _engine.TransientFlow:
686
733
  """
687
734
  Get the internal flow.
688
735
  """
689
- return self._engine_flow
736
+ return self._flow_info.engine_flow
737
+
738
+ def eval(self, *args, **kwargs) -> T:
739
+ """
740
+ Evaluate the transform flow.
741
+ """
742
+ return execution_context.run(self.eval_async(*args, **kwargs))
743
+
744
+ async def eval_async(self, *args, **kwargs) -> T:
745
+ """
746
+ Evaluate the transform flow.
747
+ """
748
+ flow_info = await self._flow_info_async()
749
+ params = []
750
+ for i, arg in enumerate(self._param_names):
751
+ if i < len(args):
752
+ params.append(encode_engine_value(args[i]))
753
+ elif arg in kwargs:
754
+ params.append(encode_engine_value(kwargs[arg]))
755
+ else:
756
+ raise ValueError(f"Parameter {arg} is not provided")
757
+ engine_result = await flow_info.engine_flow.evaluate_async(params)
758
+ return flow_info.result_decoder(engine_result)
759
+
760
+
761
+ def transform_flow() -> Callable[[Callable[..., DataSlice[T]]], TransformFlow[T]]:
762
+ """
763
+ A decorator to wrap the transform function.
764
+ """
765
+ def _transform_flow_wrapper(fn: Callable[..., DataSlice[T]]):
766
+ sig = inspect.signature(fn)
767
+ arg_types = []
768
+ for (param_name, param) in sig.parameters.items():
769
+ if param.kind not in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
770
+ inspect.Parameter.KEYWORD_ONLY):
771
+ raise ValueError(f"Parameter {param_name} is not a parameter can be passed by name")
772
+ arg_types.append(_get_data_slice_annotation_type(param.annotation))
773
+
774
+ _transform_flow = TransformFlow(fn, arg_types)
775
+ functools.update_wrapper(_transform_flow, fn)
776
+ return _transform_flow
777
+
778
+ return _transform_flow_wrapper
cocoindex/op.py CHANGED
@@ -100,8 +100,8 @@ def _register_op_factory(
100
100
  return op_args.behavior_version
101
101
 
102
102
  class _WrappedClass(executor_cls, _Fallback):
103
- _args_converters: list[Callable[[Any], Any]]
104
- _kwargs_converters: dict[str, Callable[[str, Any], Any]]
103
+ _args_decoders: list[Callable[[Any], Any]]
104
+ _kwargs_decoders: dict[str, Callable[[str, Any], Any]]
105
105
  _acall: Callable
106
106
 
107
107
  def __init__(self, spec):
@@ -109,17 +109,17 @@ def _register_op_factory(
109
109
  self.spec = spec
110
110
  self._acall = _to_async_call(super().__call__)
111
111
 
112
- def analyze(self, *args, **kwargs):
112
+ def analyze(self, *args: _engine.OpArgSchema, **kwargs: _engine.OpArgSchema):
113
113
  """
114
114
  Analyze the spec and arguments. In this phase, argument types should be validated.
115
115
  It should return the expected result type for the current op.
116
116
  """
117
- self._args_converters = []
118
- self._kwargs_converters = {}
117
+ self._args_decoders = []
118
+ self._kwargs_decoders = {}
119
119
 
120
120
  # Match arguments with parameters.
121
121
  next_param_idx = 0
122
- for arg in args:
122
+ for arg in args:
123
123
  if next_param_idx >= len(expected_args):
124
124
  raise ValueError(
125
125
  f"Too many arguments passed in: {len(args)} > {len(expected_args)}")
@@ -128,7 +128,7 @@ def _register_op_factory(
128
128
  inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.VAR_KEYWORD):
129
129
  raise ValueError(
130
130
  f"Too many positional arguments passed in: {len(args)} > {next_param_idx}")
131
- self._args_converters.append(
131
+ self._args_decoders.append(
132
132
  make_engine_value_decoder(
133
133
  [arg_name], arg.value_type['type'], arg_param.annotation))
134
134
  if arg_param.kind != inspect.Parameter.VAR_POSITIONAL:
@@ -146,7 +146,7 @@ def _register_op_factory(
146
146
  if expected_arg is None:
147
147
  raise ValueError(f"Unexpected keyword argument passed in: {kwarg_name}")
148
148
  arg_param = expected_arg[1]
149
- self._kwargs_converters[kwarg_name] = make_engine_value_decoder(
149
+ self._kwargs_decoders[kwarg_name] = make_engine_value_decoder(
150
150
  [kwarg_name], kwarg.value_type['type'], arg_param.annotation)
151
151
 
152
152
  missing_args = [name for (name, arg) in expected_kwargs
@@ -174,8 +174,8 @@ def _register_op_factory(
174
174
  await _to_async_call(setup_method)()
175
175
 
176
176
  async def __call__(self, *args, **kwargs):
177
- converted_args = (converter(arg) for converter, arg in zip(self._args_converters, args))
178
- converted_kwargs = {arg_name: self._kwargs_converters[arg_name](arg)
177
+ decoded_args = (decoder(arg) for decoder, arg in zip(self._args_decoders, args))
178
+ decoded_kwargs = {arg_name: self._kwargs_decoders[arg_name](arg)
179
179
  for arg_name, arg in kwargs.items()}
180
180
 
181
181
  if op_args.gpu:
@@ -185,9 +185,9 @@ def _register_op_factory(
185
185
  # For now, we use a lock to ensure only one task is executed at a time.
186
186
  # TODO: Implement multi-processing dispatching.
187
187
  async with _gpu_dispatch_lock:
188
- output = await self._acall(*converted_args, **converted_kwargs)
188
+ output = await self._acall(*decoded_args, **decoded_kwargs)
189
189
  else:
190
- output = await self._acall(*converted_args, **converted_kwargs)
190
+ output = await self._acall(*decoded_args, **decoded_kwargs)
191
191
  return encode_engine_value(output)
192
192
 
193
193
  _WrappedClass.__name__ = executor_cls.__name__
cocoindex/query.py CHANGED
@@ -50,7 +50,7 @@ class SimpleSemanticsQueryHandler:
50
50
  if engine_handler is None:
51
51
  engine_handler = _engine.SimpleSemanticsQueryHandler(
52
52
  flow.internal_flow(), target_name,
53
- fl.TransientFlow(query_transform_flow, [str]).internal_flow(),
53
+ fl.TransformFlow(query_transform_flow, [str]).internal_flow(),
54
54
  default_similarity_metric.value)
55
55
  engine_handler.register_query_handler(name)
56
56
  return engine_handler
cocoindex/setting.py CHANGED
@@ -49,7 +49,7 @@ def _load_field(target: dict[str, Any], name: str, env_name: str, required: bool
49
49
  class Settings:
50
50
  """Settings for the cocoindex library."""
51
51
  database: DatabaseConnectionSpec
52
- app_namespace: str
52
+ app_namespace: str = ""
53
53
 
54
54
  @classmethod
55
55
  def from_env(cls) -> Self:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoindex
3
- Version: 0.1.38
3
+ Version: 0.1.39
4
4
  Requires-Dist: sentence-transformers>=3.3.1
5
5
  Requires-Dist: click>=8.1.8
6
6
  Requires-Dist: rich>=14.0.0
@@ -1,25 +1,25 @@
1
- cocoindex-0.1.38.dist-info/METADATA,sha256=F04y39dSBt_UKZkInX4seXLMjI-bPLW3WYVD7mZSsnQ,9958
2
- cocoindex-0.1.38.dist-info/WHEEL,sha256=Kw8y023UaufEXFM028WbBCk7rJUUAhAX1Zw-54pv0m4,96
3
- cocoindex-0.1.38.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
4
- cocoindex/__init__.py,sha256=euvHrtzQEXtAEut0EFlgcc4VtogA6zltqWRdt70Zgrg,703
5
- cocoindex/_engine.cp311-win_amd64.pyd,sha256=OKJEyUBeM0IofIMrcK4Nza4Emfg6_KhJ47EM7TkI4fQ,60772352
1
+ cocoindex-0.1.39.dist-info/METADATA,sha256=pnwutYA2ul-s26Xw4BkP6nqpTCoye74FvOqRPw1AOEk,9958
2
+ cocoindex-0.1.39.dist-info/WHEEL,sha256=Kw8y023UaufEXFM028WbBCk7rJUUAhAX1Zw-54pv0m4,96
3
+ cocoindex-0.1.39.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
4
+ cocoindex/__init__.py,sha256=pHcVzNeWewxtx9gKiPnTB8jLjuFlX9Bw9hX1cEGOWvI,806
5
+ cocoindex/_engine.cp311-win_amd64.pyd,sha256=DM4eY3Dq3MlYvk6doOpMFTvqMzsVlsWCiK9G9XCwSco,60931584
6
6
  cocoindex/auth_registry.py,sha256=-EhwmyIwJLPZthPOvEK21TfMbxQtndRbogk8q7y4XuU,716
7
7
  cocoindex/cli.py,sha256=iJUQ2GSI8iHW3wfKRxHH5nixug92imPVmTalOjUVa3w,9237
8
- cocoindex/convert.py,sha256=XT747PZcerRGlsaJ69mZoG-7Z4ruwDNX1pO0VlGKlwY,7034
9
- cocoindex/flow.py,sha256=CjcMmx_2HcDkgy7qEs0fXRpNZFi3-4ajOAegR0veamE,24503
8
+ cocoindex/convert.py,sha256=Co8MhwbnGWONu2mkrQYzFM1gw3stOIdFHueT1mszdV4,7085
9
+ cocoindex/flow.py,sha256=xMJM0vzTrx4PHgQ5OxktCaBW1q54B_E11MpP-a_SD-s,28396
10
10
  cocoindex/functions.py,sha256=m7R8gNVK5RcavPY37d2lkRXwLBdMblZexCJ0JYcruss,1881
11
11
  cocoindex/index.py,sha256=32iiQI60VKhRRHle17rpoEVa_tsAHnyXXXnrLaX68uQ,557
12
12
  cocoindex/lib.py,sha256=Yv3_qKESgrjxJRYQn8a89aZcEoLZ5-xewgfEN0l9K1w,2461
13
13
  cocoindex/llm.py,sha256=POMdB-huMvPkRDpvcaBeOgXfbm0YZa0swNOdD2s4TRc,364
14
- cocoindex/op.py,sha256=PeoBddukU5vOBvUrFPC6fYH35L59THy9ZXVm_Vc2ng0,10998
14
+ cocoindex/op.py,sha256=B1P7vCmrcuBuxnX8tHqGvfFgUMRBu4Om2VFnzk00MpI,11007
15
15
  cocoindex/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
- cocoindex/query.py,sha256=GU3V8AoSK--xOU2yX0Ao-Rz1t3mlrsJ4JIhzsLVwFH8,3297
16
+ cocoindex/query.py,sha256=ljsylpRRxEpBXQakE2_4a89wWLYXTCE9HjacyjhxsQw,3297
17
17
  cocoindex/runtime.py,sha256=WwyDSpJhvaHjnxH4q6r2MVftJB-QkNVH_TxZLxuDtFw,1009
18
- cocoindex/setting.py,sha256=SODjbKgIM9_E9VEwMWcwR7BpuwEVl3Iypg1_eFdZfho,3359
18
+ cocoindex/setting.py,sha256=dTtUD_L2b4Jf2w1-Dt8M1eFMpYQV9sMS95fJ4wB_9-I,3364
19
19
  cocoindex/setup.py,sha256=YAH9ssZB27MXYvsiqtBA1IDjAfeUci--d3cjFE76i0Y,767
20
20
  cocoindex/sources.py,sha256=W5wgiNwhTjPyNxt3DLKBbOnGwrHHfi36b9Gfr1GYhe0,1369
21
21
  cocoindex/storages.py,sha256=oJcY_zZx1wXjoJ_gitSvaFTUqhL6lUJihZQivvMMZ5U,2292
22
22
  cocoindex/tests/__init__.py,sha256=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN_XKdLCPjaYaY,2
23
23
  cocoindex/tests/test_convert.py,sha256=XbjzUoKazBJyBRCPaNElbRGoDD4NJZ9J-i4el39O7w8,15863
24
24
  cocoindex/typing.py,sha256=ZZ-QqkfNNSRkzqWahx-8w3X4upjy4kyIFr7OAPWYz5Q,9232
25
- cocoindex-0.1.38.dist-info/RECORD,,
25
+ cocoindex-0.1.39.dist-info/RECORD,,