wordlift-sdk 2.7.6__py3-none-any.whl → 2.9.0__py3-none-any.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.
@@ -0,0 +1,3 @@
1
+ from .google_sheets_lookup import GoogleSheetsLookup
2
+
3
+ __all__ = ["GoogleSheetsLookup"]
@@ -0,0 +1,121 @@
1
+ import logging
2
+ import os
3
+ from typing import Optional, Any, Dict
4
+
5
+ import gspread
6
+ from wordlift_sdk.configuration import ConfigurationProvider
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class GoogleSheetsLookup:
12
+ """
13
+ A generic class to lookup values from a Google Sheet.
14
+ Preloads data upon initialization for O(1) lookup performance.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ spreadsheet_url: str,
20
+ sheet_name: str,
21
+ key_column: str,
22
+ value_column: str,
23
+ configuration_provider: ConfigurationProvider,
24
+ service_account_file: Optional[str] = None,
25
+ ):
26
+ """
27
+ Initialize the GoogleSheetsLookup.
28
+
29
+ :param spreadsheet_url: The URL of the Google Sheet.
30
+ :param sheet_name: The name of the specific worksheet (tab).
31
+ :param key_column: The header name of the column to use as keys.
32
+ :param value_column: The header name of the column to use as values.
33
+ :param configuration_provider: The ConfigurationProvider instance.
34
+ :param service_account_file: Optional path to the service account JSON file.
35
+ If not provided, it will be looked up in the configuration.
36
+ """
37
+ self.spreadsheet_url = spreadsheet_url
38
+ self.sheet_name = sheet_name
39
+ self.key_column = key_column
40
+ self.value_column = value_column
41
+ self.configuration_provider = configuration_provider
42
+ self.service_account_file = service_account_file
43
+
44
+ self._data: Dict[str, Any] = {}
45
+ self._load_data()
46
+
47
+ def _resolve_service_account_file(self) -> Optional[str]:
48
+ """
49
+ Resolves the service account file path.
50
+ Priority:
51
+ 1. Argument passed to __init__
52
+ 2. 'SERVICE_ACCOUNT_FILE' from ConfigurationProvider
53
+ """
54
+ if self.service_account_file:
55
+ return self.service_account_file
56
+
57
+ # Attempt to retrieve from ConfigurationProvider
58
+ return self.configuration_provider.get_value("SERVICE_ACCOUNT_FILE")
59
+
60
+ # Fallback: check environment variable directly if ConfigurationProvider
61
+ # behavior is different or it didn't return anything.
62
+ return os.getenv("SERVICE_ACCOUNT_FILE")
63
+
64
+ def _load_data(self):
65
+ """
66
+ Connects to Google Sheets and preloads the data into a dictionary.
67
+ """
68
+ credentials_file = self._resolve_service_account_file()
69
+
70
+ try:
71
+ if credentials_file:
72
+ logger.info(
73
+ f"Connecting to Google Sheets using credentials: {credentials_file}"
74
+ )
75
+ gc = gspread.service_account(filename=credentials_file)
76
+ else:
77
+ logger.info(
78
+ "Connecting to Google Sheets using default environment credentials"
79
+ )
80
+ gc = gspread.service_account()
81
+
82
+ # Open spreadsheet by URL
83
+ sh = gc.open_by_url(self.spreadsheet_url)
84
+
85
+ # Select worksheet
86
+ worksheet = sh.worksheet(self.sheet_name)
87
+
88
+ # Get all records
89
+ records = worksheet.get_all_records()
90
+ logger.info(
91
+ f"Fetched {len(records)} records from sheet '{self.sheet_name}'"
92
+ )
93
+
94
+ # Build lookup dictionary
95
+ for i, record in enumerate(records):
96
+ key = record.get(self.key_column)
97
+ value = record.get(self.value_column)
98
+
99
+ if key is None:
100
+ logger.warning(
101
+ f"Row {i + 2}: Key column '{self.key_column}' is missing or empty. Skipping."
102
+ )
103
+ continue
104
+
105
+ # We stringify the key to ensure consistent lookup, optional but recommended for mixed types
106
+ self._data[str(key)] = value
107
+
108
+ logger.info(f"Successfully loaded {len(self._data)} items into cache.")
109
+
110
+ except Exception as e:
111
+ logger.error(f"Failed to load data from Google Sheets: {e}")
112
+ raise
113
+
114
+ def get_value(self, key: Any) -> Optional[Any]:
115
+ """
116
+ Look up a value by its key.
117
+
118
+ :param key: The key to look up.
119
+ :return: The corresponding value, or None if not found.
120
+ """
121
+ return self._data.get(str(key))
@@ -1,10 +1,13 @@
1
1
  from .create_dataframe_from_google_sheets import create_dataframe_from_google_sheets
2
2
  from .create_dataframe_of_entities_by_types import create_dataframe_of_entities_by_types
3
- from .create_dataframe_of_entities_with_embedding_vectors import create_dataframe_of_entities_with_embedding_vectors
3
+ from .create_dataframe_of_entities_with_embedding_vectors import (
4
+ create_dataframe_of_entities_with_embedding_vectors,
5
+ )
4
6
  from .create_dataframe_of_url_iri import create_dataframe_of_url_iri
5
7
  from .create_entity_patch_request import create_entity_patch_request
6
8
  from .delayed import create_delayed
7
9
  from .get_me import get_me
10
+ from .html_converter import HtmlConverter
8
11
 
9
12
  __all__ = [
10
13
  "create_dataframe_from_google_sheets",
@@ -13,5 +16,6 @@ __all__ = [
13
16
  "create_dataframe_of_url_iri",
14
17
  "create_entity_patch_request",
15
18
  "create_delayed",
16
- "get_me"
19
+ "get_me",
20
+ "HtmlConverter",
17
21
  ]
@@ -0,0 +1,56 @@
1
+ """HTML to XHTML conversion utility."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ _INVALID_XML_CHARS_RE = re.compile(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]")
9
+ _XML_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.:-]*$")
10
+
11
+
12
+ class HtmlConverter:
13
+ """Converts HTML to XHTML."""
14
+
15
+ def convert(self, html: str) -> str:
16
+ """
17
+ Convert an HTML string to a valid XHTML string.
18
+
19
+ Args:
20
+ html: The raw HTML string.
21
+
22
+ Returns:
23
+ A sanitized XHTML string.
24
+ """
25
+ html = re.sub(r"<!DOCTYPE[^>]*>", "", html, flags=re.IGNORECASE)
26
+ html = self._strip_invalid_xml_chars(html)
27
+ try:
28
+ from lxml import html as lxml_html
29
+ except ImportError as exc:
30
+ raise ImportError(
31
+ "lxml is required for XHTML output. Install with: pip install lxml"
32
+ ) from exc
33
+
34
+ try:
35
+ parser = lxml_html.HTMLParser(encoding="utf-8", recover=True)
36
+ doc = lxml_html.document_fromstring(html, parser=parser)
37
+ self._sanitize_xhtml_tree(doc)
38
+ xhtml = lxml_html.tostring(doc, encoding="unicode", method="xml")
39
+ return self._strip_invalid_xml_chars(xhtml)
40
+ except Exception as exc:
41
+ raise RuntimeError("Failed to convert HTML to XHTML.") from exc
42
+
43
+ def _strip_invalid_xml_chars(self, value: str) -> str:
44
+ return _INVALID_XML_CHARS_RE.sub("", value)
45
+
46
+ def _sanitize_xhtml_tree(self, doc: Any) -> None:
47
+ for element in doc.iter():
48
+ if not hasattr(element, "attrib"):
49
+ continue
50
+ for attr in list(element.attrib):
51
+ if not _XML_NAME_RE.match(attr):
52
+ del element.attrib[attr]
53
+ continue
54
+ value = element.attrib.get(attr)
55
+ if isinstance(value, str):
56
+ element.attrib[attr] = self._strip_invalid_xml_chars(value)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wordlift-sdk
3
- Version: 2.7.6
3
+ Version: 2.9.0
4
4
  Summary:
