Dataset Viewer
Duplicate
The dataset viewer is not available for this split.
Cannot load the dataset split (in streaming mode) to extract the first rows.
Error code:   StreamingRowsError
Exception:    CastError
Message:      Couldn't cast
digest: string
kind: string
path: string
payload_sha3: string
prev: string
seq: int64
ts: timestamp[s]
benchmarks: list<item: struct<evidence: struct<ceilings: struct<max_files: int64, max_lines: int64, min_lines: i (... 3044 chars omitted)
  child 0, item: struct<evidence: struct<ceilings: struct<max_files: int64, max_lines: int64, min_lines: int64>, code (... 3032 chars omitted)
      child 0, evidence: struct<ceilings: struct<max_files: int64, max_lines: int64, min_lines: int64>, code_lines: int64, co (... 2961 chars omitted)
          child 0, ceilings: struct<max_files: int64, max_lines: int64, min_lines: int64>
              child 0, max_files: int64
              child 1, max_lines: int64
              child 2, min_lines: int64
          child 1, code_lines: int64
          child 2, command: string
          child 3, counts_command: string
          child 4, files_source: int64
          child 5, files_tests: int64
          child 6, files_total: int64
          child 7, method: string
          child 8, test_to_source_line_ratio: double
          child 9, total_lines: int64
          child 10, a_licences: list<item: string>
              child 0, item: string
          child 11, b_licences: list<item: string>
              child 0, item: string
          child 12, default_for_unknown_is_C: bool
          child 13, mismatches: struct<>
          child 14, observed: struct<agpl3: string, apache2: string, bsd3: string, commons_clause: string, garbage: string, gpl3:  (...
...
       child 7, versioning: struct<detail: string, evidence_path: string, present: bool>
                  child 0, detail: string
                  child 1, evidence_path: string
                  child 2, present: bool
          child 62, criteria_missing: list<item: null>
              child 0, item: null
          child 63, criteria_satisfied: int64
          child 64, criteria_total: int64
          child 65, framework_controls_verified: int64
          child 66, ladder: string
          child 67, observed_level: int64
          child 68, source: string
          child 69, trL9_claimed: bool
          child 70, trL9_reason: string
      child 1, id: string
      child 2, ok: bool
      child 3, status: string
      child 4, title: string
passed: int64
failed: int64
sbom_written: bool
version: string
failed_ids: list<item: null>
  child 0, item: null
method: struct<aggregate_rule: string, excluded: string, reproduce: string, thresholds_note: string>
  child 0, aggregate_rule: string
  child 1, excluded: string
  child 2, reproduce: string
  child 3, thresholds_note: string
platform: string
python: string
source: struct<git: struct<head: string, url: string, branch: string, sha_verified_from: string>>
  child 0, git: struct<head: string, url: string, branch: string, sha_verified_from: string>
      child 0, head: string
      child 1, url: string
      child 2, branch: string
      child 3, sha_verified_from: string
all_passed: bool
root: string
total: int64
schema: string
to
{'all_passed': Value('bool'), 'benchmarks': List({'evidence': {'ceilings': {'max_files': Value('int64'), 'max_lines': Value('int64'), 'min_lines': Value('int64')}, 'code_lines': Value('int64'), 'command': Value('string'), 'counts_command': Value('string'), 'files_source': Value('int64'), 'files_tests': Value('int64'), 'files_total': Value('int64'), 'method': Value('string'), 'test_to_source_line_ratio': Value('float64'), 'total_lines': Value('int64'), 'a_licences': List(Value('string')), 'b_licences': List(Value('string')), 'default_for_unknown_is_C': Value('bool'), 'mismatches': {}, 'observed': {'agpl3': Value('string'), 'apache2': Value('string'), 'bsd3': Value('string'), 'commons_clause': Value('string'), 'garbage': Value('string'), 'gpl3': Value('string'), 'isc': Value('string'), 'lgpl': Value('string'), 'mit': Value('string'), 'mpl2': Value('string'), 'noncommercial': Value('string'), 'proprietary': Value('string'), 'sspl': Value('string'), 'unknown_absent': Value('string')}, 'only_class_A_may_relicense': Value('bool'), 'policy_probes': {'agpl3': Value('string'), 'apache2': Value('string'), 'bsd3': Value('string'), 'commons_clause': Value('string'), 'garbage': Value('string'), 'gpl3': Value('string'), 'isc': Value('string'), 'lgpl': Value('string'), 'mit': Value('string'), 'mpl2': Value('string'), 'noncommercial': Value('string'), 'proprietary': Value('string'), 'sspl': Value('string'), 'unknown_absent': Value('string')}, 'project_licence': {'LICENSE': Value('string'), '
...
Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'qualification_environment_pinned': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'reproducible_tests': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'rerunnable_verification': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'versioning': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}}, 'criteria_missing': List(Value('null')), 'criteria_satisfied': Value('int64'), 'criteria_total': Value('int64'), 'framework_controls_verified': Value('int64'), 'ladder': Value('string'), 'observed_level': Value('int64'), 'source': Value('string'), 'trL9_claimed': Value('bool'), 'trL9_reason': Value('string')}, 'id': Value('string'), 'ok': Value('bool'), 'status': Value('string'), 'title': Value('string')}), 'failed': Value('int64'), 'failed_ids': List(Value('null')), 'method': {'aggregate_rule': Value('string'), 'excluded': Value('string'), 'reproduce': Value('string'), 'thresholds_note': Value('string')}, 'passed': Value('int64'), 'platform': Value('string'), 'python': Value('string'), 'root': Value('string'), 'sbom_written': Value('bool'), 'schema': Value('string'), 'total': Value('int64'), 'version': Value('string'), 'source': {'git': {'head': Value('string'), 'url': Value('string'), 'branch': Value('string'), 'sha_verified_from': Value('string')}}}
because column names don't match
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/src/worker/utils.py", line 147, in get_rows_or_raise
                  return get_rows(
                      dataset=dataset,
                  ...<4 lines>...
                      column_names=column_names,
                  )
                File "/src/libs/libcommon/src/libcommon/utils.py", line 272, in decorator
                  return func(*args, **kwargs)
                File "/src/services/worker/src/worker/utils.py", line 127, in get_rows
                  rows_plus_one = list(itertools.islice(safe_iter(ds, dataset=dataset), rows_max_number + 1))
                File "/src/services/worker/src/worker/utils.py", line 483, in safe_iter
                  yield from ds.decode(False) if ds.features else ds
                File "/usr/local/lib/python3.14/site-packages/datasets/iterable_dataset.py", line 2951, in __iter__
                  for key, example in ex_iterable:
                                      ^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/iterable_dataset.py", line 2461, in __iter__
                  for key, pa_table in self._iter_arrow():
                                       ~~~~~~~~~~~~~~~~^^
                File "/usr/local/lib/python3.14/site-packages/datasets/iterable_dataset.py", line 2486, in _iter_arrow
                  for key, pa_table in self.ex_iterable._iter_arrow():
                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
                File "/usr/local/lib/python3.14/site-packages/datasets/iterable_dataset.py", line 547, in _iter_arrow
                  for key, pa_table in iterator:
                                       ^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/iterable_dataset.py", line 430, in _iter_arrow
                  for key, pa_table in self.generate_tables_fn(**gen_kwags):
                                       ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 343, in _generate_tables
                  self._cast_table(pa_table, json_field_paths=json_field_paths),
                  ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 132, in _cast_table
                  pa_table = table_cast(pa_table, self.info.features.arrow_schema)
                File "/usr/local/lib/python3.14/site-packages/datasets/table.py", line 2378, in table_cast
                  return cast_table_to_schema(table, schema)
                File "/usr/local/lib/python3.14/site-packages/datasets/table.py", line 2306, in cast_table_to_schema
                  raise CastError(
                  ...<3 lines>...
                  )
              datasets.table.CastError: Couldn't cast
              digest: string
              kind: string
              path: string
              payload_sha3: string
              prev: string
              seq: int64
              ts: timestamp[s]
              benchmarks: list<item: struct<evidence: struct<ceilings: struct<max_files: int64, max_lines: int64, min_lines: i (... 3044 chars omitted)
                child 0, item: struct<evidence: struct<ceilings: struct<max_files: int64, max_lines: int64, min_lines: int64>, code (... 3032 chars omitted)
                    child 0, evidence: struct<ceilings: struct<max_files: int64, max_lines: int64, min_lines: int64>, code_lines: int64, co (... 2961 chars omitted)
                        child 0, ceilings: struct<max_files: int64, max_lines: int64, min_lines: int64>
                            child 0, max_files: int64
                            child 1, max_lines: int64
                            child 2, min_lines: int64
                        child 1, code_lines: int64
                        child 2, command: string
                        child 3, counts_command: string
                        child 4, files_source: int64
                        child 5, files_tests: int64
                        child 6, files_total: int64
                        child 7, method: string
                        child 8, test_to_source_line_ratio: double
                        child 9, total_lines: int64
                        child 10, a_licences: list<item: string>
                            child 0, item: string
                        child 11, b_licences: list<item: string>
                            child 0, item: string
                        child 12, default_for_unknown_is_C: bool
                        child 13, mismatches: struct<>
                        child 14, observed: struct<agpl3: string, apache2: string, bsd3: string, commons_clause: string, garbage: string, gpl3:  (...
              ...
                     child 7, versioning: struct<detail: string, evidence_path: string, present: bool>
                                child 0, detail: string
                                child 1, evidence_path: string
                                child 2, present: bool
                        child 62, criteria_missing: list<item: null>
                            child 0, item: null
                        child 63, criteria_satisfied: int64
                        child 64, criteria_total: int64
                        child 65, framework_controls_verified: int64
                        child 66, ladder: string
                        child 67, observed_level: int64
                        child 68, source: string
                        child 69, trL9_claimed: bool
                        child 70, trL9_reason: string
                    child 1, id: string
                    child 2, ok: bool
                    child 3, status: string
                    child 4, title: string
              passed: int64
              failed: int64
              sbom_written: bool
              version: string
              failed_ids: list<item: null>
                child 0, item: null
              method: struct<aggregate_rule: string, excluded: string, reproduce: string, thresholds_note: string>
                child 0, aggregate_rule: string
                child 1, excluded: string
                child 2, reproduce: string
                child 3, thresholds_note: string
              platform: string
              python: string
              source: struct<git: struct<head: string, url: string, branch: string, sha_verified_from: string>>
                child 0, git: struct<head: string, url: string, branch: string, sha_verified_from: string>
                    child 0, head: string
                    child 1, url: string
                    child 2, branch: string
                    child 3, sha_verified_from: string
              all_passed: bool
              root: string
              total: int64
              schema: string
              to
              {'all_passed': Value('bool'), 'benchmarks': List({'evidence': {'ceilings': {'max_files': Value('int64'), 'max_lines': Value('int64'), 'min_lines': Value('int64')}, 'code_lines': Value('int64'), 'command': Value('string'), 'counts_command': Value('string'), 'files_source': Value('int64'), 'files_tests': Value('int64'), 'files_total': Value('int64'), 'method': Value('string'), 'test_to_source_line_ratio': Value('float64'), 'total_lines': Value('int64'), 'a_licences': List(Value('string')), 'b_licences': List(Value('string')), 'default_for_unknown_is_C': Value('bool'), 'mismatches': {}, 'observed': {'agpl3': Value('string'), 'apache2': Value('string'), 'bsd3': Value('string'), 'commons_clause': Value('string'), 'garbage': Value('string'), 'gpl3': Value('string'), 'isc': Value('string'), 'lgpl': Value('string'), 'mit': Value('string'), 'mpl2': Value('string'), 'noncommercial': Value('string'), 'proprietary': Value('string'), 'sspl': Value('string'), 'unknown_absent': Value('string')}, 'only_class_A_may_relicense': Value('bool'), 'policy_probes': {'agpl3': Value('string'), 'apache2': Value('string'), 'bsd3': Value('string'), 'commons_clause': Value('string'), 'garbage': Value('string'), 'gpl3': Value('string'), 'isc': Value('string'), 'lgpl': Value('string'), 'mit': Value('string'), 'mpl2': Value('string'), 'noncommercial': Value('string'), 'proprietary': Value('string'), 'sspl': Value('string'), 'unknown_absent': Value('string')}, 'project_licence': {'LICENSE': Value('string'), '
              ...
              Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'qualification_environment_pinned': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'reproducible_tests': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'rerunnable_verification': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}, 'versioning': {'detail': Value('string'), 'evidence_path': Value('string'), 'present': Value('bool')}}, 'criteria_missing': List(Value('null')), 'criteria_satisfied': Value('int64'), 'criteria_total': Value('int64'), 'framework_controls_verified': Value('int64'), 'ladder': Value('string'), 'observed_level': Value('int64'), 'source': Value('string'), 'trL9_claimed': Value('bool'), 'trL9_reason': Value('string')}, 'id': Value('string'), 'ok': Value('bool'), 'status': Value('string'), 'title': Value('string')}), 'failed': Value('int64'), 'failed_ids': List(Value('null')), 'method': {'aggregate_rule': Value('string'), 'excluded': Value('string'), 'reproduce': Value('string'), 'thresholds_note': Value('string')}, 'passed': Value('int64'), 'platform': Value('string'), 'python': Value('string'), 'root': Value('string'), 'sbom_written': Value('bool'), 'schema': Value('string'), 'total': Value('int64'), 'version': Value('string'), 'source': {'git': {'head': Value('string'), 'url': Value('string'), 'branch': Value('string'), 'sha_verified_from': Value('string')}}}
              because column names don't match

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

