Return a ``cls`` Detection object from a pygmars.tree.Tree ``node`` with a space-normalized string value or None. Filter ``node`` Tokens with a type found in the ``ignored_labels`` set of ignorable token types. For copyright detection, include trailing "All rights reserved" if
(
node,
cls,
ignored_labels=frozenset(),
include_copyright_allrights=False,
refiner=None,
)
| 524 | |
| 525 | |
| 526 | def build_detection_from_node( |
| 527 | node, |
| 528 | cls, |
| 529 | ignored_labels=frozenset(), |
| 530 | include_copyright_allrights=False, |
| 531 | refiner=None, |
| 532 | ): |
| 533 | """ |
| 534 | Return a ``cls`` Detection object from a pygmars.tree.Tree ``node`` with a |
| 535 | space-normalized string value or None. |
| 536 | |
| 537 | Filter ``node`` Tokens with a type found in the ``ignored_labels`` set of ignorable |
| 538 | token types. |
| 539 | |
| 540 | For copyright detection, include trailing "All rights reserved" if |
| 541 | ``include_copyright_allrights`` is True. |
| 542 | |
| 543 | Apply the ``refiner`` callable function to the detection string. |
| 544 | """ |
| 545 | include_copyright_allrights = ( |
| 546 | cls == CopyrightDetection |
| 547 | and include_copyright_allrights |
| 548 | ) |
| 549 | |
| 550 | leaves = list(filter_tokens(node, ignored_labels=ignored_labels)) |
| 551 | |
| 552 | if include_copyright_allrights: |
| 553 | filtered = leaves |
| 554 | else: |
| 555 | filtered = [] |
| 556 | |
| 557 | for token in leaves: |
| 558 | # FIXME: this should operate on the tree and not on the leaves |
| 559 | # ALLRIGHTRESERVED: <NNP|NN|CAPS> <RIGHT> <NNP|NN|CAPS>? <RESERVED> |
| 560 | |
| 561 | # This pops ALL RIGHT RESERVED by finding it backwards from RESERVED |
| 562 | if token.label == 'RESERVED': |
| 563 | if ( |
| 564 | len(filtered) >= 2 |
| 565 | and filtered[-1].label == 'RIGHT' |
| 566 | and filtered[-2].label in ('NN', 'CAPS', 'NNP') |
| 567 | ): |
| 568 | filtered = filtered[:-2] |
| 569 | elif ( |
| 570 | len(filtered) >= 3 |
| 571 | and filtered[-1].label in ('NN', 'CAPS', 'NNP') |
| 572 | and filtered[-2].label == 'RIGHT' |
| 573 | and filtered[-3].label in ('NN', 'CAPS', 'NNP') |
| 574 | ): |
| 575 | filtered = filtered[:-3] |
| 576 | else: |
| 577 | filtered.append(token) |
| 578 | |
| 579 | node_string = ' '.join(t.value for t in filtered) |
| 580 | node_string = ' '.join(node_string.split()) |
| 581 | |
| 582 | if refiner: |
| 583 | node_string = refiner(node_string) |
no test coverage detected