browser-assistant 2.9.8 → 2.9.9

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.
@@ -160,26 +160,87 @@
160
160
  const numberedPrompt = /^(\d+)[.)]\s+.{3,1000}\?$/;
161
161
  const blankNumbers = (text) => [...text.matchAll(/\(\s*(\d+)\s*\)\s*(?:_{2,}|\.{3,}|…)/g)]
162
162
  .map(match => Number(match[1]));
163
+ const readingText = (node, separateInline = false) => {
164
+ const copy = node.cloneNode(true);
165
+ copy.querySelectorAll('script,style,template,[hidden],[aria-hidden="true"]').forEach(child => child.remove());
166
+ copy.querySelectorAll(separateInline ? 'br,p,div,li,span,strong,b,em' : 'br,p,div,li').forEach(child => {
167
+ child.before('\n');
168
+ child.after('\n');
169
+ });
170
+ return (copy.textContent || '').trim();
171
+ };
172
+ const phraseKeywords = (context) => {
173
+ const keywords = new Map();
174
+ // Preserve rendered lines when available. Some portals join
175
+ // the end of one item directly to the next item number.
176
+ const items = [...context.matchAll(/(?:^|[^\w])([1-9]\d*)\s*[.)]\s*(?=[A-Za-z])/g)];
177
+ for (const [index, item] of items.entries()) {
178
+ const pair = context.slice(item.index + item[0].length, items[index + 1]?.index);
179
+ const standalone = [...pair.matchAll(/^\s*([A-Z]{2,})\s*$/gm)].map(match => match[1]);
180
+ const candidates = standalone.length ? standalone : pair.match(/\b[A-Z]{2,}\b/g) || [];
181
+ if ((pair.match(/_{2,}/g) || []).length !== 1 || candidates.length !== 1
182
+ || keywords.has(Number(item[1])))
183
+ return null;
184
+ keywords.set(Number(item[1]), candidates[0]);
185
+ }
186
+ return keywords;
187
+ };
163
188
  const pageText = doc.body.innerText || doc.body.textContent || '';
164
189
  const readingRange = /questions\s+(\d+)\s*[-–—]\s*(\d+)/i.exec(pageText);
165
- const phraseSet = /which phrase best completes/i.test(pageText) && /between two and five words/i.test(pageText);
190
+ const phraseSet = /which\s+phrase\s+best\s+completes/i.test(pageText)
191
+ && /(?:two\s+and\s+five|2\s*(?:and|to|[-–—])\s*5)\s+words/i.test(pageText);
166
192
  const gapSet = blankNumbers(pageText).length >= 2 && /which (?:word|sentence) (?:best )?fits/i.test(pageText);