EXTRACTION

license offline-first audit category

Anticloud-hardened packaging of the upstream project EXTRACTION in category PHILOSOPHY SEMANTICS. Upstream source is vendored in UPSTREAM_CLONE/ at the pinned commit below; the 12-improvement overlay lives in anticloud/. Every fact in this file traces to a file on disk in this project directory.

Category: PHILOSOPHY SEMANTICS · Upstream: https://github.com/lethain/extraction · Upstream pin: 65febdc6d462c1840b9a67ac6a1bb0f29e9e37e8 · Vendor: Anticloud FZ LLE


What This Project Does

========== Extraction

Extraction is a Python package for extracting titles, descriptions, images and canonical urls from web pages. You might want to use Extraction if you're building a link aggregator where users submit links and you want to display them (like submitting a link to Facebook, Digg or Delicious).

Extraction is not a web crawling or content retrieval mechanism, rather it is a tool to use on data which has always been retrieved or crawled by a different tool.

Updated to work with Python3. See the last Python 2.x compatible version here <https://github.com/lethain/extraction/tree/c96afe2a9fd6a6d1fc1ad8eb793b43e2b9c1484c>_.

See on Github <https://github.com/lethain/extraction>, or on PyPi <http://pypi.python.org/pypi/extraction/0.1.0>.