5
5
  Author: David Riccitelli
6
6
  Author-email: david@wordlift.io
@@ -123,3 +123,8 @@ poetry install --with dev
123
123
  poetry run pytest
124
124
  ```
125
125
 
126
+ ## Documentation
127
+
128
+ - [Google Sheets Lookup](docs/google_sheets_lookup.md): Utility for O(1) lookups from Google Sheets.
129
+
130
+
@@ -14,6 +14,8 @@ wordlift_sdk/entity/patch.py,sha256=CP2H2nrrli4A_zu1D00Egye1I784ZQ6MxL_jS9ZsW9k,
14
14
  wordlift_sdk/google_search_console/__init__.py,sha256=-PmsnNYsGs4Utb9l7AXz0qAzcWhJeD-eZyFNfOHM5ow,384
15
15
  wordlift_sdk/google_search_console/create_google_search_console_data_import.py,sha256=xP_koUaaXYnnNVyw2ld4jbqc_d7yFkYXLe2dC2vLpm0,2223
16
16
  wordlift_sdk/google_search_console/raise_error_if_account_analytics_not_configured.py,sha256=pXcRlaVAODSbSgxI3KTtsHp37qiIaWCu9ISDKtDw6qM,830
17
+ wordlift_sdk/google_sheets/__init__.py,sha256=CEeLCBM2IJ_Yux0bY2T4MfIHVRc93OMF3aRPfpIYXRU,87
18
+ wordlift_sdk/google_sheets/google_sheets_lookup.py,sha256=oQwPizlT7Imbeq_Vlc5ZWfv2lkrO4VnA2sNeqdZHqew,4278
17
19
  wordlift_sdk/graph/graph_bag.py,sha256=Gp0ufstKY5xCx6dZNohcTmaEhoEYef891eaLuESUJpM,105
18
20
  wordlift_sdk/graph/ttl_liquid/__init__.py,sha256=2AmJpsFFkJxv6FyO7J3XFUfX1nSPDoY31tRom-K5C_w,97
19
21
  wordlift_sdk/graph/ttl_liquid/ttl_liquid_graph_factory.py,sha256=CSzO36YZ-XQrV7xRi99LhmYfQgMxjBkKdfEGeD0Zt9M,1242
@@ -65,7 +67,7 @@ wordlift_sdk/url_source/new_or_changed_url_source.py,sha256=81ZEitfxxMof5-fcKuvT
65
67
  wordlift_sdk/url_source/sitemap_url_source.py,sha256=JMIteakIFIWcHoQ3Uf0fyMh8pYz4YM_rnJvdm7NXYak,1198
66
68
  wordlift_sdk/url_source/url_source.py,sha256=ZmGOiDlPVzoOTt2Qz69onpnFzQYZlrwWaogOkZMEqGc,403
67
69
  wordlift_sdk/url_source/url_source_input.py,sha256=GvRAjBb103DS--rR7M8oIxIjWhQbYUTldwbPx2BctaU,152
68
- wordlift_sdk/utils/__init__.py,sha256=_BB9cgIXFY5JUDowedu2tZeQmLhtGElUTh6qzVQ-Xoc,759
70
+ wordlift_sdk/utils/__init__.py,sha256=3l2N8t7LlaEScp08rRApx6fKvx3bo9hnUdGAcZRZG8w,832
69
71
  wordlift_sdk/utils/create_dataframe_from_google_sheets.py,sha256=7j0oCwUwSqoo2505_QfcUCx4XNqhw94Y_UTL5tyIk5U,1117
70
72
  wordlift_sdk/utils/create_dataframe_of_entities_by_types.py,sha256=5U5k_OheifPJyod4PB0HEdYCGwZEMgkdiwckAR8LFJY,770
71
73
  wordlift_sdk/utils/create_dataframe_of_entities_with_embedding_vectors.py,sha256=A_JMVoYS4pcWCsKYGH_sHyc9MJvg5EuoKELp1BCI2Ko,679
@@ -73,6 +75,7 @@ wordlift_sdk/utils/create_dataframe_of_url_iri.py,sha256=xTxNyHb1Vo7YdfoYoaiCqp6
73
75
  wordlift_sdk/utils/create_entity_patch_request.py,sha256=-fEZrflVpTBtk7c7ME8-BWn6-r86cQJp7fvQJznj_aU,497
74
76
  wordlift_sdk/utils/delayed.py,sha256=uy-cQsLMprakx8CiQl6ZLL49bfYB1C6oQt4UObr5TwU,323
75
77
  wordlift_sdk/utils/get_me.py,sha256=-mr0DscVWEDFvgBYtmgND3_gIuh2q7kfD-OiqrYwLJU,297
78
+ wordlift_sdk/utils/html_converter.py,sha256=MGdXQg2EAhI2K7CWtbIzZip08clVPUgL84Xt_xxa-h4,1945
76
79
  wordlift_sdk/utils/import_url.py,sha256=KiUFkU4mRfd7YWFlLoz5bB13AgPURV8Km8H05LxevCI,1299
77
80
  wordlift_sdk/wordlift/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
78
81
  wordlift_sdk/wordlift/entity_gaps/__init__.py,sha256=PMtdyBoUD-oiTE-7Izr6fuod7OxGOQIhFSasZG_SafM,109
@@ -95,6 +98,6 @@ wordlift_sdk/workflow/url_handler/default_url_handler.py,sha256=irMoJftx9Gyq-8HQ
95
98
  wordlift_sdk/workflow/url_handler/search_console_url_handler.py,sha256=uOwD4t009-cA9JI7ZtbYhCGRwjhLzDpBNTWHERPnNqI,2698
96
99
  wordlift_sdk/workflow/url_handler/url_handler.py,sha256=meyOpWVhLk2NcbtUOO_V0z6_T9q-D3pD7kWQCRioYh0,129
97
100
  wordlift_sdk/workflow/url_handler/web_page_import_url_handler.py,sha256=xQiy-fgFj_dWKFFBNWeodAGhIMJQereSPdgnjK-Crmo,3529
98
- wordlift_sdk-2.7.6.dist-info/METADATA,sha256=GtUczWgOG4_IP8PN5NisKsEh4YPnxYS_iNcU9ekXCio,4977
99
- wordlift_sdk-2.7.6.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
100
- wordlift_sdk-2.7.6.dist-info/RECORD,,
101
+ wordlift_sdk-2.9.0.dist-info/METADATA,sha256=NF2Kp2Z4kFdv2TXA7Tf3zJjzebs_EuH8MG0deldHtx4,5098
102
+ wordlift_sdk-2.9.0.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
103
+ wordlift_sdk-2.9.0.dist-info/RECORD,,