papersearch 0.7.2 → 0.8.0

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.
Files changed (177) hide show
  1. package/LICENSE-paper-search-mcp-nodejs +24 -0
  2. package/NOTICE +8 -37
  3. package/README.en.md +7 -3
  4. package/README.fr.md +268 -0
  5. package/README.ja.md +268 -0
  6. package/README.ko.md +268 -0
  7. package/README.md +7 -3
  8. package/README.zh-Hant.md +268 -0
  9. package/dist/capabilities/download/batch/batch.d.ts +16 -1
  10. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  11. package/dist/capabilities/download/batch/batch.js +669 -53
  12. package/dist/capabilities/download/batch/batch.js.map +1 -1
  13. package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
  14. package/dist/capabilities/download/batch/batchFolder.js +4 -3
  15. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  16. package/dist/capabilities/download/batch/batchSummary.js +1 -1
  17. package/dist/capabilities/download/batch/batchSummary.js.map +1 -1
  18. package/dist/capabilities/download/batch/networkLoss.d.ts +12 -3
  19. package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
  20. package/dist/capabilities/download/batch/networkLoss.js +25 -4
  21. package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
  22. package/dist/capabilities/download/batch/resume.d.ts +7 -0
  23. package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
  24. package/dist/capabilities/download/batch/resume.js +50 -9
  25. package/dist/capabilities/download/batch/resume.js.map +1 -1
  26. package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
  27. package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
  28. package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
  29. package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
  30. package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
  31. package/dist/capabilities/download/content/markdown/shortfall.js +27 -15
  32. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  33. package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
  34. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  35. package/dist/capabilities/download/content/markdown/step.js +42 -2
  36. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  37. package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
  38. package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
  39. package/dist/capabilities/download/handler.d.ts.map +1 -1
  40. package/dist/capabilities/download/handler.js +13 -5
  41. package/dist/capabilities/download/handler.js.map +1 -1
  42. package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
  43. package/dist/capabilities/download/outputLayout.js +3 -1
  44. package/dist/capabilities/download/outputLayout.js.map +1 -1
  45. package/dist/capabilities/download/tools.js +2 -2
  46. package/dist/capabilities/download/tools.js.map +1 -1
  47. package/dist/capabilities/download/types.d.ts +9 -1
  48. package/dist/capabilities/download/types.d.ts.map +1 -1
  49. package/dist/cli.js +3 -1
  50. package/dist/cli.js.map +1 -1
  51. package/dist/infrastructure/runlog/RunLedger.d.ts +7 -0
  52. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  53. package/dist/infrastructure/runlog/RunLedger.js +13 -0
  54. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  55. package/dist/infrastructure/runlog/failureClass.d.ts +17 -9
  56. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  57. package/dist/infrastructure/runlog/failureClass.js +89 -56
  58. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  59. package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
  60. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  61. package/dist/infrastructure/school/SchoolAttempt.js +107 -59
  62. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  63. package/dist/infrastructure/school/SchoolMcpClient.d.ts +7 -2
  64. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  65. package/dist/infrastructure/school/SchoolMcpClient.js +30 -7
  66. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  67. package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
  68. package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
  69. package/dist/infrastructure/school/SchoolProgress.js +2 -0
  70. package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
  71. package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
  72. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  73. package/dist/infrastructure/school/SchoolReadiness.js +2 -0
  74. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  75. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  76. package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
  77. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  78. package/dist/infrastructure/school/index.d.ts +2 -2
  79. package/dist/infrastructure/school/index.d.ts.map +1 -1
  80. package/dist/infrastructure/school/index.js +1 -1
  81. package/dist/infrastructure/school/index.js.map +1 -1
  82. package/dist/infrastructure/school/types.d.ts +52 -3
  83. package/dist/infrastructure/school/types.d.ts.map +1 -1
  84. package/dist/infrastructure/school/types.js.map +1 -1
  85. package/dist/management/failures/index.d.ts +28 -2
  86. package/dist/management/failures/index.d.ts.map +1 -1
  87. package/dist/management/failures/index.js +83 -21
  88. package/dist/management/failures/index.js.map +1 -1
  89. package/package.json +7 -2
  90. package/school/NOTICE +3 -2
  91. package/school/paper_search_school/adapters/__init__.py +2 -0
  92. package/school/paper_search_school/adapters/aps/__init__.py +3 -6
  93. package/school/paper_search_school/adapters/base.py +18 -0
  94. package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
  95. package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
  96. package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
  97. package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
  98. package/school/paper_search_school/adapters/iop/__init__.py +8 -0
  99. package/school/paper_search_school/adapters/jama/__init__.py +8 -0
  100. package/school/paper_search_school/adapters/lww/__init__.py +14 -6
  101. package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
  102. package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
  103. package/school/paper_search_school/adapters/optica/__init__.py +2 -9
  104. package/school/paper_search_school/adapters/oup/__init__.py +27 -4
  105. package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
  106. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +8 -0
  107. package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
  108. package/school/paper_search_school/adapters/sage/__init__.py +4 -1
  109. package/school/paper_search_school/adapters/thieme/__init__.py +6 -11
  110. package/school/paper_search_school/api_keys.py +63 -13
  111. package/school/paper_search_school/assets/api_keys.json +14 -0
  112. package/school/paper_search_school/assets/capsule.html +274 -158
  113. package/school/paper_search_school/assets/capsule_en.json +99 -98
  114. package/school/paper_search_school/assets/capsule_fr.json +100 -99
  115. package/school/paper_search_school/assets/capsule_ja.json +99 -98
  116. package/school/paper_search_school/assets/capsule_ko.json +99 -98
  117. package/school/paper_search_school/assets/capsule_zh-Hant.json +94 -97
  118. package/school/paper_search_school/browser/batch_session.py +1 -1
  119. package/school/paper_search_school/browser/challenge/__init__.py +12 -9
  120. package/school/paper_search_school/browser/challenge/continuation.py +65 -0
  121. package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
  122. package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
  123. package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
  124. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +100 -0
  125. package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
  126. package/school/paper_search_school/browser/challenge/kinds.py +203 -0
  127. package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
  128. package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
  129. package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
  130. package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
  131. package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
  132. package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
  133. package/school/paper_search_school/browser/challenge/services/solver.py +272 -0
  134. package/school/paper_search_school/cli_config.py +10 -5
  135. package/school/paper_search_school/cold_start.py +22 -11
  136. package/school/paper_search_school/config.py +11 -10
  137. package/school/paper_search_school/download_diagnostics.py +7 -2
  138. package/school/paper_search_school/engine/access_rules.py +15 -5
  139. package/school/paper_search_school/engine/batch.py +55 -15
  140. package/school/paper_search_school/engine/batch_access.py +59 -21
  141. package/school/paper_search_school/engine/batch_capture.py +215 -18
  142. package/school/paper_search_school/engine/batch_common.py +3 -0
  143. package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
  144. package/school/paper_search_school/engine/batch_institution.py +168 -32
  145. package/school/paper_search_school/engine/batch_login.py +223 -16
  146. package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
  147. package/school/paper_search_school/engine/batch_waits.py +179 -12
  148. package/school/paper_search_school/engine/bridge.py +44 -7
  149. package/school/paper_search_school/engine/fulltext_page.py +45 -7
  150. package/school/paper_search_school/engine/router.py +18 -2
  151. package/school/paper_search_school/entitlements.py +1 -1
  152. package/school/paper_search_school/orchestrator.py +44 -18
  153. package/school/paper_search_school/pdf_utils.py +25 -16
  154. package/school/paper_search_school/progress_capsule.py +36 -6
  155. package/school/paper_search_school/progress_reporter.py +71 -13
  156. package/school/paper_search_school/progress_view.py +64 -44
  157. package/school/paper_search_school/publishers/builtin/iop.json +2 -1
  158. package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
  159. package/school/paper_search_school/publishers/builtin/sage.json +4 -2
  160. package/school/paper_search_school/publishers/builtin/thieme.json +3 -1
  161. package/school/paper_search_school/publishers/site.py +12 -4
  162. package/school/paper_search_school/school_switch.py +34 -52
  163. package/school/paper_search_school/school_test.py +1 -1
  164. package/school/paper_search_school/server.py +24 -11
  165. package/school/paper_search_school/user_settings.py +13 -0
  166. package/school/pyproject.toml +1 -0
  167. package/skills/paper-search/SKILL.md +107 -107
  168. package/skills/paper-search/references/browser-download.md +102 -101
  169. package/skills/paper-search/references/capability-routing.md +89 -89
  170. package/skills/paper-search/references/cli-contract.md +78 -78
  171. package/skills/paper-search/references/federation-support.md +172 -172
  172. package/skills/paper-search/references/management-layer.md +78 -78
  173. package/skills/paper-search/references/publisher-support.md +38 -38
  174. package/skills/paper-search/references/school-setup.md +56 -55
  175. package/skills/paper-search/references/setup.md +20 -20
  176. package/skills/paper-search/references/troubleshooting.md +12 -12
  177. package/school/paper_search_school/browser/challenge/prompt.py +0 -154