167
193
  if (gapSet || phraseSet || readingRange) {
168
- const promptPattern = gapSet ? blankPrompt : phraseSet ? phrasePrompt : numberedPrompt;
169
- const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,legend,[role="heading"]')]
194
+ const promptPattern = phraseSet ? phrasePrompt : gapSet ? blankPrompt : numberedPrompt;
195
+ const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,label,section,article,legend,[role="heading"]')]
170
196
  .filter(node => visible(node) && !node.closest('#assistant-root,nav,aside'));
171
197
  const headings = blocks.filter(node => promptPattern.test((node.textContent || '').trim())
172
- && ![...node.children].some(child => promptPattern.test((child.textContent || '').trim())));
173
- let passage = gapSet && blocks.find(node => {
198
+ && ![...node.querySelectorAll('div,p,h1,h2,h3,h4,span,label,section,article,legend,[role="heading"]')]
199
+ .some(child => promptPattern.test((child.textContent || '').trim())));
200
+ const headingNumbers = headings.map(node => Number(textOf(node).match(promptPattern)?.[1]));
201
+ let phraseContext;
202
+ let phrases;
203
+ let passage = !phraseSet && gapSet && blocks.find(node => {
174
204
  const text = node.textContent || '';
175
205
  return text.length <= 12000 && blankNumbers(text).length >= 2
176
206
  && !/which (?:word|sentence) (?:best )?fits/i.test(text) && !node.querySelector(radioSelector)
177
207
  && ![...node.children].some(child => blankNumbers(child.textContent || '').length >= 2);
178
208
  });
179
- if (!gapSet && headings.length) {
209
+ if (phraseSet && headings.length >= 2) {
210
+ // Some layouts place directions and the numbered source
211
+ // text in different wrappers. Find the source by its gaps,
212
+ // independent of where the directions are rendered.
213
+ const sources = blocks.filter(node => {
214
+ const raw = node.textContent || '';
215
+ return raw.length <= 12000 && (raw.match(/_{2,}/g) || []).length >= 2
216
+ && !node.querySelector(`${radioSelector},${readingFieldSelector}`);
217
+ });
218
+ const gapCount = node => (node.textContent.match(/_{2,}/g) || []).length;
219
+ const total = Math.max(0, ...sources.map(gapCount));
220
+ if (total !== headings.length)
221
+ return null;
222
+ for (const source of sources.reverse()) {
223
+ if (gapCount(source) !== total)
224
+ continue;
225
+ for (const context of [source.innerText?.trim(), readingText(source), readingText(source, true)]) {
226
+ if (!context)
227
+ continue;
228
+ const found = phraseKeywords(context);
229
+ if (found?.size !== total || !headingNumbers.every(number => found.has(number)))
230
+ continue;
231
+ passage = source;
232
+ phraseContext = context;
233
+ phrases = found;
234
+ break;
235
+ }
236
+ if (passage)
237
+ break;
238
+ }
239
+ }
240
+ else if (!gapSet && !phraseSet && headings.length) {
180
241
  // The passage occupies a separate column preceding the
181
242
  // shared answer column. Never use the timer or palette.
182
- const instruction = phraseSet ? /complete the second sentence/i : /read the (?:text|comments|passage)/i;
243
+ const instruction = /read the (?:text|comments|passage)/i;
183
244
  for (let column = headings[0].parentElement; column && column !== doc.body && !passage; column = column.parentElement) {
184
245
  if (!headings.every(heading => column.contains(heading)))
185
246
  continue;
@@ -194,23 +255,9 @@
194
255
  }
195
256
  }
196
257
  if (passage && headings.length) {
197
- const copy = passage.cloneNode(true);
198
- copy.querySelectorAll('br,p,div,li').forEach(node => { node.before('\n'); node.after('\n'); });
199
- const context = (copy.textContent || '').trim();
200
- const headingNumbers = headings.map(node => Number(textOf(node).match(promptPattern)?.[1]));
201
- const phrases = new Map();
202
- if (phraseSet) {
203
- const items = [...context.matchAll(/(?:^|\s)(\d+)\s*[.)]\s+/g)];
204
- for (const [index, item] of items.entries()) {
205
- const pair = context.slice(item.index + item[0].length, items[index + 1]?.index);
206
- const keywords = pair.match(/\b[A-Z]{2,}\b/g) || [];
207
- if (!/_{2,}/.test(pair) || keywords.length !== 1 || phrases.has(Number(item[1])))
208
- return null;
209
- phrases.set(Number(item[1]), keywords[0]);
210
- }
211
- }
258
+ const context = phraseContext || readingText(passage);
212
259
  const count = readingRange ? Number(readingRange[2]) - Number(readingRange[1]) + 1 : 0;
213
- const numbers = (gapSet ? blankNumbers(context) : phraseSet ? [...phrases.keys()]
260
+ const numbers = (phraseSet ? [...phrases.keys()] : gapSet ? blankNumbers(context)
214
261
  : count >= 2 && count <= 30 ? Array.from({ length: count }, (_, index) => Number(readingRange[1]) + index) : [])
215
262
  .sort((a, b) => a - b);
216
263
  // A partially rendered or unrecognized reading set must
@@ -248,7 +295,7 @@
248
295
  const next = headings[position + 1] || submit;
249
296
  const group = fields.filter(node => follows(heading, node) && follows(node, next));
250
297
  return { text: textOf(heading), options: [], input: group.length === 1 ? group[0] : null,
251
- requiredWord: phrases.get(headingNumbers[position]), container: scope };
298
+ requiredWord: phrases?.get(headingNumbers[position]), container: scope };
252
299
  });
253
300
  if (questions.some(question => !question.input) || fields.length !== questions.length)
254
301
  return null;
@@ -334,6 +381,18 @@
334
381
  groups.get(key).push(control);
335
382
  }
336
383
  const radioCandidates = [];