Hello World Usage

An extremely simple example of using extraction is::

>>> import extraction
>>> import requests
>>> url = "http://lethain.com/social-hierarchies-in-engineering-organizations/"
>>> html = requests.get(url).text
>>> extracted = extraction.Extractor().extract(html, source_url=url)
>>> extracted.title
>>> "Social Hierarchies in Engineering Organizations - Irrational Exuberance"
>>> print extracted.title, extracted.description, extracted.image, extracted.url
>>> print extracted.titles, extracted.descriptions, extracted.images, extracted.urls

Note that source_url is optional in extract, but is recommended as it makes it possible to rewrite relative urls and image urls into absolute paths. source_url is not used for fetching data, but can be used for targetting extraction techniques to the correct domain.

More details usage examples, including how to add your own extraction mechanisms, are beneath the installation section.

Installation

The simplest way to install Extraction is via PyPi::

pip install extraction

You'll also have to install a parser for BeautifulSoup4 <http://www.crummy.com/software/BeautifulSoup/>, and while extraction already pulls down html5lib <http://code.google.com/p/html5lib/> through it's requirements, I really recommend installing lxml <http://lxml.de/>_ as well, because there are some extremely gnarly issues with html5lib failing to parse XHTML pages (for example, PyPi fails to parse entirely with html5lib::

>>> bs4.BeautifulSoup(text, ["html5lib"]).find_all("title")
[]
>>> bs4.BeautifulSoup(text, ["lxml"]).find_all("title")
[<title>extraction 0.1.3 : Python Package Index</title>]

You should be able to install lxml <http://lxml.de/>_ via pip::

pip install lxml

If you want to develop extraction, then after installing lxml, you can install from GitHub::

git source
cd extraction
python3 -m venv env    
. ./env/bin/activate
pip install -r requirements.txt
pip install -e .

Then you can run the tests::

python tests/tests.py

All of which should pass in a sane installation.

Using Extraction

This section covers various ways to use extraction, both using the existing extraction techniques as well as add your own.

For more examples, please look in the extraction/examples directory.

Basic Usage

The simplest possible example is the "Hello World" example from above::

>>> import extraction
>>> import requests
>>> url = "http://lethain.com/social-hierarchies-in-engineering-organizations/"
>>> html = requests.get(url).text
>>> extracted = extraction.Extractor().extract(html, source_url=url)
>>> extracted.title
>>> "Social Hierarchies in Engineering Organizations - Irrational Exuberance"
>>> print extracted.title, extracted.description, extracted.image, extracted.url

You can get the best title, description and such out of an Extracted instance (which are returned by Extractor.extract) by::

>>> print extracted.title
>>> print extracted.description
>>> print extracted.url
>>> print extracted.image
>>> print extracted.feed

You can get the full list of extracted values using the plural versions::

>>> print extracted.titles
>>> print extracted.descriptions
>>> print extracted.urls
>>> print extracted.images
>>> print extracted.feeds

If you're looking for data which is being extracted but doesn't fall into one of those categories (perhaps using a custom technique), then take a look at the Extracted._unexpected_values dictionary::

>>> print extracted._unexpected_values

Any type of metadata which isn't anticipated is stored there (look at Subclassing Extracted to Extract New Types of Data if this is something you're running into frequently).

Using Custom Techniques and Changing Technique Ordering

The order techniques are run in is significant, and the most accurate techniques should always run first, and more general, lower quality techniques later on.

This is because titles, descriptions, images and urls are stored internally in a list, which is built up as techniques are run, and the title, url, image and description properties simply return the first item from the corresponding list.

Techniques are represented by a string with the full path to the technique, including its class. For example "extraction.technique.FacebookOpengraphTags" is a valid representation of a technique.

The default ordering of techniques is within the extraction.Extractor's techniques class variable, and is::

extraction.techniques.FacebookOpengraphTags
extraction.techniques.TwitterSummaryCardTags
extraction.techniques.HTML5SemanticTags
extraction.techniques.HeadTags
extraction.techniques.SemanticTags

You can modify the order and inclusion of techniques in three ways. First, you can modify it by passing in a list of techniques to the optional techniques parameter when initializing an extraction.Extractor::

>>> techniques = ["my_module.MyTechnique", "ext

(excerpt; full text in UPSTREAM_CLONE/)

Quoted from the upstream README.rst file in UPSTREAM_CLONE/. Project-specific facts detected in this directory:

  • Ecosystem: Python (manifests: setup.py, requirements.txt; scanned in UPSTREAM_CLONE)
  • Top-level source layout: extraction/
  • Snapshot size: 15 files, 979 lines of code (measured; see Benchmarks)
  • Primary languages: .py (9), .txt (3), (none) (1), .in (1), .rst (1)
  • Upstream commit pinned for this packaging: 65febdc6d462c1840b9a67ac6a1bb0f29e9e37e8

Installation

want to display them (like submitting a link to Facebook, Digg or Delicious).

Extraction is not a web crawling or content retrieval mechanism, rather it is a tool to use on data which has always been retrieved or crawled by a different tool.

Updated to work with Python3. See the last Python 2.x compatible version here <https://github.com/lethain/extraction/tree/c96afe2a9fd6a6d1fc1ad8eb793b43e2b9c1484c>_.

See on Github <https://github.com/lethain/extraction>, or on PyPi <http://pypi.python.org/pypi/extraction/0.1.0>.

Hello World Usage

An extremely simple example of using extraction is::

>>> import extraction
>>> import requests
>>> url = "http://lethain.com/social-hierarchies-in-engineering-organizations/"
>>> html = requests.get(url).text
>>> extracted = extraction.Extractor().extract(html, source_url=url)
>>> extracted.title
>>> "Social Hierarchies in Engineering Organizations - Irrational Exuberance"
>>> print extracted.title, extracted.description, extracted.image, extracted.url
>>> print extracted.titles, extracted.descriptions, extracted.images, extracted.urls

Note that source_url is optional in extract, but is recommended as it makes it possible to rewrite relative urls and image urls into absolute paths. source_url is not used for fetching data, but can be used for targetting extraction techniques to the correct domain.

More details usage examples, including how to add your own extraction mechanisms, are beneath the installation section.

Installation

The simplest way to install Extraction is via PyPi::

pip install extraction

You'll also have to install a parser for BeautifulSoup4 <http://www.crummy.com/software/BeautifulSoup/>, and while extraction already pulls down html5lib <http://code.google.com/p/html5lib/> through it's requirements, I really recommend installing lxml <http://lxml.de/>_ as well, because there are some extremely gnarly issues with html5lib failing to parse XHTML pages (for example, PyPi fails to parse entirely with html5lib::

>>> bs4.BeautifulSoup(text, ["html5lib"]).find_all("title")
[]
>>> bs4.BeautifulSoup(text, ["lxml"]).find_all("title")
[<title>extraction 0.1.3 : Python Package Index</title>]

You should be able to install lxml <http://lxml.de/>_ via pip::

pip install lxml

If you want to develop extraction, then after installing lxml, you can install from GitHub::

git source
cd extraction
python3 -m venv env    
. ./env/bin/activate
pip install -r requirements.txt
pip install -e .

Then you can run the tests::

python tests/tests.py

All of which should pass in a sane installation.

Using Extraction

This section covers various ways to use extraction, both using the existing extraction techniques as well as add your own.

For more examples, please look in the extraction/examples directory.

Basic Usage

The simplest possible example is the "Hello World" example from above::

>>> import extraction
>>> import requests
>>> url = "http://lethain.com/social-hierarchies-in-engineering-organizations/"
>>> html = requests.get(url).text
>>> extracted = extraction.Extractor().extract(html, source_url=url)
>>> extracted.title
>>> "Social Hierarchies in Engineering Organizations - Irrational Exuberance"
>>> print extracted.title, extracted.description, extracted.image, extracted.url

You can get the best title, description and such out of an Extracted instance (which are returned by Extractor.extract) by::

>>> print extracted.title
>>> print extracted.description
>>> print extracted.url
>>> print extracted.image
>>> print extracted.feed

You can get the full list of extracted values using the plural versions::

>>> print extracted.titles
>>> print extracted.descriptions
>>> print extracted.urls
>>> print extracted.images
>>> print extracted.feeds

If you're looking for data which is being extracted but doesn't fall into one of those categories (perhaps using a custom technique), then take a look at the Extracted._unexpected_values dictionary::

>>> print extracted._unexpected_values

Any type of metadata which isn't anticipated is stored there (look at Subclassing Extracted to Extract New Types of Data if this is something you're running into frequently).

