fraudcrawler 0.6.1__tar.gz → 0.6.2__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.

Potentially problematic release.


This version of fraudcrawler might be problematic. Click here for more details.

Files changed (21) hide show
  1. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/PKG-INFO +4 -3
  2. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/base/base.py +2 -0
  3. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/base/orchestrator.py +95 -34
  4. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/launch_demo_pipeline.py +1 -1
  5. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/scraping/zyte.py +103 -77
  6. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/settings.py +8 -0
  7. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/pyproject.toml +1 -1
  8. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/LICENSE +0 -0
  9. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/README.md +0 -0
  10. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/__init__.py +0 -0
  11. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/base/__init__.py +0 -0
  12. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/base/client.py +0 -0
  13. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/base/google-languages.json +0 -0
  14. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/base/google-locations.json +0 -0
  15. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/base/retry.py +0 -0
  16. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/processing/__init__.py +0 -0
  17. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/processing/processor.py +0 -0
  18. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/scraping/__init__.py +0 -0
  19. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/scraping/enrich.py +0 -0
  20. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/scraping/search.py +0 -0
  21. {fraudcrawler-0.6.1 → fraudcrawler-0.6.2}/fraudcrawler/scraping/url.py +0 -0
@@ -1,9 +1,9 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: fraudcrawler
3
- Version: 0.6.1
3
+ Version: 0.6.2
4
4
  Summary: Intelligent Market Monitoring
5
- Home-page: https://github.com/open-veanu/fraudcrawler
6
5
  License: MIT
6
+ License-File: LICENSE
7
7
  Author: Domingo Bertus
8
8
  Author-email: hello@veanu.ch
9
9
  Requires-Python: >=3.11,<4.0
@@ -12,6 +12,7 @@ Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3.11
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
15
16
  Requires-Dist: beautifulsoup4 (>=4.13.4,<5.0.0)
16
17
  Requires-Dist: httpx (>=0.28.1,<0.29.0)
17
18
  Requires-Dist: openai (>=1.68.2,<2.0.0)
@@ -140,6 +140,8 @@ class ProductItem(BaseModel):
140
140
  url_resolved: str
141
141
  search_engine_name: str
142
142
  domain: str
143
+ exact_search: bool = False
144
+ exact_search_match: bool = False
143
145
 
144
146
  # Context parameters
145
147
  product_name: str | None = None
@@ -3,10 +3,12 @@ import asyncio
3
3
  import logging
4
4
  from typing import cast, Dict, List, Self
5
5
 
6
- from bs4 import BeautifulSoup
7
6
  import httpx
7
+ import re
8
8
 
9
9
  from fraudcrawler.settings import (
10
+ EXACT_MATCH_PRODUCT_FIELDS,
11
+ EXACT_MATCH_FIELD_SEPARATOR,
10
12
  PROCESSOR_DEFAULT_MODEL,
11
13
  )
