Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Packaging #86

Merged
merged 46 commits into from
Sep 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
7a30b99
Remove unnecessary __init__
GjjvdBurg Jun 20, 2020
0995be7
Add setup.py with dependencies and include cli
GjjvdBurg Jun 20, 2020
dc887d9
Move js code in a javascript dir inside the package
GjjvdBurg Jun 20, 2020
08564bf
Remove __init__ in tests directory
GjjvdBurg Jun 20, 2020
9bb2542
Fix imports in test directory
GjjvdBurg Jun 20, 2020
0b0dd40
Install node modules when installing package
GjjvdBurg Jun 20, 2020
92e50a9
Adapt readability.js code to new package structure
GjjvdBurg Jun 20, 2020
13f356a
Add makefile
GjjvdBurg Jun 20, 2020
4f21b8f
Update travis config to new package structure
GjjvdBurg Jun 20, 2020
64056a0
Remove package.json from project root
GjjvdBurg Jun 20, 2020
2111c4b
Fix package.json path in setup.py
GjjvdBurg Jun 20, 2020
d209949
Be more robust against npm not existing
GjjvdBurg Jun 20, 2020
c0c9735
Throw a warning if we don't have node
GjjvdBurg Jun 20, 2020
2cc990a
Fix typo in travis config
GjjvdBurg Jun 20, 2020
ae9fc51
Ensure dependencies are updated on Travis
GjjvdBurg Jun 20, 2020
b8c91ab
Don't install in editable mode on travis
GjjvdBurg Jun 20, 2020
37631d3
Replicate all Travis tests in Makefile
GjjvdBurg Jun 20, 2020
d38db7d
Squashed commit of the following:
GjjvdBurg Jun 20, 2020
55e30ff
Set version to None in setup.py
GjjvdBurg Sep 15, 2020
af70ba2
Clarify warning messages when npm-based install fails
GjjvdBurg Sep 15, 2020
d58cfbc
Properly handle a missing npm installation
GjjvdBurg Sep 15, 2020
623d5ef
Run code quality checks on test directory
GjjvdBurg Sep 15, 2020
386b246
Fix code quality issue
GjjvdBurg Sep 15, 2020
4e61d5d
Run code quality checks on test dir on Travis
GjjvdBurg Sep 15, 2020
53339e9
Better variable names
GjjvdBurg Sep 15, 2020
5bd90e6
Better variable names
GjjvdBurg Sep 15, 2020
1e4079e
Use Python builtin virtualenv
GjjvdBurg Sep 21, 2020
24cfad7
Document the help target
GjjvdBurg Sep 21, 2020
7844f10
Attempt at getting pylint to work on tests dir
GjjvdBurg Sep 21, 2020
95273be
Add Python 3.8 testing on Travis
GjjvdBurg Sep 21, 2020
4d48849
Change pylint command for test dir
GjjvdBurg Sep 21, 2020
54770d5
Add version command to CLI
GjjvdBurg Sep 21, 2020
6451ff0
Reorder extra requires in preparation for docs
GjjvdBurg Sep 21, 2020
37dffb1
Make sure test command matches that of travis
GjjvdBurg Sep 21, 2020
e40afbf
Minor fixes to docs target in Makefile
GjjvdBurg Sep 21, 2020
7fadc5d
Add release script to Git
GjjvdBurg Sep 21, 2020
b7f9559
Add a change log
GjjvdBurg Sep 21, 2020
5929ac4
Rewrite the readme to match the new package layout
GjjvdBurg Sep 21, 2020
c06e42c
Clarify installation instructions
GjjvdBurg Sep 21, 2020
d325f4a
readme fix
GjjvdBurg Sep 21, 2020
c0fdb87
Fix pylint complaints in release script
GjjvdBurg Sep 21, 2020
a76f381
Change color to colour
jemrobinson Sep 21, 2020
01651e8
Fix missing colour replacement
jemrobinson Sep 21, 2020
b7ee006
Merge remote-tracking branch 'upstream/master' into packaging
jemrobinson Sep 22, 2020
4e3ef82
Added maintainer fields to setup.py
jemrobinson Sep 22, 2020
4c06d21
Minor README updates
jemrobinson Sep 22, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,30 @@ language: python
python:
- 3.6
- 3.7
- 3.8

