Skip to content

Commit 884dd7d

Browse files
chore(knowledge-graph): restructure package
1 parent 2007981 commit 884dd7d

File tree

10 files changed

+243
-139
lines changed

10 files changed

+243
-139
lines changed

libs/community/google/knowledge-graph/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919

2020
### Run as a library
2121
```
22-
from garf_knowledge_graph_api import report_fetcher
23-
from garf_io import writer
22+
from garf.community.google.knowledge_graph import report_fetcher
23+
from garf.io import writer
2424
2525
2626
# Specify query
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Defines simplified imports."""
16+
17+
from __future__ import annotations
18+
19+
from garf.community.google.knowledge_graph.api_clients import (
20+
KnowledgeGraphApiClient,
21+
)
22+
from garf.community.google.knowledge_graph.report_fetcher import (
23+
KnowledgeGraphApiReportFetcher,
24+
)
25+
26+
__all__ = [
27+
'KnowledgeGraphApiClient',
28+
'KnowledgeGraphApiReportFetcher',
29+
]
30+
31+
__version__ = '0.0.1'
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
"""Creates API client for Knowledge Graph Search API."""
15+
16+
import os
17+
18+
import requests
19+
from garf.core import api_clients, query_editor
20+
from typing_extensions import override
21+
22+
23+
class KnowledgeGraphApiClient(api_clients.BaseClient):
24+
def __init__(
25+
self,
26+
api_key: str = os.getenv('KG_API_KEY'),
27+
**kwargs: str,
28+
) -> None:
29+
"""Initializes KnowledgeGraphApiClient."""
30+
self.api_key = api_key
31+
self.query_args = kwargs
32+
33+
@override
34+
def get_response(
35+
self, request: query_editor.BaseQueryElements, **kwargs: str
36+
) -> api_clients.GarfApiResponse:
37+
service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
38+
params = {
39+
request.resource_name: request.filters,
40+
'limit': 100,
41+
'key': self.api_key,
42+
}
43+
response = requests.get(service_url, params=params)
44+
results = []
45+
for result in response.json().get('itemListElement', []):
46+
tmp_result = result.get('result')
47+
tmp_result.update({'result_score': result.get('resultScore')})
48+
results.append(tmp_result)
49+
return api_clients.GarfApiResponse(results=results)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
"""Defines KnowledgeGraphApiQuery."""
15+
16+
from garf.core import query_editor
17+
from typing_extensions import Self
18+
19+
20+
class KnowledgeGraphApiQuery(query_editor.QuerySpecification):
21+
"""Query to Knowledge Graph Search api."""
22+
23+
def __init__(
24+
self,
25+
text: str,
26+
title: str | None = None,
27+
args: dict[str, str] | None = None,
28+
**kwargs,
29+
) -> None:
30+
"""Initializes KnowledgeGraphApiQuery."""
31+
super().__init__(text, title, args, **kwargs)
32+
33+
def extract_column_names(self) -> Self:
34+
"""Removes extra symbols from column names."""
35+
for line in self._extract_query_lines():
36+
line_elements = query_editor.ExtractedLineElements.from_query_line(line)
37+
self.query.column_names.append(line_elements.alias.replace('@', ''))
38+
return self
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Defines report fetcher."""
16+
17+
import functools
18+
import itertools
19+
import operator
20+
from collections.abc import Iterable, MutableSequence
21+
from typing import Any, Final
22+
23+
from garf.community.google.knowledge_graph import (
24+
KnowledgeGraphApiClient,
25+
query_editor,
26+
)
27+
from garf.core import parsers, report, report_fetcher
28+
from typing_extensions import override
29+
30+
ALLOWED_QUERY_PARAMETERS: Final[set[str]] = (
31+
'query',
32+
'ids',
33+
'languages',
34+
'prefix',
35+
)
36+
37+
MAX_BATCH_SIZE: Final[int] = 100
38+
39+
40+
def _batched(iterable: Iterable[str], chunk_size: int):
41+
iterator = iter(iterable)
42+
while chunk := list(itertools.islice(iterator, chunk_size)):
43+
yield chunk
44+
45+
46+
class KnowledgeGraphApiReportFetcher(report_fetcher.ApiReportFetcher):
47+
"""Defines report fetcher."""
48+
49+
def __init__(
50+
self,
51+
api_client: KnowledgeGraphApiClient = KnowledgeGraphApiClient(),
52+
parser: parsers.BaseParser = parsers.NumericConverterDictParser,
53+
query_spec: query_editor.KnowledgeGraphApiQuery = (
54+
query_editor.KnowledgeGraphApiQuery,
55+
),
56+
**kwargs: str,
57+
) -> None:
58+
"""Initializes KnowledgeGraphApiReportFetcher."""
59+
super().__init__(api_client, parser, query_spec, **kwargs)
60+
61+
@override
62+
def fetch(
63+
self,
64+
query_specification,
65+
args: dict[str, Any] = None,
66+
**kwargs,
67+
) -> report.GarfReport:
68+
results = []
69+
filter_identifier = list(
70+
set(ALLOWED_QUERY_PARAMETERS).intersection(set(kwargs.keys()))
71+
)
72+
if len(filter_identifier) == 1:
73+
name = filter_identifier[0]
74+
ids = kwargs.pop(name)
75+
if not isinstance(ids, MutableSequence):
76+
ids = ids.split(',')
77+
else:
78+
return super().fetch(query_specification, args, **kwargs)
79+
for batch in _batched(ids, MAX_BATCH_SIZE):
80+
batch_ids = {name: batch[0]} if name != 'id' else {name: batch}
81+
results.append(
82+
super().fetch(query_specification, args, **batch_ids, **kwargs)
83+
)
84+
return functools.reduce(operator.add, results)
Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2024 Google LLC
1+
# Copyright 2026 Google LLC
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -12,18 +12,13 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Defines simplified imports."""
15+
import warnings
1616

17-
from __future__ import annotations
17+
from garf.community.google.knowledge_graph import *
1818

19-
from garf_knowledge_graph_api.api_clients import KnowledgeGraphApiClient
20-
from garf_knowledge_graph_api.report_fetcher import (
21-
KnowledgeGraphApiReportFetcher,
19+
warnings.warn(
20+
"The 'garf_knowledge_graph_api' namespace is deprecated. "
21+
"Please use 'garf.community.google.knowledge_graph' instead.",
22+
DeprecationWarning,
23+
stacklevel=2,
2224
)
23-
24-
__all__ = [
25-
'KnowledgeGraphApiClient',
26-
'KnowledgeGraphApiReportFetcher',
27-
]
28-
29-
__version__ = '0.0.1'
Lines changed: 9 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2025 Google LLC
1+
# Copyright 2026 Google LLC
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -11,39 +11,14 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
"""Creates API client for Knowledge Graph Search API."""
1514

16-
import os
15+
import warnings
1716

18-
import requests
19-
from garf_core import api_clients, query_editor
20-
from typing_extensions import override
17+
from garf.community.google.knowledge_graph.api_clients import *
2118

22-
23-
class KnowledgeGraphApiClient(api_clients.BaseClient):
24-
def __init__(
25-
self,
26-
api_key: str = os.getenv('KG_API_KEY'),
27-
**kwargs: str,
28-
) -> None:
29-
"""Initializes KnowledgeGraphApiClient."""
30-
self.api_key = api_key
31-
self.query_args = kwargs
32-
33-
@override
34-
def get_response(
35-
self, request: query_editor.BaseQueryElements, **kwargs: str
36-
) -> api_clients.GarfApiResponse:
37-
service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
38-
params = {
39-
request.resource_name: request.filters,
40-
'limit': 100,
41-
'key': self.api_key,
42-
}
43-
response = requests.get(service_url, params=params)
44-
results = []
45-
for result in response.json().get('itemListElement', []):
46-
tmp_result = result.get('result')
47-
tmp_result.update({'result_score': result.get('resultScore')})
48-
results.append(tmp_result)
49-
return api_clients.GarfApiResponse(results=results)
19+
warnings.warn(
20+
"The 'garf_knowledge_graph_api' namespace is deprecated. "
21+
"Please use 'garf.community.google.knowledge_graph' instead.",
22+
DeprecationWarning,
23+
stacklevel=2,
24+
)
Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2025 Google LLC
1+
# Copyright 2026 Google LLC
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -11,28 +11,14 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
"""Defines KnowledgeGraphApiQuery."""
1514

16-
from garf_core import query_editor
17-
from typing_extensions import Self
15+
import warnings
1816

17+
from garf.community.google.knowledge_graph.query_editor import *
1918

20-
class KnowledgeGraphApiQuery(query_editor.QuerySpecification):
21-
"""Query to Knowledge Graph Search api."""
22-
23-
def __init__(
24-
self,
25-
text: str,
26-
title: str | None = None,
27-
args: dict[str, str] | None = None,
28-
**kwargs,
29-
) -> None:
30-
"""Initializes KnowledgeGraphApiQuery."""
31-
super().__init__(text, title, args, **kwargs)
32-
33-
def extract_column_names(self) -> Self:
34-
"""Removes extra symbols from column names."""
35-
for line in self._extract_query_lines():
36-
line_elements = query_editor.ExtractedLineElements.from_query_line(line)
37-
self.query.column_names.append(line_elements.alias.replace('@', ''))
38-
return self
19+
warnings.warn(
20+
"The 'garf_knowledge_graph_api' namespace is deprecated. "
21+
"Please use 'garf.community.google.knowledge_graph' instead.",
22+
DeprecationWarning,
23+
stacklevel=2,
24+
)

0 commit comments

Comments
 (0)