@@ -0,0 +1,260 @@
1
+ """AWS WAF picture puzzles: capture the grid, apply service answers, and submit."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import time
6
+ from typing import Any
7
+
8
+ NAME = "awswaf"
9
+ KIND = "awswaf"
10
+ GRID_WAIT_SEC = 8.0
11
+ POLL_SEC = 0.5
12
+ CONFIRM_DELAY_SEC = 1.0
13
+ LEFT_WAIT_SEC = 12.0
14
+ ATTEMPTS = 3
15
+ RETRY_DELAY_SEC = 1.0
16
+ #: Its own control before and after the grid.
17
+ _BEGIN = "#amzn-captcha-verify-button"
18
+ _CONFIRM = "#amzn-btn-verify-internal"
19
+
20
+ _FIND = r"""() => {
21
+ const shown = el => !!el && el.getClientRects().length > 0;
22
+ const begin = document.querySelector('#amzn-captcha-verify-button');
23
+ const button = [...document.querySelectorAll('button, [role=button]')].find(el => shown(el)
24
+ && /begin|verify you are human|let's confirm/i.test((el.innerText || '').trim()));
25
+ const text = (document.body?.innerText || '').trim();
26
+ return {aws: !!document.querySelector('#amzn-captcha-container, #captcha-container, .amzn-captcha-root')
27
+ || !!begin || !!button || /choose all|select all/i.test(text),
28
+ ready: document.readyState !== 'loading' && text.length > 0,
29
+ title: document.title, text: text.slice(0, 300)};
30
+ }"""
31
+
32
+ _GRID = r"""() => {
33
+ const shown = el => !!el && el.getClientRects().length > 0;
34
+ const box = el => { const r = el.getBoundingClientRect();
35
+ return {x: r.x, y: r.y, width: r.width, height: r.height}; };
36
+ // The grid is the largest square-ish visible image or canvas on the page.
37
+ const squares = [...document.querySelectorAll('img, canvas, table')].filter(shown)
38
+ .map(el => ({el, box: box(el)}))
39
+ .filter(row => row.box.width >= 120 && row.box.height >= 120)
40
+ .sort((a, b) => b.box.width * b.box.height - a.box.width * a.box.height);
41
+ if (!squares.length) return {grid: null, question: ''};
42
+ const question = [...document.querySelectorAll('div, p, span, h1, h2, h3, label')]
43
+ .filter(shown).flatMap(el => (el.innerText || '').split('\n').map(line => line.trim()))
44
+ .find(text => text && text.length < 120 && /choose all|select all|choose the|select the|pick all|选择|选出/i.test(text)) || '';
45
+ return {grid: squares[0].box, question};
46
+ }"""
47
+
48
+
49
+
50
+ def find(page: Any) -> bool:
51
+ """Is this page AWS WAF's picture puzzle (its own button or the question line)?"""
52
+ try:
53
+ state = page.evaluate(_FIND)
54
+ except Exception: # noqa: BLE001 - a page that cannot be read is not this page
55
+ return False
56
+ return bool(isinstance(state, dict) and state.get("aws"))
57
+
58
+
59
+ def solve(page: Any, config: dict[str, Any] | None, *, observation: Any = None, limits: Any = None) -> bool:
60
+ """Try bounded image rounds; accept only a readable page without the puzzle."""
61
+ from ..services import solver as solver_module
62
+
63
+ note = observation or (lambda _reason: None)
64
+
65
+ def trace(message: str) -> None:
66
+ note(message)
67
+ try:
68
+ from ....config import DATA_DIR
69
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
70
+ with (DATA_DIR / "awswaf.log").open("a", encoding="utf-8") as handle:
71
+ handle.write(f"{time.strftime('%H:%M:%S')} {message}\n")
72
+ except OSError:
73
+ pass
74
+
75
+ trace(f"enter configured={solver_module.configured(config)} url={str(getattr(page, 'url', ''))[:80]}")
76
+ if not solver_module.configured(config):
77
+ trace("solver not configured")
78
+ return False
79
+ if limits is None:
80
+ from ..continuation import Limits
81
+ budget = getattr(page, "_papersearch_grid_budget", None)
82
+ if budget is None:
83
+ budget = solver_module.Budget(config=config)
84
+ page._papersearch_grid_budget = budget
85
+ limits = Limits(time.monotonic() + 180, budget)
86
+ budget = limits.budget
87
+ for attempt in range(1, ATTEMPTS + 1):
88
+ limits.remaining()
89
+ if not budget.take():
90
+ trace("solver budget spent")
91
+ return False
92
+ trace(f"attempt {attempt}")
93
+ if _attempt(page, config, trace, limits):
94
+ return True
95
+ trace(f"attempt {attempt} not completed")
96
+ limits.sleep(RETRY_DELAY_SEC)
97
+ return False
98
+
99
+
100
+ def _attempt(page: Any, config: dict[str, Any] | None, trace: Any, limits: Any) -> bool:
101
+ """One whole answer: Begin, the grid, the service, the clicks, Confirm, passed?"""
102
+ from ..services import solver as solver_module
103
+
104
+ limits.remaining()
105
+ if not _grid(page):
106
+ trace(f"begin pressed={_press(page, _BEGIN, trace)}")
107
+ grid = None
108
+ deadline = time.monotonic() + GRID_WAIT_SEC
109
+ while time.monotonic() < deadline:
110
+ limits.remaining()
111
+ state = _grid(page)
112
+ if state.get("grid"):
113
+ grid = state
114
+ break
115
+ limits.sleep(POLL_SEC)
116
+ if not grid:
117
+ trace("no grid")
118
+ return False
119
+ image = _screenshot(page, grid["grid"])
120
+ if not image:
121
+ trace("no screenshot")
122
+ return False
123
+ points = solver_module.solve_grid(image, grid.get("question") or "", config, kind=KIND,
124
+ timeout=min(limits.remaining(), float((config or {}).get("captcha_timeout", 90))))
125
+ limits.remaining()
126
+ if not points:
127
+ trace("no points")
128
+ return False
129
+ trace(f"points={len(points)} grid={grid['grid']} question={(grid.get('question') or '')[:40]}")
130
+ if not _click_points(page, grid["grid"], points, limits=limits):
131
+ trace("click failed")
132
+ return False
133
+ trace("points clicked")
134
+ # Let selection settle, then click the widget's Confirm control by its ID.
135
+ limits.sleep(CONFIRM_DELAY_SEC)
136
+ pressed = _press(page, _CONFIRM, trace, wait_sec=5.0)
137
+ trace(f"confirm pressed={pressed}")
138
+ if not pressed:
139
+ return False
140
+ # Pressing is not passing: the page says it left the puzzle, or the answer was
141
+ # not taken (the next attempt, or the user's wait as before).
142
+ deadline = time.monotonic() + LEFT_WAIT_SEC
143
+ while time.monotonic() < deadline:
144
+ limits.remaining()
145
+ try:
146
+ state = page.evaluate(_FIND)
147
+ except Exception: # noqa: BLE001 - navigation or a closed page is not acceptance
148
+ state = None
149
+ if isinstance(state, dict) and state.get("ready") and state.get("aws") is False:
150
+ trace("page passed")
151
+ return True
152
+ limits.sleep(POLL_SEC)
153
+ trace("still on the puzzle")
154
+ return False
155
+
156
+
157
+ def _press(page: Any, selector: str, note: Any, *, wait_sec: float = 0.0) -> bool:
158
+ """One press on the page's own control, when it is there and actionable.
159
+
160
+ ``wait_sec``: the control may still be disabled while the tiles are being
161
+ clicked (AWS WAF's "Confirm" enables once a tile is chosen), so it is looked
162
+ for again a few times before the press is given up.
163
+ """
164
+ deadline = time.monotonic() + max(0.0, wait_sec)
165
+ while True:
166
+ try:
167
+ control = page.locator(selector).first
168
+ if control.count() and control.is_visible():
169
+ if control.is_enabled():
170
+ control.click(timeout=3000, no_wait_after=True)
171
+ return True
172
+ except Exception as exc: # noqa: BLE001 - a control that cannot be pressed is the user's
173
+ note(f"press {selector}: {type(exc).__name__}")
174
+ return False
175
+ if time.monotonic() >= deadline:
176
+ note(f"press {selector}: not actionable")
177
+ return False
178
+ time.sleep(0.3)
179
+
180
+
181
+ def _grid(page: Any) -> dict:
182
+ """The grid's box and its question line, or {} while it is not up yet."""
183
+ try:
184
+ state = page.evaluate(_GRID)
185
+ except Exception: # noqa: BLE001 - a page that cannot be read has no grid
186
+ return {}
187
+ return state if isinstance(state, dict) and state.get("grid") else {}
188
+
189
+
190
+ def _screenshot(page: Any, box: dict) -> bytes:
191
+ """The whole grid as one picture: the service is given one image, not nine."""
192
+ try:
193
+ clip = {key: float(box[key]) for key in ("x", "y", "width", "height")}
194
+ # Answers are in image pixels; use one pixel per CSS pixel on Retina too.
195
+ return page.screenshot(clip=clip, scale="css") or b""
196
+ except Exception: # noqa: BLE001 - a picture that cannot be taken answers nothing
197
+ return b""
198
+
199
+
200
+ def _click_points(page: Any, box: dict, points: list, *, limits: Any = None) -> bool:
201
+ """Click the answer: the tiles' own buttons, or the picture's pixels.
202
+
203
+ The service answers with points of the picture; the page's nine
204
+ ``button.amzn-grid-cell`` tiles take a press, so a point names its tile
205
+ (a third of the picture each way) and that tile's button is pressed.
206
+ """
207
+ if not points:
208
+ return False
209
+ tiles = all(isinstance(value, (int, float)) and value in (0, 1, 2)
210
+ for point in points for value in point)
211
+ cells = []
212
+ try:
213
+ cells = page.locator("button.amzn-grid-cell").all()
214
+ except Exception: # noqa: BLE001 - no cell buttons: the picture is clicked instead
215
+ cells = []
216
+ targets = []
217
+ for x, y in points:
218
+ if not all(isinstance(v, (int, float)) and math.isfinite(v) for v in (x, y)):
219
+ return False
220
+ if not tiles and not (0 <= x < box["width"] and 0 <= y < box["height"]):
221
+ return False
222
+ index = None
223
+ if tiles:
224
+ index = int(y) * 3 + int(x)
225
+ elif len(cells) == 9:
226
+ index = int(y / (box["height"] / 3)) * 3 + int(x / (box["width"] / 3))
227
+ target = index if index is not None else (x, y)
228
+ if target not in targets:
229
+ targets.append(target)
230
+ # A rejected answer can leave tiles selected on the same question. Apply
231
+ # the whole new selection, including clearing obsolete choices.
232
+ if len(cells) == 9 and all(isinstance(target, int) for target in targets):
233
+ for index, cell in enumerate(cells):
234
+ if limits is not None:
235
+ limits.remaining()
236
+ try:
237
+ if index not in targets and cell.get_attribute("aria-checked") == "true":
238
+ cell.click(timeout=2000, no_wait_after=True)
239
+ if cell.get_attribute("aria-checked") != "false":
240
+ return False
241
+ except Exception: # noqa: BLE001 - do not submit a partially updated answer
242
+ return False
243
+ for target in targets:
244
+ if limits is not None:
245
+ limits.remaining()
246
+ try:
247
+ if isinstance(target, int):
248
+ if len(cells) != 9:
249
+ return False
250
+ cell = cells[target]
251
+ if cell.get_attribute("aria-checked") != "true":
252
+ cell.click(timeout=2000, no_wait_after=True)
253
+ if cell.get_attribute("aria-checked") != "true":
254
+ return False
255
+ else:
256
+ page.mouse.click(box["x"] + target[0], box["y"] + target[1])
257
+ time.sleep(0.2)
258
+ except Exception: # noqa: BLE001 - an incomplete answer must not be submitted
259
+ return False
260
+ return True
@@ -0,0 +1,167 @@
1
+ """Known reCAPTCHA/hCaptcha grid controls, with provider-specific image contracts.
2
+
3
+ Unknown geometry, drag/audio questions and changing images are never guessed.
4
+ The enclosing verification wait alone decides whether the publisher passed.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import struct
9
+ from typing import Any
10
+ from urllib.parse import urlsplit
11
+
12
+ from ...driver import Error
13
+ from ..local import prompt
14
+ from ..services import solver
15
+
16
+ # Official ReCaptchaV2Classification question IDs. Only exact visible labels;
17
+ # unknown languages/categories stay manual instead of being mistranslated.
18
+ _QUESTIONS = {
19
+ "taxis": "/m/0pg52", "bus": "/m/01bjv", "buses": "/m/01bjv",
20
+ "motorcycles": "/m/04_sv", "tractors": "/m/013xlm", "chimneys": "/m/01jk_4",
21
+ "crosswalks": "/m/014xcs", "traffic lights": "/m/015qff", "bicycles": "/m/0199g",
22
+ "parking meters": "/m/015qbp", "cars": "/m/0k4j", "bridges": "/m/015kr",
23
+ "boats": "/m/019jd", "palm trees": "/m/0cdl1", "mountains or hills": "/m/09d_r",
24
+ "fire hydrant": "/m/01pns0", "fire hydrants": "/m/01pns0", "stairs": "/m/01lynh",
25
+ }
26
+ _SELECTORS = {
27
+ "recaptcha": (".rc-imageselect-desc-wrapper", ".rc-imageselect-tile", "#recaptcha-verify-button"),
28
+ "hcaptcha": (".prompt-text", ".task-image", ".button-submit"),
29
+ }
30
+ _SIGNATURE = """els => els.map(el => [...el.querySelectorAll('img, .image')].map(im =>
31
+ [im.currentSrc || im.getAttribute('src'), getComputedStyle(im).backgroundImage]))"""
32
+
33
+
34
+ def _frame(page: Any, kind: str) -> Any:
35
+ frames = getattr(page, "frames", ())
36
+ for frame in frames if isinstance(frames, (tuple, list)) else ():
37
+ p = urlsplit(str(frame.url or ""))
38
+ host = p.hostname or ""
39
+ matches = (kind == "recaptcha" and host in {"www.google.com", "google.com", "www.recaptcha.net", "recaptcha.net"}
40
+ and p.path in {"/recaptcha/api2/bframe", "/recaptcha/enterprise/bframe"}) or (
41
+ kind == "hcaptcha" and (host == "hcaptcha.com" or host.endswith(".hcaptcha.com"))
42
+ and p.path.startswith("/captcha/"))
43
+ if matches and frame.frame_element().is_visible():
44
+ if frame.locator(_SELECTORS[kind][1]).count():
45
+ return frame
46
+ return None
47
+
48
+
49
+ def has_grid(page: Any) -> bool:
50
+ """Stop checkbox waiting as soon as a supported provider shows a picture grid."""
51
+ try:
52
+ return any(_frame(page, kind) is not None for kind in _SELECTORS)
53
+ except Error:
54
+ return False
55
+
56
+
57
+ def _snapshot(frame: Any, kind: str, limits: Any) -> dict | None:
58
+ question_sel, cell_sel, _ = _SELECTORS[kind]
59
+ cells = frame.locator(cell_sel)
60
+ count = cells.count()
61
+ if count not in ((9, 16) if kind == "recaptcha" else (9,)):
62
+ return None
63
+ limits.remaining()
64
+ question = frame.locator(question_sel).inner_text(timeout=1000).strip()
65
+ signature = cells.evaluate_all(_SIGNATURE)
66
+ anchors = []
67
+ if kind == "recaptcha":
68
+ label = frame.locator(question_sel + " strong").inner_text(timeout=1000).strip().lower()
69
+ question = _QUESTIONS.get(label, "")
70
+ if not question:
71
+ return None
72
+ picture = frame.locator(".rc-imageselect-table-33, .rc-imageselect-table-44")
73
+ if picture.count() != 1:
74
+ return None
75
+ images = [picture.screenshot(scale="css", timeout=min(2000, int(limits.remaining()*1000)))]
76
+ expected = 300 if count == 9 else 450
77
+ if images[0][:8] != b'\x89PNG\r\n\x1a\n' or struct.unpack('>II', images[0][16:24]) != (expected, expected):
78
+ return None
79
+ else:
80
+ if not question or question.lower().startswith(('drag', 'please drag')):
81
+ return None
82
+ images = []
83
+ for i in range(count):
84
+ images.append(cells.nth(i).locator('.image').screenshot(
85
+ scale="css", timeout=min(2000, int(limits.remaining()*1000))))
86
+ # Examples can be an image or a background on the example container
87
+ # itself. Select visible picture surfaces above the tiles, outside them;
88
+ # selectors for one particular prompt wrapper miss other hCaptcha builds.
89
+ for anchor in frame.locator('img, canvas, .image, [style*="background-image"]').all():
90
+ if anchor.evaluate('''el => {
91
+ if(el.closest('.task-image') || !el.getClientRects().length) return false;
92
+ const r=el.getBoundingClientRect(), first=document.querySelector('.task-image');
93
+ if(!first || r.bottom>first.getBoundingClientRect().top+2 ||
94
+ r.width<30 || r.height<30 || r.width>300 || r.height>300) return false;
95
+ return /^(IMG|CANVAS)$/.test(el.tagName) || getComputedStyle(el).backgroundImage!=='none';
96
+ }''', timeout=min(1000, max(1, int(limits.remaining()*1000)))):
97
+ anchors.append(anchor.screenshot(scale="css", timeout=min(2000, int(limits.remaining()*1000))))
98
+ if signature != cells.evaluate_all(_SIGNATURE):
99
+ return None
100
+ return dict(question=question, signature=signature, images=images, anchors=anchors, count=count)
101
+
102
+
103
+ def solve(page: Any, config: dict, *, kind: str, limits: Any, observation: Any) -> bool:
104
+ note = observation
105
+ try:
106
+ for round_number in range(1, 4):
107
+ limits.remaining()
108
+ if prompt.confirm_checked(page):
109
+ return True # engine owns the common outer-form submission
110
+ frame = _frame(page, kind)
111
+ if frame is None:
112
+ note(f"{kind}: no visible grid")
113
+ return False
114
+ grid = _snapshot(frame, kind, limits)
115
+ if grid is None:
116
+ note(f"{kind}: unsupported or unstable grid/question")
117
+ return False
118
+ if not limits.budget.take():
119
+ note("service budget exhausted")
120
+ return False
121
+ note(f"{kind}: service request images={len(grid['images'])} examples={len(grid['anchors'])}")
122
+ answer = solver.solve_tiles(grid['images'], grid['question'], config, kind=kind,
123
+ count=grid['count'], anchors=grid['anchors'],
124
+ timeout=min(limits.remaining(), float(config.get('captcha_timeout', 90))),
125
+ checkpoint=limits.remaining)
126
+ limits.remaining()
127
+ if answer is None:
128
+ note(f"{kind}: service failed or invalid answer")
129
+ return False
130
+ cells = frame.locator(_SELECTORS[kind][1])
131
+ # Do not apply an answer to images replaced while the service worked.
132
+ if cells.evaluate_all(_SIGNATURE) != grid['signature']:
133
+ note(f"{kind}: images changed; discard answer")
134
+ continue
135
+ changed = False
136
+ for index in range(grid['count']):
137
+ limits.remaining()
138
+ if cells.evaluate_all(_SIGNATURE) != grid['signature']:
139
+ changed = True
140
+ break
141
+ cell = cells.nth(index)
142
+ selected = cell.get_attribute('aria-pressed', timeout=min(1000, max(1, int(limits.remaining()*1000)))) == 'true' or cell.get_attribute('aria-checked', timeout=min(1000, max(1, int(limits.remaining()*1000)))) == 'true'
143
+ selected = selected or 'rc-imageselect-tileselected' in (cell.get_attribute('class', timeout=min(1000, max(1, int(limits.remaining()*1000)))) or '')
144
+ if selected != (index in answer):
145
+ cell.click(timeout=min(2000, int(limits.remaining()*1000)), no_wait_after=True)
146
+ limits.sleep(1)
147
+ if changed or cells.evaluate_all(_SIGNATURE) != grid['signature']:
148
+ note(f"{kind}: replacement images; read next round")
149
+ continue
150
+ frame.locator(_SELECTORS[kind][2]).click(
151
+ timeout=min(2000, int(limits.remaining()*1000)), no_wait_after=True)
152
+ note(f"{kind}: answer submitted; round {round_number}/3")
153
+ # The provider may acknowledge asynchronously after hiding the grid.
154
+ # Observe before taking another snapshot or paying for another answer.
155
+ for _ in range(10):
156
+ limits.sleep(0.5)
157
+ if prompt.confirm_checked(page) or _frame(page, kind) is None:
158
+ return True # outer loop owns form submission and access checks
159
+ note(f"{kind}: three image rounds exhausted")
160
+ return False
161
+ except Error as exc:
162
+ if any(marker in str(exc).lower() for marker in (
163
+ "frame was detached", "frame has been detached", "execution context was destroyed")):
164
+ note(f"{kind}: document changed; outer verification must recheck")
165
+ return True
166
+ note(f"{kind}: browser interaction failed ({type(exc).__name__})")
167
+ return False
@@ -0,0 +1,100 @@
1
+ """A standalone character challenge: capture only the code, fill one field.
2
+
3
+ Geometry and form structure, not publisher domains, identify the code. Visible
4
+ password/email fields and article metadata exclude login/article pages. No
5
+ hidden fields, cookies, DOM text answers or full-page images leave the browser.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from ...driver import Error
12
+ from ..services import solver
13
+ from ..local import submission
14
+
15
+ _FIND = r'''() => {
16
+ const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden';
17
+ const text = (document.body?.innerText || '').trim();
18
+ if (text.length > 2500 || document.querySelector('meta[name="citation_doi"]') ||
19
+ [...document.querySelectorAll('input[type=password],input[type=email]')].some(shown)) return null;
20
+ if (!/captcha|not a robot|letters.{0,20}numbers|验证码/i.test(document.title+' '+text)) return null;
21
+ const fields = [...document.querySelectorAll('input[type=text],input:not([type])')].filter(el=>shown(el)&&!el.disabled);
22
+ if(fields.length!==1) return null;
23
+ const field=fields[0], f=field.getBoundingClientRect();
24
+ const pictures=[...document.querySelectorAll('img,canvas,.puzzle,[class*=captcha-image],[id*=captchaImage]')]
25
+ .filter(shown).map(el=>({el,r:el.getBoundingClientRect()}))
26
+ .filter(({r})=>r.width>=25 && r.width<=600 && r.height>=15 && r.height<=200 &&
27
+ r.bottom<=f.top+5 && f.top-r.bottom<=160 && r.left<f.right && r.right>f.left)
28
+ .sort((a,b)=>(f.top-a.r.bottom)-(f.top-b.r.bottom));
29
+ if(!pictures.length || (pictures.length>1 && Math.abs(pictures[0].r.bottom-pictures[1].r.bottom)<5))return null;
30
+ const picture=pictures[0].el;
31
+ let scope=field.form;
32
+ if(!scope){
33
+ scope=field.parentElement;
34
+ while(scope && !scope.contains(picture))scope=scope.parentElement;
35
+ if(!scope || scope===document.body || scope===document.documentElement)return null;
36
+ }
37
+ const submits = (''' + submission.CANDIDATES + r''')(field.form, scope);
38
+ // Disabled controls still count: filling the answer may enable them. Click waits
39
+ // for actionability; multiple possible submits never become a guessed action.
40
+ if(submits.length!==1)return null;
41
+ const selector=el=>el.id ? '#'+CSS.escape(el.id) : (()=>{
42
+ const parts=[];while(el && el!==document.documentElement){
43
+ const tag=el.tagName.toLowerCase();const siblings=[...el.parentElement.children].filter(e=>e.tagName===el.tagName);
44
+ parts.unshift(tag+':nth-of-type('+(siblings.indexOf(el)+1)+')');el=el.parentElement;
45
+ }return 'html > '+parts.join(' > ');
46
+ })();
47
+ return {picture:selector(picture),field:selector(field),submit:selector(submits[0])};
48
+ }'''
49
+
50
+
51
+ def find(page: Any) -> dict | None:
52
+ try:
53
+ value = page.evaluate(_FIND)
54
+ if isinstance(value, dict) and all(isinstance(value.get(k), str) for k in ('picture', 'field', 'submit')):
55
+ return value
56
+ except Error:
57
+ pass # the outer verification loop rechecks navigation
58
+ return None
59
+
60
+
61
+ def solve(page: Any, config: dict, *, limits: Any, observation: Any) -> bool:
62
+ note = observation
63
+ try:
64
+ for attempt in range(1, 4):
65
+ limits.remaining()
66
+ controls = find(page)
67
+ if not controls:
68
+ note('image_code: no unambiguous standalone code form')
69
+ return False
70
+ picture = page.locator(controls['picture'])
71
+ image = picture.screenshot(scale='css', timeout=min(2000, int(limits.remaining()*1000)))
72
+ if not limits.budget.take():
73
+ note('service budget exhausted')
74
+ return False
75
+ answer = solver.solve_image(image, config, timeout=min(limits.remaining(), float(config.get('captcha_timeout', 90))),
76
+ checkpoint=limits.remaining)
77
+ limits.remaining()
78
+ if not answer or len(answer)>64 or not answer.isalnum():
79
+ note('image_code: service failed or invalid text')
80
+ return False
81
+ if controls != find(page) or image != picture.screenshot(scale='css', timeout=min(2000, int(limits.remaining()*1000))):
82
+ note('image_code: code changed; discard answer')
83
+ continue
84
+ page.locator(controls['field']).fill(answer, timeout=min(2000, int(limits.remaining()*1000)))
85
+ limits.remaining()
86
+ if controls != find(page):
87
+ note('image_code: form changed after filling; stop')
88
+ return False
89
+ page.locator(controls['submit']).click(timeout=min(2000, int(limits.remaining()*1000)), no_wait_after=True)
90
+ note(f'image_code: submitted; attempt {attempt}/3')
91
+ limits.sleep(2)
92
+ if not find(page):
93
+ return True # outer loop checks the resulting page, never assume pass here
94
+ note('image_code: three attempts exhausted')
95
+ return False
96
+ except Error as exc:
97
+ if any(text in str(exc).lower() for text in ('frame was detached','execution context was destroyed')):
98
+ return True
99
+ note(f'image_code: browser interaction failed ({type(exc).__name__})')
100
+ return False