├── .gitignore
├── docs
├── data_structure.png
├── getting_started.md
└── data_structure.md
├── setup.py
├── requirements.txt
├── database
├── file.py
├── answer.py
├── content.py
├── consultee.py
├── consultee_list.py
├── document.py
├── base.py
└── remiss.py
├── app.py
├── service
├── writer.py
├── ocr.py
├── file_manager.py
├── tabula_parser.py
├── wikidata.py
├── downloader.py
├── selenium_driver.py
├── database.py
├── web_parser.py
├── cleaner.py
└── document_parser.py
├── download_data.py
├── test.py
├── api
└── schema.py
├── clean_data.py
├── README.md
├── test
└── service
│ └── test_document_parser.py
├── LICENSE
└── illustration.svg
/.gitignore:
--------------------------------------------------------------------------------
1 | *.db
2 | *.db-journal
3 | *.pdf
4 | __pycache__
5 | env/
6 | .DS_Store
7 |
--------------------------------------------------------------------------------
/docs/data_structure.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DinRiksdag/OpenRemiss/HEAD/docs/data_structure.png
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | print('\n\n### OpenRemiss v0.3 ###\n\n')
2 |
3 | print('I - Downloading data from regeringen.se\n')
4 | import download_data
5 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | beautifulsoup4==4.12.2
2 | flask==2.3.2
3 | flask-graphQL==2.0.1
4 | graphene-sqlalchemy
5 | pikepdf==7.2.0
6 | sqlalchemy==2.0.12
7 | selenium==4.9.0
8 | webdriver-manager==3.8.6
9 | packaging==23.1
10 | fake-useragent==1.1.3
11 | tabula-py==2.7.0
12 | ocrmypdf==14.1.0
13 | pytest==7.3.1
14 | rapidfuzz==3.0.0
15 | SPARQLWrapper==2.0.0
16 | pdfminer
17 | pdf2image
18 | pymupdf
19 |
--------------------------------------------------------------------------------
/database/file.py:
--------------------------------------------------------------------------------
1 | from .base import Base
2 | from sqlalchemy import ForeignKey, Column, Integer, String
3 | from sqlalchemy.orm import relationship
4 |
5 |
6 | class File(Base):
7 | """File model."""
8 |
9 | __tablename__ = 'file'
10 |
11 | id = Column(Integer, primary_key=True)
12 | document_id = Column(Integer, ForeignKey('document.id'))
13 | document = relationship('Document', back_populates='files')
14 | name = Column(String)
15 | url = Column(String)
16 |
--------------------------------------------------------------------------------
/database/answer.py:
--------------------------------------------------------------------------------
1 | from database.document import Document
2 | from sqlalchemy import ForeignKey, Column, Integer, String
3 | from sqlalchemy.orm import relationship
4 |
5 |
6 | class Answer(Document):
7 | """Answer model."""
8 |
9 | __tablename__ = 'answer'
10 |
11 | id = Column(Integer, ForeignKey('document.id'), primary_key=True)
12 | remiss = relationship('Remiss', back_populates='answers')
13 | organisation = Column(String)
14 |
15 | __mapper_args__ = {
16 | 'polymorphic_identity': 'answer',
17 | }
18 |
--------------------------------------------------------------------------------
/database/content.py:
--------------------------------------------------------------------------------
1 | from .base import Base
2 | from sqlalchemy import Column, Integer, String, Date
3 |
4 |
5 | class Content(Base):
6 | """Content model."""
7 |
8 | __tablename__ = 'content'
9 |
10 | id = Column(Integer, primary_key=True)
11 | issuer = Column(String)
12 | published_on = Column(Date)
13 | title = Column(String)
14 | url = Column(String)
15 | type = Column(String)
16 |
17 | __mapper_args__ = {
18 | 'polymorphic_identity': 'content',
19 | 'polymorphic_on': type
20 | }
21 |
--------------------------------------------------------------------------------
/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask_graphql import GraphQLView
3 |
4 | from service.database import Database
5 | from api.schema import schema
6 |
7 | app = Flask(__name__)
8 | app.debug = True
9 |
10 | app.add_url_rule(
11 | '/graphql',
12 | view_func=GraphQLView.as_view(
13 | 'graphql',
14 | schema=schema,
15 | graphiql=True
16 | )
17 | )
18 |
19 |
20 | @app.teardown_appcontext
21 | def shutdown_session(exception=None):
22 | Database.remove()
23 |
24 |
25 | if __name__ == '__main__':
26 | app.run()
27 |
--------------------------------------------------------------------------------
/database/consultee.py:
--------------------------------------------------------------------------------
1 | from .base import Base
2 | from sqlalchemy import ForeignKey, Column, Integer, String
3 | from sqlalchemy.orm import relationship
4 |
5 |
6 | class Consultee(Base):
7 | """Consultee model."""
8 |
9 | __tablename__ = 'consultee'
10 |
11 | id = Column(Integer, primary_key=True)
12 | consultee_list_id = Column(Integer, ForeignKey('consultee_list.id'))
13 | consultee_list = relationship('ConsulteeList',
14 | back_populates='consultee_list')
15 | name = Column(String)
16 | cleaned_name = Column(String)
17 |
--------------------------------------------------------------------------------
/database/consultee_list.py:
--------------------------------------------------------------------------------
1 | from database.document import Document
2 | from sqlalchemy import ForeignKey, Column, Integer
3 | from sqlalchemy.orm import relationship
4 |
5 |
6 | class ConsulteeList(Document):
7 | """ConsulteeList model."""
8 |
9 | __tablename__ = 'consultee_list'
10 |
11 | id = Column(Integer, ForeignKey('document.id'), primary_key=True)
12 | remiss = relationship('Remiss', back_populates='consultees')
13 | consultee_list = relationship('Consultee', back_populates='consultee_list')
14 |
15 | __mapper_args__ = {
16 | 'polymorphic_identity': 'consultee_list',
17 | }
18 |
--------------------------------------------------------------------------------
/database/document.py:
--------------------------------------------------------------------------------
1 | from .base import Base
2 | from sqlalchemy import ForeignKey, Column, Integer, String
3 | from sqlalchemy.orm import relationship
4 |
5 |
6 | class Document(Base):
7 | """Document model."""
8 |
9 | __tablename__ = 'document'
10 |
11 | id = Column(Integer, primary_key=True)
12 | remiss_id = Column(Integer, ForeignKey('remiss.id'))
13 | remiss = relationship('Remiss', back_populates='other_documents')
14 | files = relationship('File', back_populates='document')
15 | type = Column(String)
16 |
17 | __mapper_args__ = {
18 | 'polymorphic_identity': 'document',
19 | 'polymorphic_on': type
20 | }
21 |
--------------------------------------------------------------------------------
/service/writer.py:
--------------------------------------------------------------------------------
1 | import csv
2 | import json
3 |
4 | class Writer(object):
5 | @staticmethod
6 | def write_json(dict, filename):
7 | with open(filename, 'w') as fp:
8 | json_string = json.dumps(dict, ensure_ascii=False,
9 | indent=4).encode('utf-8')
10 | fp.write(json_string.decode())
11 |
12 | @staticmethod
13 | def write_csv(dict, filename):
14 | keys = dict[0].keys()
15 |
16 | with open(filename, 'w', newline='') as output_file:
17 | dict_writer = csv.DictWriter(output_file, keys)
18 | dict_writer.writeheader()
19 | dict_writer.writerows(dict)
20 |
--------------------------------------------------------------------------------
/database/base.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import create_engine
2 | from sqlalchemy.ext.declarative import declarative_base
3 | from sqlalchemy.orm import scoped_session, sessionmaker
4 | import os
5 |
6 |
7 | # Create database engine
8 | db_name = 'database.db'
9 | db_path = os.path.join(os.path.dirname(__file__), db_name)
10 | db_uri = 'sqlite:///{}'.format(db_path)
11 | engine = create_engine(db_uri)
12 |
13 | # Declarative base model to create database tables and classes
14 | Base = declarative_base()
15 | Base.metadata.bind = engine # Bind engine to metadata of the base class
16 |
17 | # Create database session object
18 | db_session = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))
19 | Base.query = db_session.query_property() # Used by graphql to execute queries
20 |
--------------------------------------------------------------------------------
/service/ocr.py:
--------------------------------------------------------------------------------
1 | import ocrmypdf
2 | import pikepdf
3 |
4 | class OCR(object):
5 |
6 | @staticmethod
7 | def ocr(path):
8 | new_path = path.replace('.pdf', '-ocr.pdf')
9 |
10 | try:
11 | ocrmypdf.ocr(
12 | path,
13 | new_path,
14 | language='swe',
15 | deskew=True,
16 | force_ocr=True
17 | )
18 | except ocrmypdf.exceptions.EncryptedPdfError:
19 | print('Document seems to be encrypted, attempting to decrypt with empty password.')
20 | with pikepdf.Pdf.open(path, password='', allow_overwriting_input=True) as pdf:
21 | pdf.save(path)
22 | return OCR.ocr(path)
23 |
24 | return new_path
25 |
--------------------------------------------------------------------------------
/service/file_manager.py:
--------------------------------------------------------------------------------
1 | import os
2 | import rapidfuzz.fuzz as fuzz
3 |
4 | class FileManager(object):
5 |
6 | @staticmethod
7 | def filepath_exists(filepath):
8 | return os.path.exists(filepath)
9 |
10 | @staticmethod
11 | def move(old_filepath, new_filepath):
12 | dirpath = os.path.dirname(new_filepath)
13 | if not os.path.exists(dirpath):
14 | os.makedirs(dirpath)
15 |
16 | if os.path.exists(old_filepath):
17 | os.rename(old_filepath, new_filepath)
18 | elif os.path.exists(old_filepath + '.pdf'):
19 | os.rename(old_filepath + '.pdf', new_filepath)
20 | else:
21 | for file in os.listdir('tmp/'):
22 | path = os.path.join('tmp/', file)
23 | if os.path.isfile(path) and fuzz.ratio(path, new_filepath):
24 | os.rename(path, new_filepath)
25 |
--------------------------------------------------------------------------------
/database/remiss.py:
--------------------------------------------------------------------------------
1 | from database.content import Content
2 | from sqlalchemy import ForeignKey, Column, Integer, String, Date
3 | from sqlalchemy.orm import relationship
4 |
5 |
6 | class Remiss(Content):
7 | """Remiss model."""
8 |
9 | __tablename__ = 'remiss'
10 |
11 | id = Column(Integer, ForeignKey('content.id'), primary_key=True)
12 | diary_number = Column(String)
13 | deadline = Column(Date)
14 | consultees = relationship(
15 | 'ConsulteeList',
16 | back_populates='remiss',
17 | uselist=False,
18 | viewonly=True
19 | )
20 | answers = relationship(
21 | 'Answer',
22 | back_populates='remiss',
23 | viewonly=True
24 | )
25 | other_documents = relationship('Document', back_populates='remiss',
26 | viewonly=True)
27 |
28 | __mapper_args__ = {
29 | 'polymorphic_identity': 'remiss',
30 | }
31 |
--------------------------------------------------------------------------------
/service/tabula_parser.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import tabula
3 |
4 | class TabulaParser(object):
5 |
6 | @staticmethod
7 | def extract(filename, pages, area):
8 | try:
9 | return tabula.read_pdf(
10 | input_path = filename,
11 | pages = pages,
12 | pandas_options = {'header': None},
13 | area = area
14 | )
15 | except subprocess.CalledProcessError as e:
16 | print(f'Document {filename} was most probably not a PDF')
17 | return None
18 |
19 | @staticmethod
20 | def extract_header(filename):
21 | return TabulaParser.extract(
22 | filename,
23 | 1,
24 | [
25 | [10, 300, 100, 580], # Header with document number
26 | [100, 20, 200, 300] # Department and sender name
27 | ]
28 | )
29 |
30 | @staticmethod
31 | def extract_first_page(filename):
32 | return TabulaParser.extract(
33 | filename,
34 | 1,
35 | [160, 70, 800, 500] # List
36 | )
37 |
38 | @staticmethod
39 | def extract_next_pages(filename):
40 | df = TabulaParser.extract(
41 | filename,
42 | 'all',
43 | [70, 70, 800, 500] # List
44 | )
45 | return df[1:] if df != None else None
46 |
--------------------------------------------------------------------------------
/download_data.py:
--------------------------------------------------------------------------------
1 | from service.downloader import Downloader
2 | from service.database import Database
3 |
4 | from database.remiss import Remiss
5 |
6 | AMOUNT = 3000
7 | RESET_DB = False
8 |
9 | if RESET_DB:
10 | Database.drop_tables()
11 | Database.create_tables()
12 | print(f'I-0 - Recreated database.\n')
13 |
14 | downloader = Downloader()
15 |
16 | saved_remisser = Remiss.query.all()
17 | print(f'I-1 - Found {len(saved_remisser)} remisser in the database.\n')
18 |
19 | print('Querying regeringen.se...')
20 | remisser = downloader.get_last_remisser(AMOUNT)
21 |
22 | nb_of_remisser = len(remisser)
23 | print(f'I-2 - Found {nb_of_remisser} remisser online.\n')
24 |
25 | for index, online_remiss in enumerate(remisser, start=1):
26 | found = False
27 | for saved_remiss in saved_remisser:
28 | if saved_remiss.url == online_remiss.url:
29 | print(
30 | f'{index}/{nb_of_remisser} remiss(er) - '
31 | f'Already saved (id {saved_remiss.id})'
32 | )
33 | found = True
34 |
35 | if found:
36 | continue
37 |
38 | Database.add(online_remiss)
39 | Database.flush()
40 |
41 | documents = downloader.get_documents(online_remiss)
42 |
43 | for doc in documents:
44 | Database.add(doc)
45 |
46 | Database.commit()
47 | print(
48 | f'{index}/{nb_of_remisser} remiss(er) saved - '
49 | f'{len(documents)} documents(s)'
50 | )
51 |
52 | Database.close()
53 |
--------------------------------------------------------------------------------
/service/wikidata.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from SPARQLWrapper import SPARQLWrapper, JSON
3 |
4 | endpoint_url = "https://query.wikidata.org/sparql"
5 |
6 | query = """
7 | SELECT DISTINCT ?orgLabel ?typeLabel WHERE {
8 | BIND(wd:Q34 AS ?country)
9 | {
10 | VALUES ?type {
11 | wd:Q68295960
12 | wd:Q107407151
13 | wd:Q127448
14 | wd:Q1754161
15 | wd:Q10397683
16 | wd:Q59603261
17 | wd:Q10330441
18 | wd:Q341627
19 | wd:Q2065704
20 | wd:Q190752
21 | wd:Q1289455
22 | wd:Q18292311
23 | wd:Q10530889
24 | }
25 | ?org wdt:P31 ?type;
26 | wdt:P17 ?country.
27 | }
28 | UNION
29 | {
30 | VALUES ?type {
31 | wd:Q108059166
32 | wd:Q108058047
33 | wd:Q3917681
34 | }
35 | ?org wdt:P31 ?type;
36 | wdt:P137 ?country.
37 | }
38 | UNION
39 | {
40 | VALUES ?org {
41 | wd:Q10475844
42 | }
43 | }
44 | MINUS { ?org wdt:P576 _:b15. }
45 | MINUS { ?org wdt:P1366 _:b16. }
46 | MINUS { ?org wdt:P3999 _:b17. }
47 | SERVICE wikibase:label { bd:serviceParam wikibase:language "sv,en". }
48 | }
49 | ORDER BY (?typeLabel)"""
50 |
51 |
52 | def get_government_organisations():
53 | user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1])
54 | # TODO adjust user agent; see https://w.wiki/CX6
55 | sparql = SPARQLWrapper(endpoint_url, agent=user_agent)
56 | sparql.setQuery(query)
57 | sparql.setReturnFormat(JSON)
58 | results = sparql.query().convert()
59 | results = results["results"]["bindings"]
60 | results = [org['orgLabel']['value'] for org in results]
61 |
62 | return results
63 |
64 |
--------------------------------------------------------------------------------
/service/downloader.py:
--------------------------------------------------------------------------------
1 | import urllib
2 |
3 | from service.selenium_driver import Selenium_Driver
4 | from service.web_parser import WebParser
5 |
6 | REGERING_URL = 'https://www.regeringen.se'
7 | REGERING_QUERY_URL = REGERING_URL + '/Filter/GetFilteredItems?'
8 |
9 | def parameters(page_size, page_number):
10 | params = {
11 | 'lang': 'sv',
12 | 'filterType': 'Taxonomy',
13 | 'preFilteredCategories': 2099,
14 | 'displayLimited': 'true',
15 | 'pageSize': page_size,
16 | 'page': page_number,
17 | }
18 | return urllib.parse.urlencode(params)
19 |
20 | class Downloader(object):
21 |
22 | def __init__(self):
23 | self.d = Selenium_Driver()
24 |
25 | def get_remiss_amount(self):
26 | response = self.d.get_json(REGERING_QUERY_URL + parameters(1, 1))
27 |
28 | return response['TotalCount']
29 |
30 | def get_last_remisser(self, amount):
31 | if amount > 1000:
32 | page_size = 1000
33 | else:
34 | page_size = amount
35 |
36 | page_amount = amount // 1000 + 1
37 |
38 | last_remisser = []
39 |
40 | for page_number in range(1, page_amount + 1):
41 | last_remisser.extend(self.get_remisser_for_page(page_size, page_number))
42 |
43 | return last_remisser
44 |
45 | def get_remisser_for_page(self, page_size, page_number):
46 | contents = self.d.get_json(REGERING_QUERY_URL + parameters(page_size, page_number))
47 |
48 | return WebParser.get_remiss_list(contents)
49 |
50 | def get_documents(self, remiss):
51 | contents = self.d.get(remiss.url)
52 | return WebParser.get_document_list(remiss.id, contents)
53 |
54 | def get_file(self, file_url):
55 | return self.d.get_file(file_url)
56 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 |
2 | from rapidfuzz import fuzz
3 |
4 | from service.database import Database
5 | from service.cleaner import Cleaner
6 | from service.file_manager import FileManager
7 | from database.consultee import Consultee
8 |
9 | import pandas as pd
10 |
11 | import service.wikidata as wikidata
12 |
13 | # RESET_DB = False
14 |
15 | # if RESET_DB:
16 | # Database.empty_column(Consultee, Consultee.cleaned_name)
17 | # Database.commit()
18 |
19 | # popular_names = Database.get_popular_names(1)
20 | # print(popular_names)
21 | # print(len(popular_names))
22 |
23 | # print('Getting all consultees...')
24 | # all_consultees = Consultee.query.group_by(Consultee.name).filter(Consultee.cleaned_name == None).all()
25 |
26 | # print('Starting...')
27 | # for consultee in all_consultees:
28 | # if not consultee.cleaned_name:
29 | # consultee.cleaned_name = Cleaner.replace_by_popular(consultee.name, 99)
30 | # Database.commit()
31 |
32 | RESET_WIKIDATA = True
33 | GOV_LIST = 'tmp/government_organisations.csv'
34 | if RESET_WIKIDATA or not FileManager.filepath_exists(GOV_LIST):
35 | print('Downloading names for all Swedish public sector from Wikidata...')
36 | pd.DataFrame(wikidata.get_government_organisations(), columns=['organisation']).to_csv(GOV_LIST, index=None)
37 |
38 | gov_list = pd.read_csv(GOV_LIST)['organisation'].to_list()
39 |
40 |
41 | all_consultees = Consultee.query.group_by(Consultee.name).all()
42 | #.group_by(Consultee.name).filter(Consultee.cleaned_name == None)
43 |
44 | print('Starting...')
45 | for consultee in all_consultees:
46 | name = consultee.name
47 | cleaned_name = Cleaner.closest_in_list(consultee.name, gov_list, 90)
48 |
49 | if not cleaned_name:
50 | continue
51 |
52 | same = Consultee.query.filter(Consultee.name == name).all()
53 | for item in same:
54 | item.cleaned_name = cleaned_name
55 |
56 | Database.commit()
57 | print(f'Cleaned "{name}" {len(same)} times.')
58 |
--------------------------------------------------------------------------------
/service/selenium_driver.py:
--------------------------------------------------------------------------------
1 | import json
2 | import time
3 | import os
4 |
5 | from selenium import webdriver
6 | from selenium.webdriver.chrome.service import Service as ChromeService
7 | from selenium.webdriver import ChromeOptions
8 | from webdriver_manager.chrome import ChromeDriverManager
9 |
10 | from fake_useragent import UserAgent
11 |
12 | DOWNLOAD_DIR_MAC = "/Users/pierre/Code/DinRiksdag/OpenRemiss/tmp"
13 |
14 | def wait_for_downloads():
15 | time.sleep(1)
16 | while any([filename.endswith(".crdownload") for filename in
17 | os.listdir(DOWNLOAD_DIR_MAC)]):
18 | time.sleep(1)
19 | class Selenium_Driver(object):
20 |
21 | def __init__(self):
22 | options = ChromeOptions()
23 | userAgent = UserAgent().random
24 | options.add_argument(f'user-agent = { userAgent }')
25 | options.add_argument("--headless=chrome")
26 | options.add_experimental_option('prefs', {
27 | "download.default_directory": DOWNLOAD_DIR_MAC,
28 | "download.prompt_for_download": False,
29 | "download.directory_upgrade": True,
30 | "plugins.always_open_pdf_externally": True
31 | }
32 | )
33 |
34 | self.d = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options)
35 |
36 | def get(self, url):
37 | self.d.get(url)
38 | return self.d.page_source
39 |
40 | def get_json(self, url):
41 | response = self.get(url)
42 |
43 | return json.loads(response[response.index('{'):response.index('}') + 1])
44 |
45 | def get_file(self, url):
46 | self.d.get(url)
47 | wait_for_downloads()
48 |
49 | if 'Sidan kan inte hittas' in self.d.title:
50 | print(f'404: Could not download file from {url}')
51 | return None
52 |
53 | filename = url.split('/')[-1]
54 | filepath = filename
55 |
56 | print(f'Downloaded {filename}')
57 | return filepath
58 |
59 |
--------------------------------------------------------------------------------
/docs/getting_started.md:
--------------------------------------------------------------------------------
1 | # Getting started
2 |
3 | ## Installing Python and the dependencies
4 |
5 | To run this program, you will need to [install Python 3 and pip](https://realpython.com/installing-python/).
6 |
7 | When this is done, you can just run the following to install all the dependencies.
8 |
9 | ```shell
10 | pip3 install -r requirements.txt
11 | ```
12 |
13 | ## Running the script
14 |
15 | You should now be ready to run the scripts.
16 |
17 | ### Downloading the main lists
18 |
19 | Start with `download_data.py`:
20 |
21 | ```shell
22 | python3 download_data.py
23 | ```
24 |
25 | This will download a list of all the remiss processes and a list of all the associated files. It will also try to categorize these files as well as possible as:
26 | - a *remisslista*, a list of consultees published by the government
27 | - a *remissvar*, an answer from an organisation sent back to the government
28 | - another document
29 |
30 | ### Downloading and rebuilding the list of consultees
31 |
32 | ```shell
33 | python3 build_remissinstans_list.py
34 | ```
35 |
36 | This will download all the list of consultees and try to parse the content. Unfortunately, every government department has its own file structure 🤦🏼 so results may vary and the script can still be improved. For example. Finansdepartementet publishes most of its lists as scanned PDFs...
37 |
38 | ### Cleaning the data
39 |
40 | ```shell
41 | python3 clean_data.py
42 | ```
43 |
44 | Unfortunately, we have to use file names to identify the senders of the answers and these are rarely just the organisation names. In addition to all the numbers, appendices, typos, one organisation can also be named differently.
45 |
46 | The same goes for the consultees extracted from the lists.
47 |
48 | This scripts is an attempt at cleaning these organisation names. It doesn't do a perfect job and it can even be wrong or lose some useful information (ex: *Lunds universitet (Juridiska fakulteten)* -> *Lunds universitet*).
49 |
50 | This is why we don't overwrite the information but save it in new fields.
51 |
--------------------------------------------------------------------------------
/service/database.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import func
2 | from sqlalchemy.sql.functions import coalesce
3 |
4 | from database.answer import Answer
5 | from database.consultee import Consultee
6 |
7 | from database import base
8 |
9 | class Database(object):
10 |
11 | @staticmethod
12 | def name():
13 | return base.db_name
14 |
15 | @staticmethod
16 | def create_tables():
17 | base.Base.metadata.create_all(base.engine)
18 |
19 | @staticmethod
20 | def drop_tables():
21 | base.Base.metadata.drop_all(base.engine)
22 |
23 | @staticmethod
24 | def query(object):
25 | base.db_session.query(object)
26 |
27 | @staticmethod
28 | def add(object):
29 | base.db_session.add(object)
30 |
31 | @staticmethod
32 | def delete_all(table):
33 | table.query.delete()
34 |
35 | def empty_column(table, column):
36 | table.query.update({column: None})
37 |
38 | @staticmethod
39 | def flush():
40 | base.db_session.flush()
41 |
42 | @staticmethod
43 | def commit():
44 | base.db_session.commit()
45 |
46 | @staticmethod
47 | def remove():
48 | base.db_session.remove()
49 |
50 | @staticmethod
51 | def close():
52 | base.db_session.close()
53 |
54 | @staticmethod
55 | def get_popular_answering_organisations(amount):
56 | return base.db_session.query(
57 | Answer.organisation,
58 | func.count(Answer.organisation)
59 | ).group_by(
60 | Answer.organisation
61 | ).order_by(
62 | func.count(Answer.organisation).desc()
63 | ).limit(
64 | amount
65 | ).all()
66 |
67 | def __best_names(best_name):
68 | return base.db_session.query(
69 | best_name,
70 | func.count(best_name)
71 | ).group_by(
72 | best_name
73 | )
74 |
75 | @staticmethod
76 | def get_popular_names(percent):
77 | best_name = coalesce(Consultee.cleaned_name, Consultee.cleaned_name)
78 | best_names = Database.__best_names()
79 |
80 | return best_names.order_by(
81 | func.count(best_name).asc()
82 | ).limit(
83 | int(best_names.count() * percent / 100)
84 | ).all()
85 |
--------------------------------------------------------------------------------
/docs/data_structure.md:
--------------------------------------------------------------------------------
1 | # What data does this script extract?
2 |
3 | The following objects are fetched and restructured:
4 | - all the remissprocesses with the following information
5 | - title
6 | - department issuing (only the first one if there are several)
7 | - date of publication
8 | - a URL to its page on [regeringen.se](regeringen.se/remisser)
9 | - deadline (**not implemented**)
10 | - diary number (**not implemented**)
11 |
12 | In addition, we attach the following documents to every process:
13 | - a consultee list
14 | - all the answers
15 | - other documents which couldn't be identified as any of the two other categories
16 |
17 | For each consultee list, a structured list is re-generated.
18 |
19 | For each answer, the name of the issuing organisation is generated.
20 |
21 | ## Database structure
22 |
23 | To be able to store this information in a structured way, we use a SQL database with a number of tables.
24 |
25 | Here is a UML diagram of the classes used in the Python script. Note the inheritance, which means that you will have to join several tables to get all the desired columns.
26 |
27 |
28 |
29 | ## Extract data from the Database
30 |
31 | To get the data you want, you will need to use SQL queries.
32 |
33 | Here is for example the three queries I use for the three tabs of this [spreadsheet](https://docs.google.com/spreadsheets/d/1AIS7-yGfAPyUEFGaXg6gxAv2-7_Q2QQUTiKQJU7weNg/edit?usp=sharing):
34 |
35 | ### Remiss processes
36 | ```sql
37 | SELECT remiss.id, content.published_on, content.issuer, content.title, content.url AS remiss_url, file.url AS consultee_list_url
38 | FROM content, remiss, document, file
39 | WHERE content.id == remiss.id AND document.remiss_id = remiss.id AND document.type == "consultee_list" AND file.document_id == document.id
40 | UNION ALL
41 | SELECT remiss.id, content.published_on, content.issuer, content.title, content.url AS remiss_url, '' AS consultee_list_url
42 | FROM content, remiss
43 | WHERE content.id == remiss.id AND NOT EXISTS (SELECT 1
44 | FROM document
45 | WHERE document.type == "consultee_list" AND document.remiss_id == remiss.id
46 | )
47 | ```
48 |
49 | ### Answers
50 |
51 | ```sql
52 | SELECT document.id, document.remiss_id, file.name as filename, answer.organisation, file.url
53 | FROM document, answer, file
54 | WHERE document.id == answer.id AND file.document_id == document.id
55 | ```
56 |
57 | ### Consultees
58 |
59 | ```sql
60 | SELECT consultee.id, document.remiss_id, consultee.name, consultee.cleaned_name
61 | FROM document, consultee_list, consultee
62 | WHERE consultee.consultee_list_id = consultee_list.id AND document.id = consultee_list.id
63 | ```
64 |
--------------------------------------------------------------------------------
/service/web_parser.py:
--------------------------------------------------------------------------------
1 | import html
2 | from bs4 import BeautifulSoup
3 | from datetime import datetime
4 |
5 | from database.remiss import Remiss
6 | from database.answer import Answer
7 | from database.consultee_list import ConsulteeList
8 | from database.document import Document
9 | from database.file import File
10 |
11 | from service.cleaner import Cleaner
12 |
13 | REGERING_URL = 'https://www.regeringen.se'
14 |
15 |
16 | class WebParser(object):
17 |
18 | @staticmethod
19 | def get_remiss_amount(response):
20 | htmlData = html.unescape(response.decode('utf-8'))
21 | soup = BeautifulSoup(htmlData, 'html.parser')
22 |
23 | amount = soup.select_one('strong[class==filterHitCount]')
24 | return int(amount.text)
25 |
26 | @staticmethod
27 | def get_remiss_list(response):
28 | remisser = []
29 |
30 | soup = BeautifulSoup(response['Message'], 'html.parser')
31 | blocks = soup.select('div[class=sortcompact]')
32 |
33 | for block in blocks:
34 | link = block.select('a[href^="/remisser"]')
35 |
36 | if len(link) == 0:
37 | link = block.select('a[href^="/rapporter"]')
38 |
39 | if len(link) == 0:
40 | continue
41 |
42 | link = link[0]
43 |
44 | url = REGERING_URL + link['href']
45 | title = link.contents[0]
46 | date = datetime.strptime(
47 | block.select('time')[0]['datetime'],
48 | '%Y-%m-%d'
49 | )
50 | issuer = block.select('a')[-1].contents[0]
51 |
52 | remiss = Remiss(issuer=issuer,
53 | published_on=date,
54 | title=title,
55 | url=url)
56 | remisser.append(remiss)
57 |
58 | remisser.reverse()
59 | return remisser
60 |
61 | @staticmethod
62 | def get_document_list(remiss_id, response):
63 | documents = []
64 |
65 | soup = BeautifulSoup(response, 'html.parser')
66 | list = soup.select('ul[class=list--Block--icons]')
67 |
68 | def create_document(link):
69 | url = REGERING_URL + link['href']
70 | filename = link.contents[0]
71 | filename = filename[:filename.find('(pdf')]
72 |
73 | file = File(name=filename, url=url)
74 |
75 | if Cleaner.is_consultee_list(filename):
76 | return ConsulteeList(remiss_id=remiss_id, files=[file])
77 | elif Cleaner.is_other_document(filename):
78 | return Document(remiss_id=remiss_id, files=[file])
79 |
80 | return Answer(remiss_id=remiss_id, files=[file])
81 |
82 | if len(list) == 0:
83 | return []
84 | elif len(list) == 1:
85 | for link in list[0].select('a'):
86 | document = create_document(link)
87 | documents.append(document)
88 |
89 | return documents
90 | else:
91 | for link in list[0].select('a'):
92 | document = create_document(link)
93 | documents.append(document)
94 |
95 | for link in list[1].select('a'):
96 | document = create_document(link)
97 | documents.append(document)
98 |
99 | return documents
100 |
--------------------------------------------------------------------------------
/api/schema.py:
--------------------------------------------------------------------------------
1 | import graphene
2 | from graphene_sqlalchemy import SQLAlchemyObjectType
3 |
4 | from database.answer import Answer as AnswerModel
5 | from database.consultee_list import ConsulteeList as ConsulteeListModel
6 | from database.consultee import Consultee as ConsulteeModel
7 | from database.document import Document as DocumentModel
8 | from database.file import File as FileModel
9 | from database.remiss import Remiss as RemissModel
10 |
11 | from service.database import Database
12 |
13 | class FileAttribute:
14 | name = graphene.String(description="Name of the file.")
15 | url = graphene.String(description="URL of the file.")
16 |
17 |
18 | class File(SQLAlchemyObjectType):
19 | class Meta:
20 | model = FileModel
21 |
22 |
23 | class DocumentAttribute:
24 | remiss_id = graphene.Int(description="Id of the answer's remiss.")
25 | type = graphene.String(description="Type of the document.")
26 | files = graphene.List(File, description="Files of the document.")
27 |
28 |
29 | class Document(SQLAlchemyObjectType):
30 | class Meta:
31 | model = DocumentModel
32 |
33 |
34 | class AnswerAttribute:
35 | organisation = graphene.String(
36 | description="Organisation or individual which authored the answer.")
37 | remiss_id = DocumentAttribute.remiss_id
38 | type = DocumentAttribute.type
39 | files = DocumentAttribute.files
40 |
41 |
42 | class Answer(SQLAlchemyObjectType):
43 | class Meta:
44 | model = AnswerModel
45 |
46 |
47 | class ConsulteeAttribute:
48 | name = graphene.String(description="Name of the consultee.")
49 |
50 |
51 | class Consultee(SQLAlchemyObjectType):
52 | class Meta:
53 | model = ConsulteeModel
54 |
55 |
56 | class ConsulteeListAttribute:
57 | consultee_list = graphene.List(
58 | Consultee,
59 | description="List of all the consultees in the document."
60 | )
61 | remiss_id = DocumentAttribute.remiss_id
62 | type = DocumentAttribute.type
63 | files = DocumentAttribute.files
64 |
65 |
66 | class ConsulteeList(SQLAlchemyObjectType):
67 | class Meta:
68 | model = ConsulteeListModel
69 |
70 |
71 | class Remiss(SQLAlchemyObjectType):
72 | class Meta:
73 | model = RemissModel
74 |
75 |
76 | class Query(graphene.ObjectType):
77 | # Allows sorting over multiple columns, by default over the primary key
78 | answer = graphene.Field(Answer)
79 | answers = graphene.List(Answer)
80 |
81 | def resolve_answer(self, *args, **kwargs):
82 | return Database.query(AnswerModel).first()
83 |
84 | def resolve_answers(self, *args, **kwargs):
85 | return Database.query(AnswerModel).all()
86 |
87 | consultee_list = graphene.Field(ConsulteeList)
88 | consultee_lists = graphene.List(ConsulteeList)
89 |
90 | consultee = graphene.Field(Consultee)
91 | consultees = graphene.List(Consultee)
92 |
93 | document = graphene.Field(Document)
94 | documents = graphene.List(Document)
95 |
96 | file = graphene.Field(File)
97 | files = graphene.List(File)
98 |
99 | remiss = graphene.Field(Remiss)
100 | remisser = graphene.List(Remiss)
101 |
102 | def resolve_remiss(self, *args, **kwargs):
103 | return RemissModel.query.first()
104 |
105 | def resolve_remisser(self, *args, **kwargs):
106 | return RemissModel.query.all()
107 |
108 |
109 | schema = graphene.Schema(query=Query)
110 |
--------------------------------------------------------------------------------
/clean_data.py:
--------------------------------------------------------------------------------
1 | from service.database import Database
2 | from service.cleaner import Cleaner
3 | from service.file_manager import FileManager
4 | import service.wikidata as wikidata
5 | from database.remiss import Remiss
6 | from database.answer import Answer
7 | from database.document import Document
8 | from database.consultee import Consultee
9 | from database.file import File
10 | from database.consultee_list import ConsulteeList
11 |
12 | import pandas as pd
13 |
14 | saved_remisser = Remiss.query.all()
15 | saved_answers = Answer.query.all()
16 |
17 | RESET_DB = True
18 | RESET_WIKIDATA = False
19 | # GOV_LIST = 'tmp/government_organisations.csv'
20 | # if RESET_WIKIDATA or FileManager.filepath_exists(GOV_LIST):
21 | # gov_orgs = wikidata.get_government_organisations()
22 | # pd.DataFrame(gov_orgs, columns=['organisation']).to_csv(GOV_LIST)
23 |
24 | # gov_list = pd.read_csv(GOV_LIST)['organisation'].to_list()
25 |
26 | # print(gov_list)
27 |
28 | print('II-1 Light cleaning file names...')
29 | for remiss_index, remiss in enumerate(saved_remisser, start=1):
30 | answers_for_remiss = Answer.query.filter_by(remiss_id=remiss.id).all()
31 |
32 | nb_of_remisser = len(saved_remisser)
33 |
34 | for answer in answers_for_remiss:
35 | org_name = answer.files[0].name
36 |
37 | if len(answers_for_remiss) > 3:
38 | filenames = [a.files[0].name for a in answers_for_remiss]
39 |
40 | common = Cleaner.long_substr(filenames)
41 |
42 | if len(common) > 3:
43 | org_name = org_name.replace(common, '')
44 |
45 | org_name = Cleaner.light_clean(org_name)
46 |
47 | answer.organisation = org_name
48 | Database.commit()
49 | print(f'{remiss_index}/{nb_of_remisser} - Cleaned')
50 |
51 | print('II-1 Deep cleaning file names...')
52 | for remiss_index, remiss in enumerate(saved_remisser, start=1):
53 | answers_for_remiss = Answer.query.filter_by(remiss_id=remiss.id).all()
54 |
55 | nb_of_remisser = len(saved_remisser)
56 |
57 | for answer in answers_for_remiss:
58 | org_name = answer.organisation
59 |
60 | org_name = Cleaner.deep_clean(org_name)
61 |
62 | answer.organisation = org_name
63 | Database.commit()
64 | print(f'{remiss_index}/{nb_of_remisser} - Cleaned')
65 |
66 | saved_lists = Document.query.filter(Document.type == 'consultee_list').all()
67 |
68 | print('II-2 Light cleaning organisation names from consultee lists...')
69 | for document_index, consultee_list in enumerate(saved_lists, start=1):
70 | consultees_for_list = Consultee.query.filter_by(
71 | consultee_list_id=consultee_list.id
72 | ).all()
73 |
74 | nb_of_consultee_lists = len(saved_lists)
75 |
76 | for consultee in consultees_for_list:
77 | org_name = consultee.name
78 |
79 | org_name = Cleaner.light_clean(org_name)
80 |
81 | consultee.cleaned_name = org_name
82 | Database.commit()
83 | print(f'{document_index}/{nb_of_consultee_lists} - Cleaned')
84 |
85 | print('II-2 Deep cleaning organisation names from consultee lists...')
86 | for document_index, consultee_list in enumerate(saved_lists, start=1):
87 | consultees_for_list = Consultee.query.filter_by(
88 | consultee_list_id=consultee_list.id
89 | ).all()
90 |
91 | nb_of_consultee_lists = len(saved_lists)
92 |
93 | for consultee in consultees_for_list:
94 | org_name = consultee.cleaned_name
95 |
96 | org_name = Cleaner.deep_clean(org_name)
97 |
98 | consultee.cleaned_name = org_name
99 | Database.commit()
100 | print(f'{document_index}/{nb_of_consultee_lists} - Cleaned')
101 |
--------------------------------------------------------------------------------
/service/cleaner.py:
--------------------------------------------------------------------------------
1 | from service.database import Database
2 |
3 | from rapidfuzz import fuzz
4 |
5 | class Cleaner(object):
6 |
7 | def smart_ratio(name1, name2):
8 | names = [name1, name2]
9 |
10 | for i, name in enumerate(names):
11 | if '(' in name:
12 | name = name[:name.index('(')]
13 |
14 | name = name.lower()
15 | name = name.replace(' i ', '')
16 | name = name.replace(' ', '')
17 | name = name.replace('.', '')
18 | name = name.replace(',', '')
19 | names[i] = name
20 |
21 | to_replace = {
22 | 'aktiebolag': 'ab'
23 | }
24 |
25 | for i, name in enumerate(names):
26 | for word in to_replace.keys():
27 | names[i] = name.replace(word, to_replace[word])
28 |
29 | to_remove = [
30 | 'förbund',
31 | 'förening',
32 | 'sverige',
33 | 'svensk',
34 | 'företag',
35 | 'institut',
36 | 'industri',
37 | 'inspektion',
38 | ' kommun',
39 | ' stad',
40 | 'styrelse',
41 | ' ab',
42 | 'ambassad',
43 | 'råd',
44 | 'tingsrätt',
45 | 'organisation',
46 | 'universitet'
47 | ]
48 |
49 | for word in to_remove:
50 | if all(word in name for name in names):
51 | for i, name in enumerate(names):
52 | names[i] = name.replace(word, '')
53 |
54 | ratio = fuzz.ratio(names[0], names[1])
55 |
56 | return ratio if len(names[0]) >= 5 and len(names[1]) >= 5 else 0
57 |
58 | @staticmethod
59 | def closest_in_list(text, list_to_compare, tolerance):
60 |
61 | closest = ''
62 | highest_ratio = 0
63 |
64 | for name in list_to_compare:
65 | ratio = Cleaner.smart_ratio(name, text)
66 |
67 | if ratio > highest_ratio:
68 | closest = name
69 | highest_ratio = ratio
70 |
71 | if highest_ratio > tolerance:
72 | print(f'{highest_ratio} – {text} --> {closest}')
73 | return closest
74 |
75 | @staticmethod
76 | def replace_by_popular(text, tolerance):
77 | popular_names = [name[0] for name in Database.get_popular_names(100 - tolerance)]
78 |
79 | return Cleaner.closest_in_list(text, popular_names, tolerance)
80 |
81 | @staticmethod
82 | def remove_leading_characters(text):
83 | return text.lstrip('0123456789abc.-_ abc ')
84 |
85 | @staticmethod
86 | def remove_trailing_characters(text):
87 | return text.rstrip('0123456789.-_ ')
88 |
89 | @staticmethod
90 | def remove_line_breaks(text):
91 | return text.replace('\n', '').replace('\r', '')
92 |
93 | @staticmethod
94 | def replace_by_popular_contained(text):
95 | q = Database.get_popular_answering_organisations(250)
96 | popular_org_names = [r[0] for r in q]
97 |
98 | for popular_org_name in popular_org_names:
99 | if popular_org_name in text:
100 | if popular_org_name != text:
101 | print(f'{text} -> {popular_org_name}')
102 | text = popular_org_name
103 | break
104 | return text
105 |
106 | @staticmethod
107 | def light_clean(text):
108 | text = Cleaner.remove_leading_characters(text)
109 | text = Cleaner.remove_trailing_characters(text)
110 | return text
111 |
112 | @staticmethod
113 | def deep_clean(text):
114 | text = Cleaner.replace_by_popular_contained(text)
115 | return text
116 |
117 | @staticmethod
118 | def is_consultee_list(filename):
119 | return any(s in filename for s in [ 'Remissmissiv',
120 | 'Remisslista',
121 | 'Remiss av'
122 | ])
123 |
124 | @staticmethod
125 | def is_other_document(filename):
126 | return not Cleaner.is_consultee_list(filename) and \
127 | ('Remissammanställning' in filename
128 | or 'Remissbrev' in filename
129 | or 'Promemoria' in filename
130 | or 'Remiss-PM' in filename
131 | or 'Remiss av' in filename
132 | or 'Inbjudan' in filename)
133 |
134 | @staticmethod
135 | def long_substr(data):
136 | substr = ''
137 | if len(data) > 1 and len(data[0]) > 0:
138 | for i in range(len(data[0])):
139 | for j in range(len(data[0])-i+1):
140 | if (j > len(substr)
141 | and all(data[0][i:i+j] in x for x in data)):
142 | substr = data[0][i:i+j]
143 | return substr
144 |
--------------------------------------------------------------------------------
/service/document_parser.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | import pandas as pd
4 | from pikepdf import Pdf
5 |
6 | from service.ocr import OCR
7 | from service.tabula_parser import TabulaParser
8 |
9 |
10 | class DocumentParser(object):
11 |
12 | @staticmethod
13 | def extract_list(filename):
14 | first_page = TabulaParser.extract_first_page(filename)
15 | next_pages = TabulaParser.extract_next_pages(filename)
16 |
17 | if first_page is None and next_pages is None:
18 | return
19 |
20 | all_pages = first_page + next_pages
21 |
22 | if (DocumentParser.has_scanned_pages(filename, all_pages)
23 | and '-ocr.pdf' not in filename):
24 | print('Document is at least partly a scan, attempting ocr...')
25 | filename = OCR.ocr(filename)
26 |
27 | return DocumentParser.extract_list(filename)
28 |
29 | all_rows = DocumentParser.pick_right_columns(all_pages)
30 | all_rows = all_rows.tolist()
31 |
32 | start = DocumentParser.detect_start(all_rows)
33 |
34 | if not start:
35 | print('Document is most likely not a remissinstans.')
36 |
37 | if '-ocr.pdf' not in filename:
38 | print('Attempting a scan in case it fixes an issue...')
39 | filename = OCR.ocr(filename)
40 |
41 | return DocumentParser.extract_list(filename)
42 |
43 | return
44 |
45 | consultee_list = all_rows[start:]
46 |
47 | end = DocumentParser.detect_end(consultee_list)
48 |
49 | if end:
50 | consultee_list = consultee_list[:end]
51 |
52 | consultee_list = DocumentParser.remove_page_numbers(consultee_list)
53 | consultee_list = DocumentParser.remove_footer_lines(consultee_list)
54 | consultee_list = DocumentParser.remove_leading_numbers(consultee_list)
55 | consultee_list = DocumentParser.remove_leading_spaces(consultee_list)
56 | consultee_list = DocumentParser.merge_multiline(consultee_list)
57 | consultee_list = DocumentParser.remove_trailing_comma(consultee_list)
58 | consultee_list = DocumentParser.remove_last_paragraph(consultee_list)
59 |
60 | return consultee_list
61 |
62 | @staticmethod
63 | def has_scanned_pages(filename, all_pages):
64 | return all_pages and len(all_pages) < len(Pdf.open(filename).pages)
65 |
66 | @staticmethod
67 | def pick_right_columns(df_list):
68 | all_rows = pd.Series(dtype=pd.StringDtype())
69 |
70 | for df in df_list:
71 | right_column = df[df.columns[0]]
72 |
73 | len_right_column = right_column.astype(str).str.len().sum()
74 |
75 | for i in range(1, len(df.columns)):
76 | column = df[df.columns[i]]
77 | len_column = column.astype(str).str.len().sum()
78 |
79 | if len_column > len_right_column:
80 | len_right_column = len_column
81 | right_column = column
82 |
83 | all_rows= pd.concat([all_rows, right_column])
84 |
85 | return all_rows.dropna()
86 |
87 | @staticmethod
88 | def detect_start(rows):
89 | for i, s in enumerate(rows):
90 | words = ['remissinstans', 'sändlista']
91 |
92 | if (any(word in str(s).lower() for word in words)
93 | and len(s.split()) <= 2):
94 | return i + 1
95 |
96 | return None
97 |
98 | @staticmethod
99 | def detect_end(rows):
100 | for i, s in enumerate(rows):
101 | words = ['remiss', 'remitt', 'betänkande', ' har ']
102 |
103 | if any(word in str(s).lower() for word in words):
104 | return i
105 |
106 | return None
107 |
108 | @staticmethod
109 | def remove_page_numbers(rows):
110 | i = 0
111 | while i < len(rows):
112 | if re.match('[0-9]{1,2} \([0-9]{1,2}\)', rows[i]):
113 | del rows[i]
114 | i -= 1
115 |
116 | i += 1
117 |
118 | return rows
119 |
120 | @staticmethod
121 | def remove_footer_lines(rows):
122 | i = 0
123 | while i < len(rows):
124 | row = rows[i]
125 | words = [
126 | 'telefonväxel',
127 | 'postadress',
128 | 'fax:',
129 | 'besöksadress',
130 | '08-405',
131 | 'webb:',
132 | '33 st'
133 | ]
134 |
135 | if any(word in str(row).lower() for word in words):
136 | del rows[i]
137 | i -= 1
138 |
139 | i += 1
140 |
141 | return rows
142 |
143 | @staticmethod
144 | def remove_leading_numbers(rows):
145 | for i in range(len(rows)):
146 | row = rows[i]
147 | if '.' in row[:5]:
148 | num = row[:row.index('.')]
149 | num = num.replace('l', '1')
150 | num = num.replace('O', '0')
151 | num = num.replace(' ', '')
152 |
153 | row = num + row[row.index('.'):]
154 |
155 |
156 | row = re.sub(r'^\d{1,3}\.', '', row) # Remove '1. ', '2. ', '3. '...
157 | row = re.sub(r'^\d{1,3}\s', '', row) # Remove '1 ', '2 ', '3 '...
158 | rows[i] = row
159 |
160 | return rows
161 |
162 | @staticmethod
163 | def remove_leading_spaces(rows):
164 | return [row.lstrip() for row in rows]
165 |
166 | @staticmethod
167 | def merge_multiline(rows):
168 | i = 0
169 | while i < len(rows):
170 | if i < len(rows):
171 | row = rows[i]
172 | else:
173 | continue
174 |
175 | if row:
176 | r = row[0]
177 | else:
178 | i += 1
179 | continue
180 |
181 | #if rows[i - 1][-1:] == ',' and row[-1:] != ',':
182 | # # Trailing comma that doesn't seem to be the norm
183 | # rows[i - 1] += ' ' + row
184 | # del rows[i]
185 |
186 | if (')' in row
187 | and '(' not in row):
188 | # Unclosed parenthesis
189 | rows[i - 1] += ' ' + rows[i]
190 | del rows[i]
191 | continue
192 |
193 | if (i > 0
194 | and not r.isupper() # If not capital letter
195 | and len(rows[i - 1]) > 60): # and the previous row is long
196 | if rows[i - 1].endswith('-'):
197 | # Merges word split with '-'
198 | rows[i - 1] = rows[i - 1][:-1] + row
199 | else:
200 | # Merges lines cut between two words
201 | rows[i - 1] += ' ' + row
202 |
203 | del rows[i]
204 | continue
205 | i += 1
206 | return rows
207 |
208 | @staticmethod
209 | def remove_trailing_comma(rows):
210 | return [row.rstrip(',') for row in rows]
211 |
212 | @staticmethod
213 | def remove_last_paragraph(rows):
214 | for i, s in enumerate(rows):
215 | if len(s.split()) >= 17:
216 | if ('(' not in s or ')' not in s
217 | or len(s[s.index('('):s.index(')')]) / len(s) < 0.5):
218 | return rows[:i]
219 |
220 | return rows
221 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This code is the result of a **[Civic Tech](https://civictech.se) hackathon in Göteborg in September 2018** 🤓.
2 | It was written by [Emil Hemdal](https://github.com/emilhem), Albin and [Pierre Mesure](https://github.com/PierreMesure).
3 |
4 | # What does it do? 🖨
5 |
6 | This is a script that scraps data from [regeringen.se](regeringen.se).
7 | For now, it only looks for [remisser](https://sv.wikipedia.org/wiki/Remiss),
8 | lists them and builds a dataset containing information about these remissprocesses.
9 |
10 | You can read more on how to run the script and which data it saves.
11 |
12 | The result is saved in an SQL database.
13 |
14 | # Why? 📕📗📘
15 |
16 |
17 |
18 | **Regeringskansliet**, the Swedish government's chancellery, has very little open data.
19 | Theoretically, all of their documents are available publicly on [regeringen.se](regeringen.se),
20 | but a weak search engine (which doesn't search for keywords through the content of the page or documents) and the lack of structured data (most of the documents are available as PDF with various formattings)
21 | make it virtually impossible for journalists, researchers and activists from civil society to delve in this information and scrutinize the government's actions.
22 |
23 | Apart from this valuable work by counterpowers, this lack of open structured data also prevents civil servants from working efficiently
24 | and other public agencies to use the information released.
25 |
26 | The Swedish parliament, **Riksdagen**, includes some of the government's documents on their website (bills, [SOUs](https://en.wikipedia.org/wiki/Statens_offentliga_utredningar))
27 | but they get this as PDF from Regeringskansliet and have to parse the content to display it, making it harder for them to inform citizens.
28 |
29 | The end result is impossible to use in a good way.
30 | Formatting is lost, page numbers and tables get inserted in the text and no structure is preserved.
31 | See example [here](http://www.riksdagen.se/sv/dokument-lagar/dokument/proposition/ett-klimatpolitiskt-ramverk-for-sverige_H403146/html).
32 |
33 | # Goal 🎯
34 |
35 | Our goal with this small script is to show how ridiculously hard it is to find simple information such as:
36 | - which organisations does the government ask?
37 | - which organisations answer?
38 | - how many times have they asked each organisation and how many times do they answer?
39 |
40 | Statistical information would already help counterpowers to say who the government is picking to help them to shape a bill.
41 | Big interest groups? NGOs? Local associations? These are important democratic issues.
42 |
43 | And that would only require a structured list of remisser and remisssvar.
44 |
45 | If Regeringskansliet was also publishing remissvar's content in a structured format, techniques such as semantic analysis
46 | could be applied to analyze the proximity of a remissvar and a bill to determine which organisations influenced most.
47 | This is already done to study the impact of lobbying in the [EU](https://www.politico.eu/article/7-tools-on-eu-governance-brussels-lobbying-governance-open-data/)
48 | and the [US](https://www.frontiersin.org/articles/10.3389/fdata.2018.00003/full) parliaments.
49 |
50 | # First results 📊
51 |
52 | ** EDIT: The script has now been improved and you can find better updated results in this [spreadsheet](https://docs.google.com/spreadsheets/d/1AIS7-yGfAPyUEFGaXg6gxAv2-7_Q2QQUTiKQJU7weNg/edit?usp=sharing).**
53 | The hackathon was just one day and we realised while doing it that the quality of the "data" was poorer than expected:
54 | - [regeringen.se](regeringen.se) only shows the last 894 remisser, the oldest one being from the 02/04/2015. We harvested the name and link of 23353 attached files.
55 | - we used the file names as the name of the organisation (for lack of something better) and although that worked most of the time,
56 | a lot of names include a typo (`Stockholm universitet` instead of `Stockholms universitet`), a number (`35. Stockholms universitet`)
57 | or something else which requires manual cleaning of the data.
58 | - we had no choice but to group local branches of national organisations (`LO Dalarna` becoming `LO`) and suborganisations (`Sverigesingenjörer`, `Sveriges Läkarförbund`, etc. becoming `SACO`, which explains the high number for them as they usually send their answers separately for each remiss)
59 |
60 | However, we managed to get a shortlist of organisations sorted by which answers the most to remisser,
61 | and we filtered it manually to show only interest groups:
62 |
63 | # 🏆
64 |
65 | | Rank | Organisation | # |
66 | | -- | --------------------------- | -- |
67 | | 🥇 | Sveriges advokatsamfund | 124 |
68 | | 🥈 | Svenskt näringsliv | 118 |
69 | | 🥉 | SACO | 115 |
70 | | 4 | LO | 86 |
71 | | 5 | Företagarna | 80 |
72 | | 6 | Lantbrukarnas Riksförbund | 73 |
73 | | 7 | Fastighetsägarna | 57 |
74 | | 7 | Skogsindustrierna | 54 |
75 | | 9 | Näringslivets Regelnämnd | 52 |
76 | | 10 | Avfall Sverige | 48 |
77 | | 10 | Svenska Bankföreningen | 48 |
78 | | 12 | Sveriges Byggindustrier | 47 |
79 | | 13 | Svenska kyrkan | 43 |
80 | | 14 | Naturskyddsföreningen | 40 |
81 | | 15 | Svensk Handel | 39 |
82 | | 16 | Energigas Sverige | 33 |
83 | | 17 | Energiföretagen Sverige | 30 |
84 | | 18 | Svensk Försäkring | 30 |
85 | | 19 | BIL Sweden | 28 |
86 | | 20 | Villaägarnas Riksörbund | 28 |
87 |
88 | You can run the script yourself to get the raw data or find it in this Google [spreadsheet](https://docs.google.com/spreadsheets/d/1AIS7-yGfAPyUEFGaXg6gxAv2-7_Q2QQUTiKQJU7weNg/edit?usp=sharing). Don't hesitate to use it to make your own rankings and visualisations.
89 |
90 | ## What does that show us? 🧐
91 |
92 | There's really no conclusion we can jump to by seeing that **Svenskt näringsliv** answers to more remisser than **LO**. But as basic as this information can be, the fact that you have to know how to code and spend a Sunday in front of a screen to access it shows us a lack of transparency.
93 |
94 | In just one day, we didn't manage to extract, clean and restructure enough data to make conclusions on which organisations the government listens to most. But we hope it will motivate others to dive into more of this data and create more robust models to answer that question and more!
95 |
96 | # How can I contribute? 🙌
97 |
98 | Did we manage to get your attention with this small demo?
99 | Do you want to see more insights on all the information that Regeringskansliet has but doesn't publish in a usable format?
100 |
101 | There are 3 ways you can help:
102 | - if you can script, fork this project and try to fetch and analyse more data from [regeringen.se](regeringen.se)!
103 | Write some code to clean the data or to visualise it! 👩🏽💻
104 | - if you can't but have a profession/occupation which would benefit from having this data available (journalist, politician, researcher),
105 | contact the government to ask them to release it! Explain to them what you could do with it. 👨🏻⚕️
106 | - ask the government to reform its [offentlighetsprincip](https://sv.wikipedia.org/wiki/Offentlighetsprincipen)
107 | to require that any piece of public data be available online in a structured format.
108 | Canada, the UK, Germany or France are doing it, it's time for Sweden to catch up! 🙋🏻♀️
109 |
110 | And don't hesitate to contact us, we love hearing from opengov enthusiasts! ❤️
111 |
--------------------------------------------------------------------------------
/test/service/test_document_parser.py:
--------------------------------------------------------------------------------
1 | from service.document_parser import DocumentParser
2 |
3 | def assert_document_parser(filepath,
4 | expected_result):
5 | assert DocumentParser.extract_list(filepath) == expected_result
6 |
7 | def assert_document_parser_size(filepath,
8 | expected_size):
9 | assert len(DocumentParser.extract_list(filepath)) == expected_size
10 |
11 | def test_with_pdf_1():
12 | # Socialdepartementet/2019
13 | expected_result = [
14 | 'Autism- och Aspergerförbundet',
15 | 'Barnombudsmannen',
16 | 'Biobank Sverige',
17 | 'Blekinge läns landsting',
18 | 'Dalarnas läns landsting',
19 | 'Datainspektionen',
20 | 'Etikprövningsmyndigheten',
21 | 'FUB',
22 | 'Funktionsrätt Sverige',
23 | 'Förvaltningsrätten i Göteborg',
24 | 'Gotlands kommun',
25 | 'Gävleborgs läns landsting',
26 | 'Göteborgs universitet',
27 | 'Hallands läns landsting',
28 | 'Hälso- och sjukvårdens ansvarsnämnd (HSAN)',
29 | 'Inspektionen för vård och omsorg (IVO)',
30 | 'Judiska Centralrådet',
31 | 'Justitiekanslern',
32 | 'Jämtlands läns landsting',
33 | 'Jönköpings läns landsting',
34 | 'Kalmar läns landsting',
35 | 'Karolinska institutet',
36 | 'Kronobergs läns landsting',
37 | 'Landstingens Ömsesidiga Försäkringsbolag (LÖF)',
38 | 'Livet som gåva',
39 | 'Lunds universitet',
40 | 'MOD Merorgandonation',
41 | 'Norrbottens läns landsting',
42 | 'Njurförbundet',
43 | 'Pensionärernas Riksorganisation (PRO)',
44 | 'Riksdagens ombudsmän (JO)',
45 | 'Rättsmedicinalverket',
46 | 'Skåne läns landsting',
47 | 'Socialstyrelsen',
48 | 'SPF Seniorerna',
49 | 'Statens beredning för medicinsk och social utvärdering (SBU)',
50 | 'Statens medicinsk-etiska råd (Smer)',
51 | 'Stockholms läns landsting',
52 | 'Svenska kyrkan',
53 | 'Svenska läkaresällskapet',
54 | 'Svensk sjuksköterskeförening',
55 | 'Sveriges Kommuner och Landsting (SKL)',
56 | 'Sveriges kristna råd',
57 | 'Sveriges läkarförbund',
58 | 'Sveriges Muslimska Råd',
59 | 'Sveriges psykologförbund',
60 | 'Södermanlands läns landsting',
61 | 'Södertörns tingsrätt',
62 | 'Uppsala läns landsting',
63 | 'Uppsala universitet',
64 | 'Vårdförbundet',
65 | 'Värmlands läns landsting',
66 | 'Västerbottens läns landsting',
67 | 'Västernorrlands läns landsting',
68 | 'Västmanlands läns landsting',
69 | 'Västra Götalands läns landsting',
70 | 'Vävnadsrådet',
71 | 'Örebro läns landsting',
72 | 'Östergötlands läns landsting'
73 | ]
74 | assert_document_parser('tmp/1/1.pdf',
75 | expected_result)
76 |
77 | def test_with_pdf_2():
78 | # Arbetsmarknadsdepartementet/2019
79 | expected_result = [
80 | 'Alla Kvinnors Hus Karlstad',
81 | 'Alvesta kommun',
82 | 'Barnombudsmannen',
83 | 'Borgholm kommun',
84 | 'Brottsofferjouren Sverige',
85 | 'Brottsoffermyndigheten',
86 | 'Domstolsverket',
87 | 'Falu kommun',
88 | 'Freezonen (Kvinnojouren, Tjejjouren och Brottsofferjouren i Sydöstra Skåne)',
89 | 'Förvaltningsrätten i Stockholm',
90 | 'Förvaltningsrätten i Umeå',
91 | 'Förvaltningsrätten i Uppsala',
92 | 'Gällivare kommun',
93 | 'Göteborgs kommun',
94 | 'Habo kommun',
95 | 'Helsingborgs kommun',
96 | 'Härnösands kommun',
97 | 'Hässleholms kommun',
98 | 'Jämställdhetsmyndigheten',
99 | 'Kammarrätten i Jönköping',
100 | 'Klippan kommun',
101 | 'Konkurrensverket',
102 | 'Kungsbacka kommun',
103 | 'Kvinnojouren – en fristad i ingenmansland',
104 | 'Kvinnojouren Sigtuna',
105 | 'Kvinnors nätverk',
106 | 'Landskrona kommun',
107 | 'Lerum kommun',
108 | 'Länsstyrelsen i Norrbotten',
109 | 'Länsstyrelsen i Skåne län',
110 | 'Länsstyrelsen i Västra Götalands län',
111 | 'Länsstyrelsen i Östergötland',
112 | 'Malmö kommun',
113 | 'Motala kommun',
114 | 'Myndigheten för ungdoms- och civilsamhällesfrågor (MUCF)',
115 | 'Män',
116 | 'Nordmaling kommun',
117 | 'Riksförbundet för homosexuellas, bisexuellas, transpersoners och queeras rättigheter (RFSL)',
118 | 'Rikskriscentrum, Sveriges professionella kriscentra för män',
119 | 'Riksorganisationen Glöm aldrig Pela och Fadime (GAPF)',
120 | 'Riksföreningen Stödcentrum mot incest och andra sexuella övergrepp (Rise)',
121 | 'Riksorganisationen för kvinnojourer och tjejjourer i Sverige (Roks)',
122 | 'Ronneby kommun',
123 | 'Rädda Barnens riksförbund',
124 | 'Sigtuna kommun',
125 | 'Simrishamns kommun',
126 | 'Skyddsjouren i Ängelholm',
127 | 'Socialstyrelsen',
128 | 'Sollentuna kommun',
129 | 'Sollentuna kvinnojour',
130 | 'Stadsmissionen',
131 | 'Stiftelsen Manscentrum i Stockholm',
132 | 'Stockholms läns landsting',
133 | 'Stockholms kommun',
134 | 'Stockholms tjejjour',
135 | 'Sunne kommun',
136 | 'Sveriges Kommuner och Landsting',
137 | 'Sveriges kvinnolobby',
138 | 'Södermanlands läns landsting',
139 | 'Talita',
140 | 'Terrafem',
141 | 'Tjejjouren Väst',
142 | 'Tjejzonen',
143 | 'Tranås kommun',
144 | 'Trelleborgs kommun',
145 | 'Tjejers rätt i samhället (TRIS)',
146 | 'Ulricehamns kommun',
147 | 'Unizon',
148 | 'Upphandlingsmyndigheten',
149 | 'Vara kommun',
150 | 'Värmlands mansforum',
151 | 'Västerbottens läns landsting',
152 | 'Västerås kommun',
153 | 'Västra Götalands läns landsting',
154 | 'Åsele kommun',
155 | 'Östersunds kommun'
156 | ]
157 | assert_document_parser('tmp/2/47.pdf',
158 | expected_result)
159 |
160 | def test_with_pdf_3():
161 | # Kulturdepartementet/2019
162 | assert_document_parser_size('tmp/3/97.pdf', 90)
163 |
164 | def test_with_pdf_4():
165 | # Kulturdepartementet/2019
166 | assert_document_parser_size('tmp/4/162-ocr.pdf', 275)
167 |
168 | def test_with_pdf_84():
169 | # Finansdepartementet/2020
170 | assert_document_parser_size('tmp/84/3365.pdf', 49)
171 |
172 | def test_with_pdf_158():
173 | # Finansdepartementet/2020
174 | assert_document_parser_size('tmp/158/6290.pdf', 162)
175 |
176 | def test_with_pdf_162():
177 | # Finansdepartementet/2020
178 | assert_document_parser_size('tmp/162/6477.pdf', 29)
179 |
180 | def test_with_pdf_174():
181 | # Finansdepartementet/2020
182 | assert_document_parser_size('tmp/174/6902.pdf', 37)
183 |
184 | def test_with_pdf_187():
185 | # Utbildningsdepartementet/2020
186 | assert_document_parser_size('tmp/187/7444.pdf', 109)
187 |
188 | def test_with_pdf_207():
189 | # Justitiedepartementet/2020
190 | assert_document_parser_size('tmp/207/8247.pdf', 93)
191 |
192 | def test_with_pdf_255():
193 | # Infrastrukturdepartementet/2020
194 | assert_document_parser_size('tmp/255/10204.pdf', 13)
195 |
196 | def test_with_pdf_271():
197 | # Miljö- och energidepartementet/2019
198 | assert_document_parser_size('tmp/271/10795.pdf', 154)
199 |
200 | def test_with_pdf_305():
201 | # Infrastrukturdepartementet/2020
202 | assert_document_parser_size('tmp/305/12211.pdf', 8)
203 |
204 | def test_with_pdf_443():
205 | # Socialdepartementet/2020
206 | assert_document_parser_size('tmp/443/18259.pdf', 77)
207 |
208 | def test_with_pdf_452():
209 | # Kulturdepartementet/2020
210 | assert_document_parser_size('tmp/452/18629.pdf', 88)
211 |
212 | def test_with_pdf_554():
213 | # Försvarsdepartementet/2021
214 | assert_document_parser_size('tmp/554/23075.pdf', 11)
215 |
216 | def test_with_pdf_642():
217 | # Justitiedepartementet/2021
218 | assert_document_parser_size('tmp/642/26836.pdf', 50)
219 |
220 | def test_with_pdf_885():
221 | # Justitiedepartementet/2022
222 | assert_document_parser_size('tmp/885/37864.pdf', 25)
223 |
224 | def test_with_pdf_1057():
225 | # Justitiedepartementet/2015
226 | assert_document_parser_size('tmp/1057/43258-ocr.pdf', 31)
227 |
228 | def test_with_pdf_1073():
229 | # Näringsdepartementet/2015
230 | assert_document_parser_size('tmp/1073/43584-ocr.pdf', 77)
231 |
232 | def test_with_pdf_1114():
233 | # Miljö- och energidepartementet/2015
234 | assert_document_parser_size('tmp/1114/44311.pdf', 16)
235 |
236 | def test_with_pdf_1201():
237 | # Justitiedepartementet/2015
238 | assert_document_parser_size('tmp/1201/46516-ocr.pdf', 29)
239 |
240 | def test_with_pdf_1259():
241 | # Finansdepartementet/2016
242 | assert_document_parser_size('tmp/1259/47863.pdf', 32 )
243 |
244 | def test_with_pdf_1262():
245 | # Justitiedepartementet/2016
246 | assert_document_parser_size('tmp/1262/47866.pdf', 62)
247 |
248 | def test_with_pdf_1334():
249 | # Näringsdepartementet/2016
250 | assert_document_parser_size('tmp/1334/50171.pdf', 148)
251 |
252 | def test_with_pdf_1356():
253 | # Kulturdepartementet/2016
254 | assert_document_parser_size('tmp/1356/50961.pdf', 123)
255 |
256 | def test_with_pdf_1368():
257 | # Justitiedepartementet/2016
258 | assert_document_parser_size('tmp/1368/51107.pdf', 75)
259 |
260 | def test_with_pdf_1401():
261 | # Justitiedepartementet/2016
262 | assert_document_parser_size('tmp/1401/52269.pdf', 24)
263 |
264 | def test_with_pdf_1460():
265 | # Utbildningsdepartementet/2017
266 | assert_document_parser_size('tmp/1460/53654.pdf', 89)
267 |
268 | def test_with_pdf_1549():
269 | # Miljö- och energidepartementet/2017
270 | assert_document_parser_size('tmp/1549/56528.pdf', 128)
271 |
272 | def test_with_pdf_1597():
273 | # Näringsdepartementet/2017
274 | assert_document_parser_size('tmp/1597/57682.pdf', 103)
275 |
276 | def test_with_pdf_1864():
277 | # Näringsdepartementet/2018
278 | assert_document_parser_size('tmp/1864/67023.pdf', 159)
279 |
280 | def test_with_pdf_1949():
281 | # Infrastrukturdepartementet/2019
282 | assert_document_parser_size('tmp/1949/70170.pdf', 27)
283 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/illustration.svg:
--------------------------------------------------------------------------------
1 |
101 |
--------------------------------------------------------------------------------