(text, language="en-US", accept_re=None)
| 444 | |
| 445 | |
| 446 | def run_languagetool(text, language="en-US", accept_re=None): |
| 447 | try: |
| 448 | import language_tool_python |
| 449 | except ImportError: |
| 450 | print( |
| 451 | "language_tool_python is not installed; skipping LanguageTool check.", |
| 452 | file=sys.stderr, |
| 453 | ) |
| 454 | return None |
| 455 | |
| 456 | tool = language_tool_python.LanguageTool(language) |
| 457 | try: |
| 458 | tool.disabled_rules.update(DISABLED_RULES) |
| 459 | except AttributeError: |
| 460 | # Older / non-standard build of the library — fall back silently; |
| 461 | # the in-script filter below will drop matches from disabled rules. |
| 462 | pass |
| 463 | disabled = set(DISABLED_RULES) |
| 464 | # language_tool_python's Match overrides __setattr__ to drop unknown keys, |
| 465 | # so we cannot stash the global offset on the match itself. Track the |
| 466 | # translation externally instead. |
| 467 | all_matches = [] |
| 468 | try: |
| 469 | for global_offset, chunk in chunk_text(text): |
| 470 | try: |
| 471 | matches = tool.check(chunk) |
| 472 | except Exception as exc: # noqa: BLE001 — advisory check must not crash CI |
| 473 | print( |
| 474 | f"LanguageTool failed on chunk at offset {global_offset} ({len(chunk)} bytes): {exc}", |
| 475 | file=sys.stderr, |
| 476 | ) |
| 477 | continue |
| 478 | for m in matches: |
| 479 | rule_id = _attr(m, "rule_id", "ruleId", default="") |
| 480 | if rule_id in disabled: |
| 481 | continue |
| 482 | flagged = _flagged_text(m) |
| 483 | local_off = _attr(m, "offset", default=0) |
| 484 | local_len = _attr(m, "error_length", "errorLength", default=0) |
| 485 | after = chunk[local_off + local_len:local_off + local_len + 64] |
| 486 | if is_accepted(flagged, accept_re, surrounding_after=after): |
| 487 | continue |
| 488 | all_matches.append((global_offset + m.offset, m)) |
| 489 | finally: |
| 490 | tool.close() |
| 491 | return all_matches |
| 492 | |
| 493 | |
| 494 | def _flagged_text(m): |
no test coverage detected