Using Custom Techniques and Changing Technique Ordering

The order techniques are run in is significant, and the most accurate techniques should always run first, and more general, lower quality techniques later on.

This is because titles, descriptions, images and urls are stored internally in a list, which is built up as techniques are run, and the title, url, image and description properties simply return the first item from the corresponding list.

Techniques are represented by a string with the full path to the technique, including its class. For example "extraction.technique.FacebookOpengraphTags" is a valid representation of a technique.

The default ordering of techniques is within the extraction.Extractor's techniques class variable, and is::

extraction.techniques.FacebookOpengraphTags
extraction.techniques.TwitterSummaryCardTags
extraction.techniques.HTML5SemanticTags
extraction.techniques.HeadTags
extraction.techniques.SemanticTags

You can modify the order and inclusion of techniques in three ways. First, you can modify it by passing in a list of techniques to the optional techniques parameter when initializing an extraction.Extractor::

>>> techniques = ["my_module.MyTechnique", "extraction.techniques.FacebookOpengraphTags"]
>>> extractor = extraction.Extractor(techniques=techniques)

The second approach is to subclass Extractor with a different value of techniques::

from extraction import Extractor

class MyExtractor(Extractor):
    techniques = ["my_module.MyTechnique"]

Finally, the third option is to directly modify the techniques class variable. This is probably the most unpredictable technique, as it's possible for mutiple pieces of code to perform this modification and to create havoc, if possible use one of the previous two techniques to avoid future debugging::

>>> import extraction
>>> extraction.Extractor.techniques.insert(0, "my_module.MyAwesomeTechnique")
>>> extraction.Extractor.techniques.append("my_module.MyLastReportTechnique")

Again, please try the first two techniques instead if you value sanity.

Writing New Technique

It may be that you're frequently parsing a given website and aren't impressed with how the default extraction techniques are performing. In that case, consider writng your own technique.

Let's take for example a blog entry at lethain.com <http://lethain.com/social-hierarchies-in-engineering-organizations/>_, which uses the H1 tag to represent the overall blogs title, and always uses the first H2 tag in DIV.page for its actual title.

A technique to properly extract this data would look like::

from extraction.techniques import Technique
from bs4 import BeautifulSoup
class LethainComTechnique(Technique):
    def extract(self, html):
        "Extract data from lethain.com."
        soup = BeautifulSoup(html)
        page_div = soup.find('div', class_='page')
        text_div = soup.find('div', class_='text')
        return { 'titles': [page_div.find('h2').string],
                 'dates': [page_div.find('span', class_='date').string],
                 'descriptions': [" ".join(text_div.find('p').strings)],
                 'tags': [x.find('a').string for x in page_div.find_all('span', class_='tag')],
                 'images': [x.attrs['src'] for x in text_div.find_all('img')],
                 }

To integrate your technique, take a look at the Using Custom Techniques and Changing Technique Ordering section above.

Adding new techniques incorporating microformats is an interesting area for some consideration. Most microformats have very limited usage, but where they are in use they tend to be high quality sources of information.

Subclassing Extracted to Extract New Types of Data

Your techniques can return non-standard keys in the dictionary returned by extract, which will be available in the Extracted()._unexpected_values dictionary. In this way you could fairly easily add support for extracting addresses or whatnot.

For a contrived example, we'll extract my address from willarson.com <http://willarson.com/>_, which is in no way a realistic example of extracting an address, and is only meant as an example of how to add a new type of extracted data.