384
+ const choiceSelector = 'input[type="radio"],input[type="checkbox"],[role="radio"],[role="checkbox"]';
385
+ const codeSelector = 'pre,code,.ace_editor,.CodeMirror,.monaco-editor';
386
+ const promptSelector = '#generic-question-wrapper-id,#exam-question-wrapper-id,[data-question-text]';
387
+ const readable = node => visible(node) && !node.closest('[hidden],[aria-hidden="true"],[inert],#assistant-root')
388
+ && doc.defaultView?.getComputedStyle?.(node)?.visibility !== 'hidden';
389
+ const proseText = node => {
390
+ if (!readable(node) || node.matches(codeSelector))
391
+ return '';
392
+ const clone = node.cloneNode(true);
393
+ clone.querySelectorAll(`${codeSelector},[hidden],[aria-hidden="true"],[inert]`).forEach(child => child.remove());
394
+ return textOf(clone);
395
+ };
337
396
  for (const group of groups.values()) {
338
397
  if (group.length < 2)
339
398
  continue;
@@ -362,27 +421,23 @@
362
421
  const fieldset = container.closest('fieldset') || group[0].closest('fieldset');
363
422
  const radioGroup = group[0].closest('[role="radiogroup"]');
364
423
  const optionScope = fieldset || radioGroup || group[0].parentElement?.parentElement || container;
365
- const heading = fieldset?.querySelector('legend')
366
- || radioGroup?.querySelector('h1,h2,h3,h4,[role="heading"]')
367
- || container.querySelector?.('h1,h2,h3,h4,[role="heading"]');
424
+ const heading = [fieldset?.querySelector('legend'), radioGroup?.querySelector('h1,h2,h3,h4,[role="heading"]'),
425
+ container.querySelector?.('h1,h2,h3,h4,[role="heading"]')].find(node => node && readable(node));
368
426
  const localPrompt = [...optionScope.querySelectorAll('p,h1,h2,h3,h4,[role="heading"],div,span')]
369
- .find(node => !node.querySelector('input[type="radio"],input[type="checkbox"],[role="radio"],[role="checkbox"]')
427
+ .find(node => readable(node) && !node.matches(choiceSelector) && !node.querySelector(choiceSelector)
428
+ && !options.some(option => option.node.contains(node))
370
429
  && textOf(node).length >= 12 && textOf(node).length <= 1200);
371
430
  let nearbyPrompt = '';
372
- let branch = optionScope;
373
- for (let ancestor = optionScope; ancestor && ancestor !== doc.body && !nearbyPrompt; ancestor = ancestor.parentElement) {
431
+ for (let branch = optionScope; branch && branch !== doc.body && !nearbyPrompt; branch = branch.parentElement) {
374
432
  for (let sibling = branch.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
375
- const prose = sibling.cloneNode(true);
376
- prose.querySelectorAll('pre,code,.ace_editor,.CodeMirror,.monaco-editor').forEach(node => node.remove());
377
- const candidate = sibling.matches('pre,code,.ace_editor,.CodeMirror,.monaco-editor') ? '' : textOf(prose);
378
- if (candidate.length >= 20 && candidate.length <= 1200 && !sibling.querySelector('input[type="radio"],[role="radio"]')) {
433
+ const candidate = proseText(sibling);
434
+ if (candidate.length >= 20 && candidate.length <= 1200
435
+ && !sibling.matches(choiceSelector) && !sibling.querySelector(choiceSelector)
436
+ && !options.some(option => option.node === sibling || option.node.contains(sibling))) {
379
437
  nearbyPrompt = candidate;
380
438
  break;
381
439
  }
382
440
  }
383
- branch = ancestor;
384
- if (ancestor === doc.body)
385
- break;
386
441
  }
387
442
  const text = textOf(heading) || textOf(localPrompt) || labelledText(radioGroup) || labelledText(container)
388
443
  || radioGroup?.getAttribute('aria-label') || container.getAttribute('aria-label') || nearbyPrompt;
@@ -390,12 +445,18 @@
390
445
  continue;
391
446
  // Coding MCQs often render the code separately from the prose
392
447
  // question. Preserve that visible context before asking the AI.
393
- const questionRegion = optionScope.closest('[data-question],article,section,main') || optionScope.parentElement;
394
- const promptRegion = questionRegion?.querySelector('#generic-question-wrapper-id,#exam-question-wrapper-id,[data-question-text]')
395
- || doc.querySelector('#generic-question-wrapper-id,#exam-question-wrapper-id');
448
+ const questionRegion = optionScope.closest('[data-question],#generic-question-container,#exam-question-container,article,section,main')
449
+ || optionScope.parentElement;
450
+ const promptRegion = [...(questionRegion?.querySelectorAll(promptSelector) || [])].find(node => {
451
+ if (node.querySelector(choiceSelector))
452
+ return false;
453
+ const prose = proseText(node);
454
+ return prose.length >= 12 && (prose.includes(text.trim()) || text.includes(prose));
455
+ });
396
456
  const sourceRegion = promptRegion || questionRegion;
397
- const snippets = [...(sourceRegion?.querySelectorAll('pre,code,.ace_editor,.CodeMirror,.monaco-editor') || [])]
398
- .filter(node => visible(node) && !node.parentElement?.closest('pre,code,.ace_editor,.CodeMirror,.monaco-editor'));
457
+ const snippets = [...(sourceRegion?.querySelectorAll(codeSelector) || [])]
458
+ .filter(node => readable(node) && !node.parentElement?.closest(codeSelector)
459
+ && (!node.closest(promptSelector) || node.closest(promptSelector) === promptRegion));
399
460
  const codeText = node => {
400
461
  const lines = [...node.querySelectorAll('.ace_line,.view-line,.CodeMirror-line')];
401
462
  if (lines.length)
@@ -405,7 +466,7 @@
405
466
  return (clone.textContent || '').trim();
406
467
  };
407
468
  let questionText;
408
- if (promptRegion && !promptRegion.querySelector('input[type="radio"],[role="radio"]')) {
469
+ if (promptRegion) {
409
470
  // Preserve filenames, prose and ALL snippets together; the
410
471
  // last code block alone is not the question's full context.
411
472
  const clone = promptRegion.cloneNode(true);
@@ -531,6 +531,11 @@ function mountJournalCountdown(signal) {
531
531
  if (!answer)
532
532
  return [];
533
533
  const normalize = value => value.trim().replace(/\r\n/g, '\n').replace(/(\d) +%/g, '$1%');
534
+ const complexityKey = (value) => {
535
+ const expression = value.trim().replace(/^\x60([^\x60\r\n]+)\x60$/, '$1').trim();
536
+ return /^O[ \t]*\([A-Za-z0-9 \t+*/^().-]+\)$/.test(expression)
537
+ ? expression.replace(/[ \t]+/g, ' ').replace(/ *([()+*/^.-]) */g, '$1') : '';
538
+ };
534
539
  const matrixSyntax = /\\begin\{(?:[bpBvV]?matrix|smallmatrix)\}/;
535
540
  const matrixQuestion = matrixSyntax.test(question.text ?? '') || question.options.some(option => matrixSyntax.test(option.text));
536
541
  const matrixKey = (value) => {
@@ -547,6 +552,9 @@ function mountJournalCountdown(signal) {
547
552
  const matchesOption = (option, candidate) => {
548
553
  if (normalize(option) === normalize(candidate))
549
554
  return true;
555
+ const complexity = complexityKey(option);
556
+ if (complexity && complexity === complexityKey(candidate))
557
+ return true;
550
558
  const matrix = matrixQuestion && matrixKey(option);
551
559
  return Boolean(matrix && matrix === matrixKey(candidate));
552
560
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.8",
4
+ "version": "2.9.9",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.8",
3
+ "version": "2.9.9",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
package/server/main.py CHANGED
@@ -191,7 +191,7 @@ async def lifespan(_app: FastAPI):
191
191
  client.close()
192
192
 
193
193
 
194
- app = FastAPI(title="Browser Assistant API", version="2.9.8", lifespan=lifespan)
194
+ app = FastAPI(title="Browser Assistant API", version="2.9.9", lifespan=lifespan)
195
195
  install_local_guards(app)
196
196
 
197
197
  @app.exception_handler(HTTPException)
@@ -336,15 +336,16 @@ def normalize_checked_answer(value, *, matrix_math=False):
336
336
  value = re.sub(r'(^|;[ \t]*)(?:option[ \t]+)?([a-z])[ \t]*[:.)][ \t]*',
337
337
  lambda match: ('; ' if match[1] else '') + f'Option {match[2].upper()}: ',
338
338
  value, flags=re.I)
339
- if not matrix_math:
340
- return value
341
339
  choices = re.split(r'; (?=Option [A-Z]: )', value)
342
340
  normalized = []
343
341
  for choice in choices:
344
342
  label = re.match(r'Option [A-Z]: ', choice)
345
343
  prefix = label[0] if label else ''
346
344
  body = choice[len(prefix):]
347
- normalized.append(prefix + (numeric_matrix_key(body) or body))
345
+ expression = re.sub(r'^\x60([^\x60\r\n]+)\x60$', r'\1', body.strip()).strip()
346
+ if re.fullmatch(r'O[ \t]*\([A-Za-z0-9 \t+*/^().-]+\)', expression):
347
+ body = re.sub(r' *([()+*/^.-]) *', r'\1', re.sub(r'[ \t]+', ' ', expression))
348
+ normalized.append(prefix + ((numeric_matrix_key(body) if matrix_math else None) or body))
348
349
  return '; '.join(normalized)
349
350
 
350
351