12
14
  from fraudcrawler.settings import (
@@ -27,8 +29,8 @@ from fraudcrawler import (
27
29
  Searcher,
28
30
  SearchEngineName,
29
31
  Enricher,
30
- URLCollector,
31
32
  ZyteAPI,
33
+ URLCollector,
32
34
  Processor,
33
35
  )
34
36
 
@@ -227,44 +229,29 @@ class Orchestrator(ABC):
227
229
 
228
230
  if not product.filtered:
229
231
  try:
230
- # Fetch the product context from Zyte API
232
+ # Fetch and enrich the product context from Zyte API
231
233
  details = await self._zyteapi.details(url=product.url)
232
- url_resolved = self._zyteapi.extract_url_resolved(details=details)
233
- if url_resolved:
234
- product.url_resolved = url_resolved
235
- product.product_name = self._zyteapi.extract_product_name(
236
- details=details
234
+ product = self._zyteapi.enrich_context(
235
+ product=product, details=details
237
236
  )
238
237
 
239
- # If the resolved URL is different from the original URL, we also need to update the domain as
240
- # otherwise the unresolved domain will be shown.
241
- # For example for an unresolved domain "toppreise.ch" but resolved "digitec.ch
242
- if url_resolved and url_resolved != product.url:
243
- logger.debug(
244
- f"URL resolved for {product.url} is {url_resolved}"
245
- )
246
- product.domain = self._searcher._get_domain(url_resolved)
247
-
248
- product.product_price = self._zyteapi.extract_product_price(
249
- details=details
250
- )
251
- product.product_description = (
252
- self._zyteapi.extract_product_description(details=details)
253
- )
254
- product.product_images = self._zyteapi.extract_image_urls(
255
- details=details
256
- )
257
- product.probability = self._zyteapi.extract_probability(
258
- details=details
259
- )
260
- product.html = self._zyteapi.extract_html(details=details)
261
- if product.html:
262
- soup = BeautifulSoup(product.html, "html.parser")
263
- product.html_clean = soup.get_text(separator=" ", strip=True)
264
238
  # Filter the product based on the probability threshold
265
239
  if not self._zyteapi.keep_product(details=details):
266
240
  product.filtered = True
267
- product.filtered_at_stage = "Zyte probability threshold"
241
+ product.filtered_at_stage = (
242
+ "Context (Zyte probability threshold)"
243
+ )
244
+
245
+ # Check for exact match inside the full product context
246
+ product = self._check_exact_search(product=product)
247
+ if (
248
+ not product.filtered
249
+ and product.exact_search
250
+ and not product.exact_search_match
251
+ ):
252
+ product.filtered = True
253
+ product.filtered_at_stage = "Context (exact search)"
254
+
268
255
  except Exception as e:
269
256
  logger.warning(f"Error executing Zyte API search: {e}.")
270
257
  await queue_out.put(product)
@@ -502,6 +489,80 @@ class Orchestrator(ABC):
502
489
  **common_kwargs, # type: ignore[arg-type]
503
490
  )
504
491
 
492
+ @staticmethod
493
+ def _is_exact_search(search_term: str) -> bool:
494
+ """Check if the search term is an exact search (contains double quotation marks).
495
+
496
+ Args:
497
+ search_term: The search term to check.
498
+
499
+ Returns:
500
+ True if the search term contains double quotation marks, False otherwise.
501
+ """
502
+ return '"' in search_term
503
+
504
+ @staticmethod
505
+ def _extract_exact_search_terms(search_term: str) -> list[str]:
506
+ """Extract all exact search terms from within double quotation marks.
507
+
508
+ Args:
509
+ search_term: The search term that may contain double quotation marks.
510
+
511
+ Returns:
512
+ A list of extracted search terms without quotes, or empty list if no quotes found.
513
+ """
514
+ # Find all double-quoted strings
515
+ double_quote_matches = re.findall(r'"([^"]*)"', search_term)
516
+ return double_quote_matches
517
+
518
+ @staticmethod
519
+ def _check_exact_search_terms_match(
520
+ product: ProductItem,
521
+ exact_search_terms: list[str],
522
+ ) -> bool:
523
+ """Check if the product, represented by a string of selected attributes, matches ALL of the exact search terms.
524
+
525
+ Args:
526
+ product: The product item.
527
+ exact_search_terms: List of exact search terms to match against.
528
+ """
529
+ field_values = [
530
+ str(val)
531
+ for fld in EXACT_MATCH_PRODUCT_FIELDS
532
+ if (val := getattr(product, fld, None)) is not None
533
+ ]
534
+ product_str_lower = EXACT_MATCH_FIELD_SEPARATOR.join(field_values).lower()
535
+
536
+ return all(
537
+ re.search(re.escape(est.lower()), product_str_lower)
538
+ for est in exact_search_terms
539
+ )
540
+
541
+ def _check_exact_search(self, product: ProductItem) -> ProductItem:
542
+ """Checks if the search term requests an exact search and if yes, checks for conformity."""
543
+ # Check for exact search and apply regex matching
544
+ exact_search = self._is_exact_search(product.search_term)
545
+ product.exact_search = exact_search
546
+
547
+ # Only set exact_search_match if this was an exact search (contains quotes)
548
+ if exact_search:
549
+ exact_search_terms = self._extract_exact_search_terms(product.search_term)
550
+ if exact_search_terms:
551
+ product.exact_search_match = self._check_exact_search_terms_match(
552
+ product=product, exact_search_terms=exact_search_terms
553
+ )
554
+ logger.debug(
555
+ f"Exact search terms {exact_search_terms} matched: {product.exact_search_match} "
556
+ f"for offer with url={product.url}"
557
+ )
558
+ else:
559
+ logger.warning(
560
+ f"is_exact_search=True but no exact search terms found in search_term='{product.search_term}' "
561
+ f"for offer with url={product.url}"
562
+ )
563
+ # If exact_search is False, product.exact_search_match remains False (default value)
564
+ return product
565
+
505
566
  async def run(
506
567
  self,
507
568
  search_term: str,
@@ -97,4 +97,4 @@ def search(search_term: str):
97
97
 
98
98
 
99
99
  if __name__ == "__main__":
100
- search(search_term='Gorenje "R619FEW5"')
100
+ search(search_term="Kaffeebohnen")
@@ -2,11 +2,12 @@ from base64 import b64decode
2
2
  import logging
3
3
  from typing import List
4
4
 
5
+ from bs4 import BeautifulSoup
5
6
  import httpx
6
7
  from tenacity import RetryCallState
7
8
 
8
9
  from fraudcrawler.settings import ZYTE_DEFALUT_PROBABILITY_THRESHOLD
9
- from fraudcrawler.base.base import DomainUtils
10
+ from fraudcrawler.base.base import DomainUtils, ProductItem
10
11
  from fraudcrawler.base.retry import get_async_retry
11
12
 
12
13
  logger = logging.getLogger(__name__)
@@ -61,77 +62,8 @@ class ZyteAPI(DomainUtils):
61
62
  else:
62
63
  logger.debug(f"retry_state is {retry_state}; not logging before_sleep.")
63
64
 
64
- async def details(self, url: str) -> dict:
65
- """Fetches product details for a single URL.
66
-
67
- Args:
68
- url: The URL to fetch product details from.
69
-
70
- Returns:
71
- A dictionary containing the product details, fields include:
72
- (c.f. https://docs.zyte.com/zyte-api/usage/reference.html#operation/extract/response/200/product)
73
- {
74
- "url": str,
75
- "statusCode": str,
76
- "product": {
77
- "name": str,
78
- "price": str,
79
- "mainImage": {"url": str},
80
- "images": [{"url": str}],
81
- "description": str,
82
- "metadata": {
83
- "probability": float,
84
- },
85
- },
86
- "httpResponseBody": base64
87
- }
88
- """
89
- logger.info(f"Fetching product details by Zyte for URL {url}.")
90
-
91
- # Perform the request and retry if necessary. There is some context aware logging:
92
- # - `before`: before the request is made (and before retrying)
93
- # - `before_sleep`: if the request fails before sleeping
94
- retry = get_async_retry()
95
- retry.before = lambda retry_state: self._log_before(
96
- url=url, retry_state=retry_state
97
- )
98
- retry.before_sleep = lambda retry_state: self._log_before_sleep(
99
- url=url, retry_state=retry_state
100
- )
101
- async for attempt in retry:
102
- with attempt:
103
- response = await self._http_client.post(
104
- url=self._endpoint,
105
- json={"url": url, **self._config},
106
- auth=(self._api_key, ""), # API key as username, empty password
107
- )
108
- response.raise_for_status()
109
-
110
- details = response.json()
111
- return details
112
-
113
- @staticmethod
114
- def keep_product(
115
- details: dict,
116
- threshold: float = ZYTE_DEFALUT_PROBABILITY_THRESHOLD,
117
- ) -> bool:
118
- """Determines whether to keep the product based on the probability threshold.
119
-
120
- Args:
121
- details: A product details data dictionary.
122
- threshold: The probability threshold used to filter the products.
123
- """
124
- try:
125
- prob = float(details["product"]["metadata"]["probability"])
126
- except KeyError:
127
- logger.warning(
128
- f"Product with url={details.get('url')} has no probability value - product is ignored"
129
- )
130
- return False
131
- return prob > threshold
132
-
133
65
  @staticmethod
134
- def extract_product_name(details: dict) -> str | None:
66
+ def _extract_product_name(details: dict) -> str | None:
135
67
  """Extracts the product name from the product data.
136
68
 
137
69
  The input argument is a dictionary of the following structure:
@@ -144,7 +76,7 @@ class ZyteAPI(DomainUtils):
144
76
  return details.get("product", {}).get("name")
145
77
 
146
78
  @staticmethod
147
- def extract_url_resolved(details: dict) -> str | None:
79
+ def _extract_url_resolved(details: dict) -> str | None:
148
80
  """Extracts the resolved URL from the product data - this is automatically resolved by Zyte.
149
81
 
150
82
  The input argument is a dictionary of the following structure:
@@ -157,7 +89,7 @@ class ZyteAPI(DomainUtils):
157
89
  return details.get("product", {}).get("url")
158
90
 
159
91
  @staticmethod
160
- def extract_product_price(details: dict) -> str | None:
92
+ def _extract_product_price(details: dict) -> str | None:
161
93
  """Extracts the product price from the product data.
162
94
 
163
95
  The input argument is a dictionary of the following structure:
@@ -170,7 +102,7 @@ class ZyteAPI(DomainUtils):
170
102
  return details.get("product", {}).get("price")
171
103
 
172
104
  @staticmethod
173
- def extract_product_description(details: dict) -> str | None:
105
+ def _extract_product_description(details: dict) -> str | None:
174
106
  """Extracts the product description from the product data.
175
107
 
176
108
  The input argument is a dictionary of the following structure:
@@ -183,7 +115,7 @@ class ZyteAPI(DomainUtils):
183
115
  return details.get("product", {}).get("description")
184
116
 
185
117
  @staticmethod
186
- def extract_image_urls(details: dict) -> List[str]:
118
+ def _extract_image_urls(details: dict) -> List[str]:
187
119
  """Extracts the images from the product data.
188
120
 
189
121
  The input argument is a dictionary of the following structure:
@@ -206,7 +138,7 @@ class ZyteAPI(DomainUtils):
206
138
  return images
207
139
 
208
140
  @staticmethod
209
- def extract_probability(details: dict) -> float:
141
+ def _extract_probability(details: dict) -> float:
210
142
  """Extracts the probability from the product data.
211
143
 
212
144
  The input argument is a dictionary of the following structure:
@@ -223,7 +155,7 @@ class ZyteAPI(DomainUtils):
223
155
  )
224
156
 
225
157
  @staticmethod
226
- def extract_html(details: dict) -> str | None:
158
+ def _extract_html(details: dict) -> str | None:
227
159
  """Extracts the HTML from the Zyte API response.
228
160
 
229
161
  The input argument is a dictionary of the following structure:
@@ -243,6 +175,51 @@ class ZyteAPI(DomainUtils):
243
175
  return decoded_string
244
176
  return None
245
177
 
178
+ def enrich_context(self, product: ProductItem, details: dict) -> ProductItem:
179
+ product.product_name = self._extract_product_name(details=details)
180
+
181
+ url_resolved = self._extract_url_resolved(details=details)
182
+ if url_resolved:
183
+ product.url_resolved = url_resolved
184
+
185
+ # If the resolved URL is different from the original URL, we also need to update the domain as
186
+ # otherwise the unresolved domain will be shown.
187
+ # For example for an unresolved domain "toppreise.ch" but resolved "digitec.ch
188
+ if url_resolved and url_resolved != product.url:
189
+ logger.debug(f"URL resolved for {product.url} is {url_resolved}")
190
+ product.domain = self._get_domain(url=url_resolved)
191
+
192
+ product.product_price = self._extract_product_price(details=details)
193
+ product.product_description = self._extract_product_description(details=details)
194
+ product.product_images = self._extract_image_urls(details=details)
195
+ product.probability = self._extract_probability(details=details)
196
+ product.html = self._extract_html(details=details)
197
+ if product.html:
198
+ soup = BeautifulSoup(product.html, "html.parser")
199
+ product.html_clean = soup.get_text(separator=" ", strip=True)
200
+
201
+ return product
202
+
203
+ @staticmethod
204
+ def keep_product(
205
+ details: dict,
206
+ threshold: float = ZYTE_DEFALUT_PROBABILITY_THRESHOLD,
207
+ ) -> bool:
208
+ """Determines whether to keep the product based on the probability threshold.
209
+
210
+ Args:
211
+ details: A product details data dictionary.
212
+ threshold: The probability threshold used to filter the products.
213
+ """
214
+ try:
215
+ prob = float(details["product"]["metadata"]["probability"])
216
+ except KeyError:
217
+ logger.warning(
218
+ f"Product with url={details.get('url')} has no probability value - product is ignored"
219
+ )
220
+ return False
221
+ return prob > threshold
222
+
246
223
  async def unblock_url_content(self, url: str) -> bytes:
247
224
  """Unblock the content of an URL using Zyte proxy mode.
248
225
 
@@ -256,3 +233,52 @@ class ZyteAPI(DomainUtils):
256
233
  raise httpx.HTTPError("No httpResponseBody in Zyte response")
257
234
 
258
235
  return b64decode(details["httpResponseBody"])
236
+
237
+ async def details(self, url: str) -> dict:
238
+ """Fetches product details for a single URL.
239
+
240
+ Args:
241
+ url: The URL to fetch product details from.
242
+
243
+ Returns:
244
+ A dictionary containing the product details, fields include:
245
+ (c.f. https://docs.zyte.com/zyte-api/usage/reference.html#operation/extract/response/200/product)
246
+ {
247
+ "url": str,
248
+ "statusCode": str,
249
+ "product": {
250
+ "name": str,
251
+ "price": str,
252
+ "mainImage": {"url": str},
253
+ "images": [{"url": str}],
254
+ "description": str,
255
+ "metadata": {
256
+ "probability": float,
257
+ },
258
+ },
259
+ "httpResponseBody": base64
260
+ }
261
+ """
262
+ logger.info(f"Fetching product details by Zyte for URL {url}.")
263
+
264
+ # Perform the request and retry if necessary. There is some context aware logging:
265
+ # - `before`: before the request is made (and before retrying)
266
+ # - `before_sleep`: if the request fails before sleeping
267
+ retry = get_async_retry()
268
+ retry.before = lambda retry_state: self._log_before(
269
+ url=url, retry_state=retry_state
270
+ )
271
+ retry.before_sleep = lambda retry_state: self._log_before_sleep(
272
+ url=url, retry_state=retry_state
273
+ )
274
+ async for attempt in retry:
275
+ with attempt:
276
+ response = await self._http_client.post(
277
+ url=self._endpoint,
278
+ json={"url": url, **self._config},
279
+ auth=(self._api_key, ""), # API key as username, empty password
280
+ )
281
+ response.raise_for_status()
282
+
283
+ details = response.json()
284
+ return details
@@ -78,6 +78,14 @@ ENRICHMENT_DEFAULT_LIMIT = 10
78
78
  # Zyte settings
79
79
  ZYTE_DEFALUT_PROBABILITY_THRESHOLD = 0.1
80
80
 
81
+ # Exact match settings
82
+ EXACT_MATCH_PRODUCT_FIELDS = {
83
+ "url_resolvedproduct_name",
84
+ "product_description",
85
+ "html",
86
+ }
87
+ EXACT_MATCH_FIELD_SEPARATOR = "\n"
88
+
81
89
  # Processor settings
82
90
  PROCESSOR_DEFAULT_MODEL = "gpt-4o"
83
91
  PROCESSOR_DEFAULT_IF_MISSING = -1
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
4
4
 
5
5
  [tool.poetry]
6
6
  name = "fraudcrawler"
7
- version = "0.6.1"
7
+ version = "0.6.2"
8
8
  description = "Intelligent Market Monitoring"
9
9
  authors = [
10
10
  "Domingo Bertus <hello@veanu.ch>",
File without changes
File without changes