before_install:
# Install node.js following instructions from
# https://nodejs.org/en/download/package-manager/
- sudo apt install curl
- curl -sL https://deb.nodesource.com/setup_11.x | sudo bash -
- sudo apt install nodejs
# Use the pre-installed nvm version to update node
# Apparently Travis comes with nvm even on the python containers
- nvm install v12.18.1
- nvm use v12.18.1
- node -v
- npm version

install:
# Install node.js dependencies
- npm install
# Install python dependencies
- pip install -r requirements-dev.txt
# Install package, while updating dependencies
- pip install --upgrade --upgrade-strategy eager .[dev]

script:
# Run all pytest unit tests
- python -m pytest -v tests --cov readabilipy --cov-report term-missing --benchmark-disable
- cd tests && python -m pytest -v . --cov readabilipy --cov-report term-missing --benchmark-disable && cd ..
# Run pyflakes for error detection
- pyflakes *.py readabilipy tests
# Check PEP8 compliance (ignoring long lines)
- pycodestyle --statistics --ignore=E501 --count *.py readabilipy tests
# Run pylint for stricter error checking
- pylint readabilipy tests
- pylint readabilipy
GjjvdBurg marked this conversation as resolved.
Show resolved Hide resolved
- pylint ./tests/*.py

after_success:
# Upload results to coveralls.io
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Change Log

## Version 0.1.0

* Initial release of Python package to PyPI.
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include readabilipy/javascript/*.js
include readabilipy/javascript/package.json
108 changes: 108 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Makefile for easier installation and cleanup.
#
# Uses self-documenting macros from here:
# http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html

SHELL := bash
.SHELLFLAGS := -eu -o pipefail -c
MAKEFLAGS += --warn-undefined-variables --no-builtin-rules

PACKAGE=readabilipy
DOC_DIR=./docs
VENV_DIR=/tmp/rdpy_venv
TEST_DIR=./tests

.PHONY: help

.DEFAULT_GOAL := help

# Display a help message when called without target, using the ## comments
help:
@grep -E '^[0-9a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) |\
awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m\
%s\n", $$1, $$2}'
GjjvdBurg marked this conversation as resolved.
Show resolved Hide resolved

################
# Installation #
################

.PHONY: install

install: ## Install for the current user using the default python command
python setup.py build_ext --inplace
python setup.py install --user


################
# Distribution #
################

.PHONY: release dist

release: ## Make a release
python make_release.py

dist: ## Make Python source distribution
python setup.py sdist bdist_wheel


###########
# Testing #
###########

.PHONY: test

test: venv ## Run unit tests
source $(VENV_DIR)/bin/activate && cd $(TEST_DIR) && \
python -m pytest -v . --cov readabilipy \
--cov-report term-missing --benchmark-disable
source $(VENV_DIR)/bin/activate && pyflakes *.py readabilipy $(TEST_DIR)
source $(VENV_DIR)/bin/activate && pycodestyle --statistics \
--ignore=E501 --count *.py readabilipy $(TEST_DIR)
source $(VENV_DIR)/bin/activate && pylint readabilipy $(TEST_DIR)/*.py

#################
# Documentation #
#################

.PHONY: docs

docs: install ## Build documentation with Sphinx
exit; # not implemented
source $(VENV_DIR)/bin/activate && m2r README.md && mv README.rst $(DOC_DIR)
source $(VENV_DIR)/bin/activate && m2r CHANGELOG.md && mv CHANGELOG.rst $(DOC_DIR)
cd $(DOC_DIR) && \
rm source/* && \
source $(VENV_DIR)/bin/activate && \
sphinx-apidoc -H 'ReadabiliPy API Documentation' -o source ../$(PACKAGE) && \
touch source/AUTOGENERATED
$(MAKE) -C $(DOC_DIR) html

#######################
# Virtual environment #
#######################

.PHONY: venv

venv: $(VENV_DIR)/bin/activate

$(VENV_DIR)/bin/activate: setup.py
test -d $(VENV_DIR) || python -m venv $(VENV_DIR)
source $(VENV_DIR)/bin/activate && pip install .[dev]
touch $(VENV_DIR)/bin/activate

############
# Clean up #
############

.PHONY: clean

clean: ## Clean build dist and egg directories left after install
rm -rf ./dist
rm -rf ./build
rm -rf ./$(PACKAGE).egg-info
rm -rf $(VENV_DIR)
rm -f MANIFEST
rm -rf $(PACKAGE)/javascript/node_modules
find . -type f -iname '*.pyc' -delete
find . -type d -name '__pycache__' -empty -delete
172 changes: 110 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,67 +1,115 @@
ReadabiliPy
# ReadabiliPy

[![Build Status](https://travis-ci.org/alan-turing-institute/ReadabiliPy.svg?branch=master)](https://travis-ci.org/alan-turing-institute/ReadabiliPy)
[![Coverage Status](https://coveralls.io/repos/github/alan-turing-institute/ReadabiliPy/badge.svg?branch=master)](https://coveralls.io/github/alan-turing-institute/ReadabiliPy?branch=master)
===========
A Node and filesystem dependent Python wrapper for Mozilla's [Readability.js](https://github.com/mozilla/readability) Node.js package.

This package also augments the output of `Readability.js` to also return a list of plain text representations of article paragraphs.

## Package contents
- `javascript` folder
- `Readability.js`: Taken unaltered from commit [876c81f](https://github.com/mozilla/readability/tree/876c81f710711ba2afb36dd83889d4c5b4fc2743) of Mozilla's [Readability.js](https://github.com/mozilla/readability) Node.js package.

- `ExtractArticle.js`: A Node.js script that reads a file containing a HTML snippet (does not have to be a full document), parses it using [jsdom](https://github.com/jsdom/jsdom), attempts to extract an article using `Readability.parse()` and writes the output to a JSON file.
- Usage: `node ExtractArticle.js -i <input_file> -o <output_file>`
- Arguments:
- `-i`: The path to an input file containing full or partial HTML as text.
- `-o`: The path to the file the output article JSON data should be written to.

- `readabilipy` folder
- `simple_json.py` file containing the function `simple_json_from_html_string()`.
- Usage:
```python
from readabilipy import simple_json_from_html_string

article = simple_json_from_html_string(html_string, content_digests=False, node_indexes=False, use_readability=False)
```
- The function returns a dictionary with the following fields:
- `title`: The article title
- `byline`: Author information
- `content`: A simplified HTML representation of the article, with all article text contained in paragraph elements.
- `plain_content`: A "plain" version of the simplified `Readability.js` article HTML present in the `content` field. This attempts to retain only the plain text content of the article, while preserving the HTML structure.
- `plain_text`: A list containing plain text representations of each paragraph (`<p>`) or list (`<ol>` or `<ul>`) present in the simplified `Readability.js` article HTML in the `content` field. Each paragraph or list is represented as a single string. List strings look like `"* item 1, * item 2, * item 3,"` for both ordered and unordered lists (note the trailing `,`).
- All fields are guaranteed to be present. If individual fields are missing from the output of `Readability.js`, the value of these fields will be `None`. If no article data is returned by `Readability.js`, the value of all fields will be `None`.
- All text in the `plain_content` and `plain_text` fields is encoded as unicode normalised using the "NFKC" normal form. This normal form is used to try and ensure as much as possible that things that appear visually the same are encoded with the same unicode representation (the K part) and characters are represented as a single composite character where possible (the C part).
- An optional `content_digests` flag can be passed to the Python wrapper. When this is set to `True`, each HTML element in the `plain_content` field has a `data-content-digest` attribute, which holds the SHA-256 hash of its plain text content. For "leaf" nodes (containing only plain text in the output), this is the SHA-256 hash of their plain text content. For nodes containing other nodes, this is the SHA-256 hash of the concatenated SHA-256 hashes of their child nodes.
- An optional `node_indexes` flag can be passed to the Python wrapper. When this is set to `True`, each HTML element in the `plain_content` field has a `data-node-indexes` attribute, which holds a hierarchical index describing the location of element within the `plain_content` HTML structure.
- An optional `use_readability` flag can be passed to the Python wrapper. When this is set to `True`, Mozilla's `Readability.js` will be used as the parser. If it is set to `False` then the pure-python parser in `plain_html.py` will be used instead.

- `simple_tree.py` file containing the function `simple_tree_from_html_string()`.
- Usage:
```python
from readabilipy import simple_tree_from_html_string

article = simple_tree_from_html_string(html_string)
```
- The function returns a `bs4.BeautifulSoup` object containing a cleaned, parsed HTML tree.


- `extract_article.py`: A Python script that uses `readabilipy.simple_json_from_html_string()` to extract the augmented readable article data.
- Usage: `python extract_article.py -i <input_file> -o <output_file> [-c] [-n] [-p]`
- All arguments have long and short form versions.
- `-i` / `--input-file`: The path to an input file containing full or partial HTML as text.
- `-o` / `--output-file`: The path to the file the output article JSON data should be written to.
- `-c` / `--content-digests` (optional): If this flag is provided, then `simple_json_from_html_string()` is called with `content_digests=True`
- `-n` / `--node-indexes` (optional): If this flag is provided, then `simple_json_from_html_string()` is called with `node_indexes=True`
- `-p` / `--use-python-parser` (optional): If this flag is provided then `simple_json_from_html_string()` is called with `use_readability=False`

`ReadabiliPy` contains a Python wrapper for Mozilla's [Readability.js](https://github.com/mozilla/readability) Node.js package, as well as article extraction routines written in pure Python.

This package augments the output of `Readability.js` to also return a list of plain text representations of article paragraphs.

`ReadabiliPy` comes with a handy command line application: ``readabilipy``.

## Installation
1. [Install Node.js](https://nodejs.org/en/download/)
2. Install the node part of this package by running `npm install`.
3. Install the requirements for the Python part of this package by running:
- As a user of this project `pip install -r requirements.txt`
- As a developer of this project `pip install -r requirements-dev.txt`

## Testing
1. Run the tests with `python -m pytest -vv`

To use the `Readability.js` wrapper you need to have a working [Node.js](https://nodejs.org/en/download/) installation of version 10 or higher.
Make sure to install Node.js before installing this package, as this ensures Readability.js will be installed.
If you only want to use the Python-based article extraction, you **do not need** to install Node.js.

`ReadabiliPy` can be installed simply from PyPI:

```
$ pip install readabilipy
```

Note that to update to a new version of `Readability.js` you can simply reinstall `ReadabiliPy`.

## Usage

`ReadabiliPy` can be used either as a command line application or as a Python library.

### Command line application

The ``readabilipy`` command line application can be used to extract an article from an HTML source file.

For example, if you have the article saved as ``input.html`` in the current directory then you can run:

```
$ readabilipy -i ./input.html -o article.json
```

The extracted article can then be found in the ``article.json`` file. By default ReadabiliPy will use the Readability.js functionality to extract the article, provided this is available. If instead you'd like to use the Python-based extraction, run:

```
$ readabilipy -p -i ./input.html -o article.json
```

The complete help text of the command line application is as follows:

```
$ readabilipy -h
usage: readabilipy [-h] -i INPUT_FILE -o OUTPUT_FILE [-c] [-n] [-p] [-V]

Extract article data from a HTML file using either Mozilla's Readability.js
package or a simplified python-only alternative.

optional arguments:
-h, --help show this help message and exit
-i INPUT_FILE, --input-file INPUT_FILE
Path to input file containing HTML.
-o OUTPUT_FILE, --output-file OUTPUT_FILE
Path to file to output the article data to as JSON.
-c, --content-digests
Add a 'data-content-digest' attribute containing a
SHA256-based digest of the element's contents to each
HTML element in the plain_content output.
-n, --node-indexes Add a 'data-node-index' attribute containing a
hierarchical representation of the element's position
in the HTML structure each HTML element in the
plain_content output.
-p, --use-python-parser
Use the pure-python 'plain_html' parser included in
this project rather than Mozilla's Readability.js.
-V, --version Show version and exit
```

## Library

ReadabiliPy can also be used as a Python package.
The main routine is called ``simple_json_from_html_string`` and expects the HTML article as a string.
Here is an example of extracting an article after downloading the page using [requests](https://requests.readthedocs.io/en/master/):

```python
>>> import requests
>>> from readabilipy import simple_json_from_html_string
>>> req = requests.get('https://en.wikipedia.org/wiki/Readability')
>>> article = simple_json_from_html_string(req.text, use_readability=True)
```

Note that you need to use the flag ``use_readability=True`` to use Readability.js, otherwise the Python-based extraction is used.

The ``simple_json_from_html_string`` function returns a dictionary with the following fields:

- `title`: The article title
- `byline`: Author information
- `content`: A simplified HTML representation of the article, with all article text contained in paragraph elements.
- `plain_content`: A "plain" version of the simplified `Readability.js` article HTML present in the `content` field. This attempts to retain only the plain text content of the article, while preserving the HTML structure.
- `plain_text`: A list containing plain text representations of each paragraph (`<p>`) or list (`<ol>` or `<ul>`) present in the simplified `Readability.js` article HTML in the `content` field. Each paragraph or list is represented as a single string. List strings look like `"* item 1, * item 2, * item 3,"` for both ordered and unordered lists (note the trailing `,`).

Note further that:

- All fields are guaranteed to be present. If individual fields are missing from the output of `Readability.js`, the value of these fields will be `None`. If no article data is returned by `Readability.js`, the value of all fields will be `None`.
- All text in the `plain_content` and `plain_text` fields is encoded as unicode normalised using the "NFKC" normal form. This normal form is used to try and ensure as much as possible that things that appear visually the same are encoded with the same unicode representation (the K part) and characters are represented as a single composite character where possible (the C part).
- An optional `content_digests` flag can be passed to the Python wrapper. When this is set to `True`, each HTML element in the `plain_content` field has a `data-content-digest` attribute, which holds the SHA-256 hash of its plain text content. For "leaf" nodes (containing only plain text in the output), this is the SHA-256 hash of their plain text content. For nodes containing other nodes, this is the SHA-256 hash of the concatenated SHA-256 hashes of their child nodes.
- An optional `node_indexes` flag can be passed to the Python wrapper. When this is set to `True`, each HTML element in the `plain_content` field has a `data-node-indexes` attribute, which holds a hierarchical index describing the location of element within the `plain_content` HTML structure.
- An optional `use_readability` flag can be passed to the Python wrapper. When this is set to `True`, Mozilla's `Readability.js` will be used as the parser. If it is set to `False` then the pure-python parser in `plain_html.py` will be used instead.

The second top-level function exported by ReadabiliPy is ``simple_tree_from_html_string``. This returns a cleaned, parsed HTML tree of the article as a [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) object.

## Notes

License: MIT License, see the `LICENSE` file.

Copyright (c) 2018, The Alan Turing Institute

If you encounter any issues or have any suggestions for improvement, please open an issue [on Github](https://github.com/alan-turing-institute/ReadabiliPy).
You're helping to make this project better for everyone!
Empty file removed __init__.py
Empty file.
33 changes: 0 additions & 33 deletions extract_article.py

This file was deleted.

Loading