matchescu-reference-extraction 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 matchescu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.1
2
+ Name: matchescu-reference-extraction
3
+ Version: 0.1.0
4
+ Summary: Extract references from a multitude of data sources
5
+ License: MIT
6
+ Author: Andrei Olar
7
+ Author-email: andrei.olar@samlex.ro
8
+ Requires-Python: >=3.12,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Requires-Dist: matchescu-base (>=0.10.0,<0.11.0)
14
+ Requires-Dist: polars (>=1.25.2,<2.0.0)
15
+ Description-Content-Type: text/markdown
16
+
17
+ from matchescu.data_sources import CsvDataSource
18
+
19
+ # matchescu-reference-extraction
20
+
21
+ This package implements an entity reference extraction subsystem for entity
22
+ resolution.
23
+ The main concepts that are relevant here are:
24
+
25
+ * a generic attribute-based data record implementation (can access data by `str`
26
+ or `int` key),
27
+ * various `data_sources` which support reading records from different data
28
+ stores, and
29
+ * generic `extraction_engines` that convert data records to entity references.
30
+
31
+ # Development
32
+
33
+ Run the following commands to ensure you have a proper environment.
34
+
35
+ ```shell
36
+ $ pyenv install 3.12
37
+ $ poetry install
38
+ $ poetry run pytest
39
+ ```
40
+
41
+ When you contribute code, open a new `feature/*` or `hotfix/*` branch.
42
+
43
+ # Usage
44
+
45
+ ```python
46
+ from matchescu.data_sources import CsvDataSource
47
+ from matchescu.extraction import Traits
48
+
49
+ traits = list(
50
+ Traits().int(["id"])
51
+ .string(["name", "description", "manufacturer"])
52
+ .currency(["price"])
53
+ )
54
+ csv = CsvDataSource("./path/to/csv/file", list(traits))
55
+
56
+ ```
@@ -0,0 +1,40 @@
1
+ from matchescu.data_sources import CsvDataSource
2
+
3
+ # matchescu-reference-extraction
4
+
5
+ This package implements an entity reference extraction subsystem for entity
6
+ resolution.
7
+ The main concepts that are relevant here are:
8
+
9
+ * a generic attribute-based data record implementation (can access data by `str`
10
+ or `int` key),
11
+ * various `data_sources` which support reading records from different data
12
+ stores, and
13
+ * generic `extraction_engines` that convert data records to entity references.
14
+
15
+ # Development
16
+
17
+ Run the following commands to ensure you have a proper environment.
18
+
19
+ ```shell
20
+ $ pyenv install 3.12
21
+ $ poetry install
22
+ $ poetry run pytest
23
+ ```
24
+
25
+ When you contribute code, open a new `feature/*` or `hotfix/*` branch.
26
+
27
+ # Usage
28
+
29
+ ```python
30
+ from matchescu.data_sources import CsvDataSource
31
+ from matchescu.extraction import Traits
32
+
33
+ traits = list(
34
+ Traits().int(["id"])
35
+ .string(["name", "description", "manufacturer"])
36
+ .currency(["price"])
37
+ )
38
+ csv = CsvDataSource("./path/to/csv/file", list(traits))
39
+
40
+ ```
@@ -0,0 +1,23 @@
1
+ [tool.poetry]
2
+ name = "matchescu-reference-extraction"
3
+ version = "0.1.0"
4
+ description = "Extract references from a multitude of data sources"
5
+ authors = ["Andrei Olar <andrei.olar@samlex.ro>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ packages = [{include="matchescu", from="src"}]
9
+
10
+ [tool.poetry.dependencies]
11
+ python = "^3.12"
12
+ matchescu-base = "^0.10.0"
13
+ polars = "^1.25.2"
14
+
15
+ [tool.poetry.group.dev.dependencies]
16
+ black = "^25.1.0"
17
+ pytest = "^8.3.5"
18
+ mypy = "^1.15.0"
19
+ ruff = "^0.11.0"
20
+
21
+ [build-system]
22
+ requires = ["poetry-core"]
23
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,5 @@
1
+ from matchescu.data_sources._record import Record
2
+ from matchescu.data_sources._csv import CsvDataSource
3
+
4
+
5
+ __all__ = ["Record", "CsvDataSource"]
@@ -0,0 +1,39 @@
1
+ from collections.abc import Sequence, Iterator
2
+ from os import PathLike
3
+ from pathlib import Path
4
+
5
+ import polars as pl
6
+
7
+ from matchescu.typing import Trait
8
+
9
+ from matchescu.data_sources._record import Record
10
+
11
+
12
+ class CsvDataSource:
13
+ def __init__(
14
+ self,
15
+ file_path: str | PathLike,
16
+ traits: Sequence[Trait],
17
+ has_header: bool = True,
18
+ ):
19
+ file_path = Path(file_path)
20
+ self.name = file_path.name.replace(file_path.suffix, "")
21
+ self.traits = traits
22
+
23
+ self.__file_path = file_path
24
+ self.__df: pl.DataFrame | None = None
25
+ self.__header = has_header
26
+
27
+ def read(self) -> "CsvDataSource":
28
+ self.__df = pl.read_csv(
29
+ self.__file_path, ignore_errors=True, has_header=self.__header
30
+ )
31
+ return self
32
+
33
+ def __iter__(self) -> Iterator[Record]:
34
+ if self.__df is None:
35
+ return iter([])
36
+ return iter(map(Record, self.__df.iter_rows(named=True)))
37
+
38
+ def __len__(self) -> int:
39
+ return self.__df.shape[0] if self.__df is not None else 0
@@ -0,0 +1,30 @@
1
+ from typing import Iterable, Iterator
2
+
3
+ from matchescu.typing import Trait
4
+ from matchescu.data_sources._record import Record
5
+
6
+
7
+ class ListDataSource:
8
+ def __init__(self, name: str, traits: Iterable[Trait]):
9
+ self.name = name
10
+ self.traits = traits
11
+ self._items: list[Record] = []
12
+
13
+ def append(self, item: Record | Iterable[Record]) -> "ListDataSource":
14
+ if isinstance(item, Iterable):
15
+ item = Record.merge(item)
16
+ self._items.append(item)
17
+ return self
18
+
19
+ def extend(
20
+ self, items: Iterable[Record] | Iterable[Iterable[Record]]
21
+ ) -> "ListDataSource":
22
+ for item in items:
23
+ self.append(item)
24
+ return self
25
+
26
+ def __iter__(self) -> Iterator[Record]:
27
+ return iter(self._items)
28
+
29
+ def __len__(self) -> int:
30
+ return len(self._items)
@@ -0,0 +1,57 @@
1
+ from collections.abc import Iterable
2
+ from typing import Any, Iterator
3
+
4
+
5
+ class Record:
6
+ def __init__(self, value: Iterable) -> None:
7
+ if isinstance(value, Record):
8
+ self.__values = value.__values
9
+ self.__attr_names = value.__attr_names
10
+ else:
11
+ tuples = list(self.__init_data(value))
12
+ self.__values = tuple(x[1] for x in tuples)
13
+ self.__attr_names = {x[0]: i for i, x in enumerate(tuples)}
14
+
15
+ @staticmethod
16
+ def __get_attr_key(key: str | int) -> str:
17
+ return f"column_{key}" if isinstance(key, int) else key
18
+
19
+ @staticmethod
20
+ def merge(records: Iterable["Record"]) -> "Record":
21
+ merge_record = {}
22
+ for record in records:
23
+ merge_record.update(
24
+ {k: record.__values[i] for k, i in record.__attr_names.items()}
25
+ )
26
+ return Record(merge_record)
27
+
28
+ def __init_data(self, value: Iterable) -> Iterable[tuple]:
29
+ if isinstance(value, dict):
30
+ return ((self.__get_attr_key(k), v) for k, v in value.items())
31
+ elif isinstance(value, (tuple, list, set)):
32
+ return ((self.__get_attr_key(i), v) for i, v in enumerate(value, start=1))
33
+ raise ValueError(
34
+ f"can't initialize data record from '{type(value).__name__}' values"
35
+ )
36
+
37
+ def __getitem__(self, key: str | int) -> Any:
38
+ if isinstance(key, str):
39
+ return (
40
+ self.__values[self.__attr_names[key]]
41
+ if key in self.__attr_names
42
+ else None
43
+ )
44
+ elif isinstance(key, int):
45
+ return self.__values[key]
46
+ raise ValueError(f"can't get data record using '{type(key).__name__}' keys")
47
+
48
+ def __getattr__(self, key: str) -> Any:
49
+ if key not in self.__attr_names:
50
+ raise AttributeError(f"Record attribute '{key}' not found")
51
+ return self[key]
52
+
53
+ def __len__(self) -> int:
54
+ return len(self.__values)
55
+
56
+ def __iter__(self) -> Iterator[Any]:
57
+ return iter(self.__values)
@@ -0,0 +1,10 @@
1
+ from matchescu.extraction._traits import Traits
2
+ from matchescu.extraction._basic import EntityReferenceExtractionFromRecords
3
+ from matchescu.extraction._csv import CsvEntityReferenceExtraction
4
+
5
+
6
+ __all__ = [
7
+ "CsvEntityReferenceExtraction",
8
+ "EntityReferenceExtractionFromRecords",
9
+ "Traits",
10
+ ]
@@ -0,0 +1,9 @@
1
+ from typing import Iterable
2
+ from matchescu.data import EntityReferenceExtraction
3
+
4
+ from matchescu.data_sources._record import Record
5
+
6
+
7
+ class EntityReferenceExtractionFromRecords(EntityReferenceExtraction[Record]):
8
+ def _merge_records(self, records: Iterable[Record]) -> Record:
9
+ return Record.merge(records)
@@ -0,0 +1,20 @@
1
+ from typing import Generator
2
+ from matchescu.typing import RecordAdapter, DataSource
3
+
4
+ from matchescu.data_sources import CsvDataSource
5
+ from matchescu.extraction._basic import EntityReferenceExtractionFromRecords
6
+
7
+
8
+ class CsvEntityReferenceExtraction(EntityReferenceExtractionFromRecords):
9
+ def __init__(
10
+ self,
11
+ ds: CsvDataSource,
12
+ record_adapter: RecordAdapter,
13
+ ):
14
+ super().__init__(
15
+ ds, record_adapter, CsvEntityReferenceExtraction._sample_csv_records
16
+ )
17
+
18
+ @staticmethod
19
+ def _sample_csv_records(ds: DataSource) -> Generator[list, None, None]:
20
+ yield from map(lambda x: [x], ds)
@@ -0,0 +1,62 @@
1
+ import locale
2
+
3
+ from typing import Any, Callable, Iterator, Union
4
+
5
+ from matchescu.typing import Trait
6
+ from matchescu.data_sources import Record
7
+
8
+
9
+ def _process_string(value: Any) -> str:
10
+ return str(value)
11
+
12
+
13
+ def _process_int(value: Any) -> int:
14
+ return int(value)
15
+
16
+
17
+ def _process_float(value: Any) -> float:
18
+ return float(value)
19
+
20
+
21
+ def _process_currency(value: Any) -> float | None:
22
+ if value is None:
23
+ return None
24
+ str_val = str(value).replace(",", "").strip()
25
+ return locale.atof(str_val.lstrip("$"))
26
+
27
+
28
+ class RecordExtractionTrait:
29
+ def __init__(self, mapping: Callable[[Any], Any], keys: list[int | str]) -> None:
30
+ self.__mapping = mapping
31
+ self.__keys = keys
32
+
33
+ def __call__(self, input_records: list[Record]) -> Record:
34
+ if len(input_records) == 0:
35
+ return Record([])
36
+ return Record(
37
+ {key: self.__mapping(input_records[0][key]) for key in self.__keys}
38
+ )
39
+
40
+
41
+ class Traits:
42
+ def __init__(self):
43
+ self._traits = []
44
+
45
+ def string(self, keys: list[Union[int, str]]) -> "Traits":
46
+ self._traits.append(RecordExtractionTrait(_process_string, keys))
47
+ return self
48
+
49
+ def int(self, keys: list[Union[int, str]]) -> "Traits":
50
+ self._traits.append(RecordExtractionTrait(_process_int, keys))
51
+ return self
52
+
53
+ def float(self, keys: list[Union[int, str]]) -> "Traits":
54
+ self._traits.append(RecordExtractionTrait(_process_float, keys))
55
+ return self
56
+
57
+ def currency(self, keys: list[Union[int, str]]) -> "Traits":
58
+ self._traits.append(RecordExtractionTrait(_process_currency, keys))
59
+ return self
60
+
61
+ def __iter__(self) -> Iterator[Trait]:
62
+ return iter(self._traits)