As such, to add support for extracting address should look like (a fuller, commented version of this example is available in extraction/examples/new_return_type.py, I've written this as concisely as possible to fit into this doc more cleanly)::

from extraction.techniques import Technique
from extraction import Extractor, Extracted
from bs4 import BeautifulSoup

class AddressExtracted(Extracted):
    def __init__(self, addresses=None, *args, **kwargs):
        self.addresses = addresses or []
        super(AddressExtracted, self).__init__(*args, **kwargs)

    @property
    def address(self):
        return self.addresses[0] if self.addresses else None

class AddressExtractor(Extractor):
    "Extractor which supports addresses as first-class data."
    extracted_class = AddressExtracted
    text_types = ["titles", "descriptions", "addresses"]

class AddressTechnique(Technique):
    def extract(self, html):
        "Extract address data from willarson.com."
        soup = BeautifulSoup(html)
        return {'addresses': [" ".join(soup.find('div', id='address').strings)]}

Usage would then look like::

>>> import requests
>>> from extraction.examples.new_return_type import AddressExtractor
>>> extractor = AddressExtractor()
>>> extractor.techniques = ["extraction.examples.new_return_type.AddressTechnique"]
>>> extracted = extractor.extract(requests.get("http://willarson.com/"))
>>> extracted.address
"Cole Valey San Francisco, CA USA"

There you have it, extracted addresses as first class extracted data.

Passing Parameters to Techniques

There isn't a mechanism for passing parameters to Techniques when they are initialized, but it is possible to customize the behavior of Techniques in a couple of ways.

First, you can simply subclass the Technique with the specific behavior you want, perhaps pulling the data from Django settings or what not::

class MyTechnique(Technique):
    def __init__(self, *args, **kwargs):
        if 'something' in kwargs:
            self.something = kwargs['something']
        del kwargs['something']
        else:
            self.something = "something else"
        return super(MyTechnique, self).__init__(*args, **kwargs)

    def extract(html, source_url=None):
        print self.something
        return super(MyTechnique, self).extract(html, source_url=source_url)

Second, all techniques are passed in the Extractor being used to process them, so you can bake the customization into an extraction.Extractor subclass::

from extraction import Extractor
from extraction.techniques import Technique

class MyExtractor(Extractor):
    techniques = ["my_module.MyTechnique"]
    def __init__(self, something, *args, **kwargs):
        self.something = something
        super(MyExtractor, self).__init__(*args, **kwargs)

class MyTechnique(Technique):
    class extract(self, html, source_url=None):
        print self.extractor.something
        return super(MyTechnique, self).extract(html, source_url=source_url)

Between these two techniques, it should be feasible to get the customization of behavior you need.

Extraction Techniques

This section lists the current techniques used by extraction. To rerank the techniques, remove techniques or add new techniques of your own, look at the Using Extraction section below.

extraction.techniques.HeadTags

Every webpage's head tag contains has a title tag, and many also include additional data like descriptions, RSS feeds and such. This technique parses data that looks like::

<head>
    <meta name="description" content="Will Larson&#39;s blog about programming and other things." />
    <link rel="alternate" type="application/rss+xml" title="Page Feed" href="/feeds/" />
    <link rel="canonical" href="http://lethain.com/digg-v4-architecture-process/">
    <title>Digg v4&#39;s Architecture and Development Processes - Irrational Exuberance</title>
</head>

While the head tag is authoritative source of canonical URLs and RSS, it's often very hit or miss for titles, descriptions and such. At worst, it's better than nothing.

extraction.techniques.FacebookOpengraphTags

For better or for worse, the highest quality source of page data is usually the Facebook Opengraph meta tags <https://developers.facebook.com/docs/opengraphprotocol/>_. This technique uses Opengraph tags, which look like this::

<head>
    ...
    <meta property="og:title" content="Something"/>
    <meta property="og:url" content="http://www.example.org/something//"/>
    <meta property="og:image" content="http://images.example.org/a/"/>
    <meta property="og:description" content="Something amazing."/>
    ...
</head>

as their source of data.

extraction.techniques.TwitterSummaryCardTags

Another, increasingly common set of meta tags is the Twitter Card tags <https://dev.twitter.com/docs/cards/types/summary-card>_. This technique parses those tags, which look like::

<head>
    ...
    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@nytimes">
    <meta name="twitter:creator" content="@SarahMaslinNir">
    <meta name="twitter:title" content="Parade of Fans for Houston’s Funeral">
    <meta name="twitter:description" content="NEWARK - The guest list and parade...">
    <meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-article.jpg">
    ...
</head>

For sites with cards integration (which many high quality sites have, because it's necessary for rendering with images in the Twitter feed), this will be a very high quality source of data.

One oddity is that Twitter cards don't include a URL tag, so they don't help much with canonicalizing articles.

extraction.techniques.HTML5SemanticTags

The HTML5 article tag, and also the video tag give us some useful hints for extracting page information for the sites which happen to utilize these tags.

This technique will extract information from pages formed like::

<html>
  <body>
    <h1>This is not a title to HTML5SemanticTags</h1>
    <article>
      <h1>This is a title</h1>
      <p>This is a description.</p>
      <p>This is not a description.</p>
    </article>
    <video>
      <source src="this_is_a_video.mp4">
    </video>
  </body>
</html>

Note that HTML5SemanticTags is intentionally much more conservative than SemanticTags, as it provides high quality information in the small number of cases where it hits, and otherwise expects SemanticTags to run sweep behind it for the lower quality, more abundant hits it discovers.

extraction.techniques.SemanticTags

This technique relies on the basic tags themselves--for example, all img tags include images, most h1 and h2 tags include titles, and p tags often include text usable as descriptions::

<html>
  <body>
    <h1>This will be extracted as a title.</h1>
    <h2>So will this, but after all H1s.</h2>
    <img src="/datasets/Anticloud/anticloud-extraction/resolve/main/this_will_be_extracted_as_an_img.png">
    <p>And this as a description.</p>
    <p>This as another possible description.</p>
    <p>This as a third possible description.</p>
  </body>
</html>

There is a limit, defined within SemanticTags of how many tags of a given type will be consumed, and is usually 3-5, with the exception of images, where it is 10 (as this is actually a valid way to detect images, unlike the others).

This is a true last resort technique.

Implementation Details

I've tried to comment the classes and modules themselves in a fairly indepth fashion, and would recommend reading them for the most details, the recommended reading order is::

extraction/tests.py
extraction/__init__.py
extraction/techniques.py

Hopefully all questions are answered therein.

Contributions, Questions, Concerns

Please open a GitHub pull-request with any improvements, preferably with tests, and I'll be glad to merge it in.

Section quoted from the upstream readme. Overlay install (this project):

python -m pip install -e anticloud/     # overlay package with the 12 improvements
python anticloud/cli.py --help          # 13 subcommands, JSON stdout

Usage

if you're building a link aggregator where users submit links and you want to display them (like submitting a link to Facebook, Digg or Delicious).

Extraction is not a web crawling or content retrieval mechanism, rather it is a tool to use on data which has always been retrieved or crawled by a different tool.

Updated to work with Python3. See the last Python 2.x compatible version here <https://github.com/lethain/extraction/tree/c96afe2a9fd6a6d1fc1ad8eb793b43e2b9c1484c>_.

See on Github <https://github.com/lethain/extraction>, or on PyPi <http://pypi.python.org/pypi/extraction/0.1.0>.

Hello World Usage

An extremely simple example of using extraction is::

>>> import extraction
>>> import requests
>>> url = "http://lethain.com/social-hierarchies-in-engineering-organizations/"
>>> html = requests.get(url).text
>>> extracted = extraction.Extractor().extract(html, source_url=url)
>>> extracted.title
>>> "Social Hierarchies in Engineering Organizations - Irrational Exuberance"
>>> print extracted.title, extracted.description, extracted.image, extracted.url
>>> print extracted.titles, extracted.descriptions, extracted.images, extracted.urls

Note that source_url is optional in extract, but is recommended as it makes it possible to rewrite relative urls and image urls into absolute paths. source_url is not used for fetching data, but can be used for targetting extraction techniques to the correct domain.

More details usage examples, including how to add your own extraction mechanisms, are beneath the installation section.

Installation

The simplest way to install Extraction is via PyPi::

pip install extraction

You'll also have to install a parser for BeautifulSoup4 <http://www.crummy.com/software/BeautifulSoup/>, and while extraction already pulls down html5lib <http://code.google.com/p/html5lib/> through it's requirements, I really recommend installing lxml <http://lxml.de/>_ as well, because there are some extremely gnarly issues with html5lib failing to parse XHTML pages (for example, PyPi fails to parse entirely with html5lib::

>>> bs4.BeautifulSoup(text, ["html5lib"]).find_all("title")
[]
>>> bs4.BeautifulSoup(text, ["lxml"]).find_all("title")
[<title>extraction 0.1.3 : Python Package Index</title>]

You should be able to install lxml <http://lxml.de/>_ via pip::

pip install lxml

If you want to develop extraction, then after installing lxml, you can install from GitHub::

git source
cd extraction
python3 -m venv env    
. ./env/bin/activate
pip install -r requirements.txt
pip install -e .

Then you can run the tests::

python tests/tests.py

All of which should pass in a sane installation.

Using Extraction

This section covers various ways to use extraction, both using the existing extraction techniques as well as add your own.

For more examples, please look in the extraction/examples directory.

Basic Usage

The simplest possible example is the "Hello World" example from above::

>>> import extraction
>>> import requests
>>> url = "http://lethain.com/social-hierarchies-in-engineering-organizations/"
>>> html = requests.get(url).text
>>> extracted = extraction.Extractor().extract(html, source_url=url)
>>> extracted.title
>>> "Social Hierarchies in Engineering Organizations - Irrational Exuberance"
>>> print extracted.title, extracted.description, extracted.image, extracted.url

You can get the best title, description and such out of an Extracted instance (which are returned by Extractor.extract) by::

>>> print extracted.title
>>> print extracted.description
>>> print extracted.url
>>> print extracted.image
>>> print extracted.feed

You can get the full list of extracted values using the plural versions::

>>> print extracted.titles
>>> print extracted.descriptions
>>> print extracted.urls
>>> print extracted.images
>>> print extracted.feeds

If you're looking for data which is being extracted but doesn't fall into one of those categories (perhaps using a custom technique), then take a look at the Extracted._unexpected_values dictionary::

>>> print extracted._unexpected_values

Any type of metadata which isn't anticipated is stored there (look at Subclassing Extracted to Extract New Types of Data if this is something you're running into frequently).

Using Custom Techniques and Changing Technique Ordering

The order techniques are run in is significant, and the most accurate techniques should always run first, and more general, lower quality techniques later on.

This is because titles, descriptions, images and urls are stored internally in a list, which is built up as techniques are run, and the title, url, image and description properties simply return the first item from the corresponding list.

Techniques are represented by a string with the full path to the technique, including its class. For example "extraction.technique.FacebookOpengraphTags" is a valid representation of a technique.

The default ordering of techniques is within the extraction.Extractor's techniques class variable, and is::

extraction.techniques.FacebookOpengraphTags
extraction.techniques.TwitterSummaryCardTags
extraction.techniques.HTML5SemanticTags
extraction.techniques.HeadTags
extraction.techniques.SemanticTags

You can modify the order and inclusion of techniques in three ways. First, you can modify it by passing in a list of techniques to the optional techniques parameter when initializing an extraction.Extractor::

>>> techniques = ["my_module.MyTechnique", "extraction.techniques.FacebookOpengraphTags"]
>>> extractor = extraction.Extractor(techniques=techniques)

The second approach is to subclass Extractor with a different value of techniques::

from extraction import Extractor

class MyExtractor(Extractor):
    techniques = ["my_module.MyTechnique"]

Finally, the third option is to directly modify the techniques class variable. This is probably the most unpredictable technique, as it's possible for mutiple pieces of code to perform this modification and to create havoc, if possible use one of the previous two techniques to avoid future debugging::

>>> import extraction
>>> extraction.Extractor.techniques.insert(0, "my_module.MyAwesomeTechnique")
>>> extraction.Extractor.techniques.append("my_module.MyLastReportTechnique")

Again, please try the first two techniques instead if you value sanity.

Writing New Technique

It may be that you're frequently parsing a given website and aren't impressed with how the default extraction techniques are performing. In that case, consider writng your own technique.

Let's take for example a blog entry at lethain.com <http://lethain.com/social-hierarchies-in-engineering-organizations/>_, which uses the H1 tag to represent the overall blogs title, and always uses the first H2 tag in DIV.page for its actual title.

A technique to properly extract this data would look like::

from extraction.techniques import Technique
from bs4 import BeautifulSoup
class LethainComTechnique(Technique):
    def extract(self, html):
        "Extract data from lethain.com."
        soup = BeautifulSoup(html)
        page_div = soup.find('div', class_='page')
        text_div = soup.find('div', class_='text')
        return { 'titles': [page_div.find('h2').string],
                 'dates': [page_div.find('span', class_='date').string],
                 'descriptions': [" ".join(text_div.find('p').strings)],
                 'tags': [x.find('a').string for x in page_div.find_all('span', class_='tag')],
                 'images': [x.attrs['src'] for x in text_div.find_all('img')],
                 }

To integrate your technique, take a look at the Using Custom Techniques and Changing Technique Ordering section above.

Adding new techniques incorporating microformats is an interesting area for some consideration. Most microformats have very limited usage, but where they are in use they tend to be high quality sources of information.

Subclassing Extracted to Extract New Types of Data

Your techniques can return non-standard keys in the dictionary returned by extract, which will be available in the Extracted()._unexpected_values dictionary. In this way you could fairly easily add support for extracting addresses or whatnot.

For a contrived example, we'll extract my address from willarson.com <http://willarson.com/>_, which is in no way a realistic example of extracting an address, and is only meant as an example of how to add a new type of extracted data.

As such, to add support for extracting address should look like (a fuller, commented version of this example is available in extraction/examples/new_return_type.py, I've written this as concisely as possible to fit into this doc more cleanly)::

from extraction.techniques import Technique
from extraction import Extractor, Extracted
from bs4 import BeautifulSoup

class AddressExtracted(Extracted):
    def __init__(self, addresses=None, *args, **kwargs):
        self.addresses = addresses or []
        super(AddressExtracted, self).__init__(*args, **kwargs)

    @property
    def address(self):
        return self.addresses[0] if self.addresses else None

class AddressExtractor(Extractor):
    "Extractor which supports addresses as first-class data."
    extracted_class = AddressExtracted
    text_types = ["titles", "descriptions", "addresses"]

class AddressTechnique(Technique):
    def extract(self, html):
        "Extract address data from willarson.com."
        soup = BeautifulSoup(html)
        return {'addresses': [" ".join(soup.find('div', id='address').strings)]}

Usage would then look like::

>>> import requests
>>> from extraction.examples.new_return_type import AddressExtractor
>>> extractor = AddressExtractor()
>>> extractor.techniques = ["extraction.examples.new_return_type.AddressTechnique"]
>>> extracted = extractor.extract(requests.get("http://willarson.com/"))
>>> extracted.address
"Cole Valey San Francisco, CA USA"

There you have it, extracted addresses as first class extracted data.

Passing Parameters to Techniques

There isn't a mechanism for passing parameters to Techniques when they are initialized, but it is possible to customize the behavior of Techniques in a couple of ways.

First, you can simply subclass the Technique with the specific behavior you want, perhaps pulling the data from Django settings or what not::

class MyTechnique(Technique):
    def __init__(self, *args, **kwargs):
        if 'something' in kwargs:
            self.something = kwargs['something']
        del kwargs['something']
        else:
            self.something = "something else"
        return super(MyTechnique, self).__init__(*args, **kwargs)

    def extract(html, source_url=None):
        print self.something
        return super(MyTechnique, self).extract(html, source_url=source_url)

Second, all techniques are passed in the Extractor being used to process them, so you can bake the customization into an extraction.Extractor subclass::

from extraction import Extractor
from extraction.techniques import Technique

class MyExtractor(Extractor):
    techniques = ["my_module.MyTechnique"]
    def __init__(self, something, *args, **kwargs):
        self.something = something
        super(MyExtractor, self).__init__(*args, **kwargs)

class MyTechnique(Technique):
    class extract(self, html, source_url=None):
        print self.extractor.something
        return super(MyTechnique, self).extract(html, source_url=source_url)

Between these two techniques, it should be feasible to get the customization of behavior you need.

Extraction Techniques

This section lists the current techniques used by extraction. To rerank the techniques, remove techniques or add new techniques of your own, look at the Using Extraction section below.

extraction.techniques.HeadTags

Every webpage's head tag contains has a title tag, and many also include additional data like descriptions, RSS feeds and such. This technique parses data that looks like::

<head>
    <meta name="description" content="Will Larson&#39;s blog about programming and other things." />
    <link rel="alternate" type="application/rss+xml" title="Page Feed" href="/feeds/" />
    <link rel="canonical" href="http://lethain.com/digg-v4-architecture-process/">
    <title>Digg v4&#39;s Architecture and Development Processes - Irrational Exuberance</title>
</head>

While the head tag is authoritative source of canonical URLs and RSS, it's often very hit or miss for titles, descriptions and such. At worst, it's better than nothing.

extraction.techniques.FacebookOpengraphTags

For better or for worse, the highest quality source of page data is usually the Facebook Opengraph meta tags <https://developers.facebook.com/docs/opengraphprotocol/>_. This technique uses Opengraph tags, which look like this::

<head>
    ...
    <meta property="og:title" content="Something"/>
    <meta property="og:url" content="http://www.example.org/something//"/>
    <meta property="og:image" content="http://images.example.org/a/"/>
    <meta property="og:description" content="Something amazing."/>
    ...
</head>

as their source of data.

extraction.techniques.TwitterSummaryCardTags

Another, increasingly common set of meta tags is the Twitter Card tags <https://dev.twitter.com/docs/cards/types/summary-card>_. This technique parses those tags, which look like::

<head>
    ...
    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@nytimes">
    <meta name="twitter:creator" content="@SarahMaslinNir">
    <meta name="twitter:title" content="Parade of Fans for Houston’s Funeral">
    <meta name="twitter:description" content="NEWARK - The guest list and parade...">
    <meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-article.jpg">
    ...
</head>

For sites with cards integration (which many high quality sites have, because it's necessary for rendering with images in the Twitter feed), this will be a very high quality source of data.

One oddity is that Twitter cards don't include a URL tag, so they don't help much with canonicalizing articles.

extraction.techniques.HTML5SemanticTags

The HTML5 article tag, and also the video tag give us some useful hints for extracting page information for the sites which happen to utilize these tags.

This technique will extract information from pages formed like::

<html>
  <body>
    <h1>This is not a title to HTML5SemanticTags</h1>
    <article>
      <h1>This is a title</h1>
      <p>This is a description.</p>
      <p>This is not a description.</p>
    </article>
    <video>
      <source src="this_is_a_video.mp4">
    </video>
  </body>
</html>

Note that HTML5SemanticTags is intentionally much more conservative than SemanticTags, as it provides high quality information in the small number of cases where it hits, and otherwise expects SemanticTags to run sweep behind it for the lower quality, more abundant hits it discovers.

extraction.techniques.SemanticTags

This technique relies on the basic tags themselves--for example, all img tags include images, most h1 and h2 tags include titles, and p tags often include text usable as descriptions::

<html>
  <body>
    <h1>This will be extracted as a title.</h1>
    <h2>So will this, but after all H1s.</h2>
    <img src="/datasets/Anticloud/anticloud-extraction/resolve/main/this_will_be_extracted_as_an_img.png">
    <p>And this as a description.</p>
    <p>This as another possible description.</p>
    <p>This as a third possible description.</p>
  </body>
</html>

There is a limit, defined within SemanticTags of how many tags of a given type will be consumed, and is usually 3-5, with the exception of images, where it is 10 (as this is actually a valid way to detect images, unlike the others).

This is a true last resort technique.

Implementation Details

I've tried to comment the classes and modules themselves in a fairly indepth fashion, and would recommend reading them for the most details, the recommended reading order is::

extraction/tests.py
extraction/__init__.py
extraction/techniques.py

Hopefully all questions are answered therein.

Contributions, Questions, Concerns

Please open a GitHub pull-request with any improvements, preferably with tests, and I'll be glad to merge it in.

Section quoted from the upstream readme. Anticloud overlay CLI (available in every project):

python anticloud/cli.py --help     # 13 subcommands, JSON stdout
python anticloud/cli.py checks     # run the 16-check suite

API

indepth fashion, and would recommend reading them for the most details, the recommended reading order is::

extraction/tests.py
extraction/__init__.py
extraction/techniques.py

Hopefully all questions are answered therein.

Contributions, Questions, Concerns

Please open a GitHub pull-request with any improvements, preferably with tests, and I'll be glad to merge it in.

Section quoted from the upstream readme.

Dependencies

Metric Value
Ecosystem Python
Manifests detected setup.py, requirements.txt
Files in snapshot 15
Lines of code 979
Dependency references 0
Upstream license MIT
Overlay license Anticommons 0.1.0

Pinned lockfile: anticloud/requirements.lock (hash-pinned, PEP 508). SBOM: sbom.cdx.json (CycloneDX 1.5, pinned to the upstream SHA).


Configuration

or what not::

class MyTechnique(Technique):
    def __init__(self, *args, **kwargs):
        if 'something' in kwargs:
            self.something = kwargs['something']
        del kwargs['something']
        else:
            self.something = "something else"
        return super(MyTechnique, self).__init__(*args, **kwargs)

    def extract(html, source_url=None):
        print self.something
        return super(MyTechnique, self).extract(html, source_url=source_url)

Second, all techniques are passed in the Extractor being used to process them, so you can bake the customization into an extraction.Extractor subclass::

from extraction import Extractor
from extraction.techniques import Technique

class MyExtractor(Extractor):
    techniques = ["my_module.MyTechnique"]
    def __init__(self, something, *args, **kwargs):
        self.something = something
        super(MyExtractor, self).__init__(*args, **kwargs)

class MyTechnique(Technique):
    class extract(self, html, source_url=None):
        print self.extractor.something
        return super(MyTechnique, self).extract(html, source_url=source_url)

Between these two techniques, it should be feasible to get the customization of behavior you need.

Extraction Techniques

This section lists the current techniques used by extraction. To rerank the techniques, remove techniques or add new techniques of your own, look at the Using Extraction section below.

extraction.techniques.HeadTags

Every webpage's head tag contains has a title tag, and many also include additional data like descriptions, RSS feeds and such. This technique parses data that looks like::

<head>
    <meta name="description" content="Will Larson&#39;s blog about programming and other things." />
    <link rel="alternate" type="application/rss+xml" title="Page Feed" href="/feeds/" />
    <link rel="canonical" href="http://lethain.com/digg-v4-architecture-process/">
    <title>Digg v4&#39;s Architecture and Development Processes - Irrational Exuberance</title>
</head>

While the head tag is authoritative source of canonical URLs and RSS, it's often very hit or miss for titles, descriptions and such. At worst, it's better than nothing.

extraction.techniques.FacebookOpengraphTags

For better or for worse, the highest quality source of page data is usually the Facebook Opengraph meta tags <https://developers.facebook.com/docs/opengraphprotocol/>_. This technique uses Opengraph tags, which look like this::

<head>
    ...
    <meta property="og:title" content="Something"/>
    <meta property="og:url" content="http://www.example.org/something//"/>
    <meta property="og:image" content="http://images.example.org/a/"/>
    <meta property="og:description" content="Something amazing."/>
    ...
</head>

as their source of data.

extraction.techniques.TwitterSummaryCardTags

Another, increasingly common set of meta tags is the Twitter Card tags <https://dev.twitter.com/docs/cards/types/summary-card>_. This technique parses those tags, which look like::

<head>
    ...
    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@nytimes">
    <meta name="twitter:creator" content="@SarahMaslinNir">
    <meta name="twitter:title" content="Parade of Fans for Houston’s Funeral">
    <meta name="twitter:description" content="NEWARK - The guest list and parade...">
    <meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-article.jpg">
    ...
</head>

For sites with cards integration (which many high quality sites have, because it's necessary for rendering with images in the Twitter feed), this will be a very high quality source of data.

One oddity is that Twitter cards don't include a URL tag, so they don't help much with canonicalizing articles.

extraction.techniques.HTML5SemanticTags

The HTML5 article tag, and also the video tag give us some useful hints for extracting page information for the sites which happen to utilize these tags.

This technique will extract information from pages formed like::

<html>
  <body>
    <h1>This is not a title to HTML5SemanticTags</h1>
    <article>
      <h1>This is a title</h1>
      <p>This is a description.</p>
      <p>This is not a description.</p>
    </article>
    <video>
      <source src="this_is_a_video.mp4">
    </video>
  </body>
</html>

Note that HTML5SemanticTags is intentionally much more conservative than SemanticTags, as it provides high quality information in the small number of cases where it hits, and otherwise expects SemanticTags to run sweep behind it for the lower quality, more abundant hits it discovers.

extraction.techniques.SemanticTags

This technique relies on the basic tags themselves--for example, all img tags include images, most h1 and h2 tags include titles, and p tags often include text usable as descriptions::

<html>
  <body>
    <h1>This will be extracted as a title.</h1>
    <h2>So will this, but after all H1s.</h2>
    <img src="/datasets/Anticloud/anticloud-extraction/resolve/main/this_will_be_extracted_as_an_img.png">
    <p>And this as a description.</p>
    <p>This as another possible description.</p>
    <p>This as a third possible description.</p>
  </body>
</html>

There is a limit, defined within SemanticTags of how many tags of a given type will be consumed, and is usually 3-5, with the exception of images, where it is 10 (as this is actually a valid way to detect images, unlike the others).

This is a true last resort technique.

Implementation Details

I've tried to comment the classes and modules themselves in a fairly indepth fashion, and would recommend reading them for the most details, the recommended reading order is::

extraction/tests.py
extraction/__init__.py
extraction/techniques.py

Hopefully all questions are answered therein.

Contributions, Questions, Concerns

Please open a GitHub pull-request with any improvements, preferably with tests, and I'll be glad to merge it in.

Section quoted from the upstream readme. Overlay configuration (Anticloud):

  • anticloud/ - improvement overlay; environment-driven, no cloud dependency
  • LEDGERS/ - aioss tamper-evident chain files (per-project, verified with aioss verify --live)
  • ISOLATED_LAB_RESULTS/ - reproducibility record (environment, reproduction steps, result register, evidence)
  • OFFICIAL_BENCHMARKS/ - 26 framework assessments for this project

Contributing

Upstream contributions: fork the EXTRACTION project, create a feature branch, and open a pull request against upstream. Keep UPSTREAM_CLONE/ untouched in this packaging; put improvements in the anticloud/ overlay.

Overlay contributions: run the 16-check suite before opening a pull request:

python anticloud/bench/runner.py --cwd anticloud

License

Upstream license: MIT (evidence: LICENSE.txt in the upstream snapshot).

License file excerpt:

The MIT License (MIT)
Copyright (c) 2012, Will Larson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Anticommons 0.1.0 overlay

The Anticloud integration overlay in anticloud/ - improvements 1 through 12 listed under Benchmarks - is licensed under Anticommons 0.1.0. Upstream code remains under its original MIT terms. See ANTICOMMONS_LICENSE.md in this directory for the overlay terms and contact.

SPDX: MIT (upstream) + Anticommons 0.1.0 (overlay, dual).


Upstream

  • Project: EXTRACTION (category: PHILOSOPHY SEMANTICS)
  • Upstream URL: https://github.com/lethain/extraction
  • Pinned commit (SHA): 65febdc6d462c1840b9a67ac6a1bb0f29e9e37e8
  • Branch: master
  • Pin provenance: GitHub API commits/master. The parent-project stamp is explicitly rejected for this project.
  • Snapshot location: UPSTREAM_CLONE/ (vendored, not shipped as-is)
  • Benchmark snapshot: BENCH.json

Benchmarks

Measured by the Anticloud assurance suite. Every value below is read from this project's BENCH.json, produced by a real run — the SHA3-256 of that file is 4d96d951092ebcf6a0433cc52f137e764ba57ea7b5c41bf7d5612cea0b198a08.

Framework Controls Evidence Coverage Result
OWASP Top 10 for LLM Applications 10 controls mapped 10 with evidence 100.0% PASS
OWASP Top 10 (2021) 9 controls mapped 9 with evidence 100.0% PASS
SOC 2 Type II readiness 9 controls mapped 9 with evidence 100.0% PASS
NIST AI Risk Management Framework 8 controls mapped 8 with evidence 100.0% PASS
NIST SP 800-53 Rev. 5 12 controls mapped 12 with evidence 100.0% PASS
NIST Cybersecurity Framework 2.0 8 controls mapped 8 with evidence 100.0% PASS
FedRAMP Rev. 5 10 controls mapped 10 with evidence 100.0% PASS
PCI DSS v4.0.1 11 controls mapped 11 with evidence 100.0% PASS
ISO/IEC 27001:2022 9 controls mapped 9 with evidence 100.0% PASS
MITRE ATT&CK v16 12 controls mapped 12 with evidence 100.0% PASS
ML Technology Readiness Level TRL 8 8/8 criteria PASS

Overall: 16/16 checks passing.

See ISOLATED_LAB_RESULTS/03_Result_Register.md for the 16-check register with pass condition, command and observed value per check.

Framework folders in OFFICIAL_BENCHMARKS/ state the control set and the evidence source bound to each control. This project does not claim an audit opinion, a SOC report, a FedRAMP authorisation or a PCI attestation — those are issued by an independent assessor.

Archives and Permanent Records

Platform Identifier Volume
Harvard Dataverse DOI 10.7910/DVN/YMJKOG 145 citable datasets
AIOSS verification kit DOI 10.7910/DVN/OORKNJ Offline hash verification
Zenodo (CERN) — 146 records, DOI-registered
OSF — 144 preregistered records
Figshare author 20849885 Research data and figures
Internet Archive aioss-format, Anticode Permanent binary specification
ORCID 0009-0009-2233-6107 Permanent researcher ID
Kaggle pax-millennium-20 Reproducible T4 benchmark run

Press and Independent Publication

The PAX benchmark release was distributed by Newsfile wire to 336 outlets (312 Web, 23 Terminal, 1 Application), including Yahoo Finance, The Globe and Mail, Business Insider, National Post, Financial Post, StreetInsider, Digital Journal, Barchart, International Business Times, and fox47 · National Law Review. Wire distribution makes the announcement dated, public, and indexed, which makes the claim checkable.

Downloads last month
53