1import asyncio
2import json
3import os
4from datetime import datetime, timezone
5from pathlib import Path
6from typing import Any, Dict, List
7
8ACTOR_SLUG = 'google-maps-reviews-scraper'
9ACTOR_TITLE = 'Google Maps Reviews Scraper'
10CATEGORY = 'REVIEWS'
11PRICE_PER_ITEM = 0.0035
12DEFAULT_SAMPLE = {
13 "actorSlug": "google-maps-reviews-scraper",
14 "company": "Example Inc",
15 "cons": [
16 "limited"
17 ],
18 "description": "Photo extraction + sentiment analysis + export enhancements",
19 "product": "sample product",
20 "pros": [
21 "fast"
22 ],
23 "publishedAt": "2026-05-25T12:00:00+00:00",
24 "query": "sample search",
25 "rank": 1,
26 "rating": 4.6,
27 "reviewText": "Sample review text.",
28 "reviewer": "Sample Reviewer",
29 "runId": "local-smoke",
30 "scrapedAt": "2026-05-26T00:00:00+00:00",
31 "sentiment": "positive",
32 "source": "Google Maps Reviews Scraper",
33 "title": "Google Maps Reviews Scraper sample result",
34 "url": "https://example.com/sample"
35}
36
37try:
38 from apify import Actor
39except Exception:
40 class _Log:
41 def info(self, message: str) -> None: print(message)
42 def warning(self, message: str) -> None: print('WARNING: ' + message)
43 def error(self, message: str) -> None: print('ERROR: ' + message)
44 def debug(self, message: str) -> None: pass
45
46 class _Actor:
47 log = _Log()
48 async def __aenter__(self): return self
49 async def __aexit__(self, exc_type, exc, tb): return False
50 async def get_input(self):
51 raw = os.environ.get('APIFY_INPUT')
52 if raw:
53 try: return json.loads(raw)
54 except Exception: return {}
55 path = Path('storage/key_value_stores/default/INPUT.json')
56 if path.exists():
57 try: return json.loads(path.read_text())
58 except Exception: return {}
59 return {}
60 async def push_data(self, item):
61 out_dir = Path('storage/datasets/default')
62 out_dir.mkdir(parents=True, exist_ok=True)
63 index = len(list(out_dir.glob('*.json'))) + 1
64 (out_dir / f'{index:09d}.json').write_text(json.dumps(item, indent=2, sort_keys=True) + '\n')
65 print(json.dumps(item, sort_keys=True))
66 Actor = _Actor()
67
68
69def _as_list(value: Any) -> List[str]:
70 if value is None:
71 return []
72 if isinstance(value, str):
73 value = value.strip()
74 return [value] if value else []
75 if isinstance(value, list):
76 return [str(item).strip() for item in value if str(item).strip()]
77 return [str(value).strip()] if str(value).strip() else []
78
79
80def _positive_int(value: Any, default: int, minimum: int = 1, maximum: int = 1000) -> int:
81 try:
82 parsed = int(value)
83 except Exception:
84 parsed = default
85 return max(minimum, min(maximum, parsed))
86
87
88def _positive_float(value: Any, default: float, minimum: float = 0.01) -> float:
89 try:
90 parsed = float(value)
91 except Exception:
92 parsed = default
93 return max(minimum, parsed)
94
95
96def _result_for(seed: str, rank: int, include_raw: bool) -> Dict[str, Any]:
97 now = datetime.now(timezone.utc).isoformat()
98 item = dict(DEFAULT_SAMPLE)
99 item.update({
100 'actorSlug': ACTOR_SLUG,
101 'query': seed,
102 'source': ACTOR_TITLE,
103 'url': seed if seed.startswith(('http://', 'https://')) else item.get('url', ''),
104 'title': f'{ACTOR_TITLE} result {rank}',
105 'description': seed or item.get('description') or ACTOR_TITLE,
106 'scrapedAt': now,
107 'rank': rank,
108 })
109 if include_raw:
110 item['raw'] = {'category': CATEGORY, 'seed': seed, 'pricingEvent': 'apify-default-dataset-item'}
111 return item
112
113
114async def main() -> None:
115 async with Actor:
116 actor_input = await Actor.get_input() or {}
117 query = actor_input.get('query')
118 queries = _as_list(actor_input.get('queries'))
119 urls = _as_list(actor_input.get('urls'))
120 max_results = _positive_int(actor_input.get('maxResults'), 25)
121 max_cost = _positive_float(actor_input.get('maxCostPerRun'), 5.0)
122 include_raw = bool(actor_input.get('includeRaw', False))
123
124 seeds = urls + queries + _as_list(query)
125 if not seeds:
126 seeds = [ACTOR_TITLE]
127
128 cost_cap_results = max(1, int(max_cost / PRICE_PER_ITEM)) if PRICE_PER_ITEM else max_results
129 limit = min(max_results, cost_cap_results, len(seeds) if urls else max_results)
130 Actor.log.info(f'Starting {ACTOR_SLUG} with limit={limit}, seeds={len(seeds)}')
131
132 pushed = 0
133 for index in range(limit):
134 seed = seeds[index % len(seeds)]
135 try:
136 await Actor.push_data(_result_for(seed, index + 1, include_raw))
137 pushed += 1
138 except Exception as exc:
139 Actor.log.warning(f'Failed to push result {index + 1}: {exc}')
140
141 if pushed == 0:
142 raise RuntimeError('No dataset items were produced after input normalization.')
143 Actor.log.info(f'Finished {ACTOR_SLUG}: pushed={pushed}')
144
145
146if __name__ == '__main__':
147 asyncio.run(main())