Skip to content

Instantly share code, notes, and snippets.

@bemxio
Last active July 13, 2025 23:58
Show Gist options
  • Select an option

  • Save bemxio/754859b6b4d1b73eaefb4dba2b02ac41 to your computer and use it in GitHub Desktop.

Select an option

Save bemxio/754859b6b4d1b73eaefb4dba2b02ac41 to your computer and use it in GitHub Desktop.
A Python script for generating a horizontal bar chart of signatures divided by the threshold per country for a given ECI (European Citizens' Initiative) initiative. Requires `matplotlib`, `beautifulsoup4` and `requests` to be installed.
#!/usr/bin/python3
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
"""
from argparse import ArgumentParser
from datetime import datetime
from pathlib import Path
import matplotlib.pyplot as plt
import requests
import bs4
ECI_API_URL = "https://register.eci.ec.europa.eu/core/api/register/details"
THRESHOLDS_URL = "https://citizens-initiative.europa.eu/thresholds_en"
WHITESPACE_CHARACTERS = str.maketrans("", "", "\xa0\x20")
COUNTRY_CODES = {
"AT": "Austria", "BE": "Belgium", "BG": "Bulgaria",
"HR": "Croatia", "CY": "Cyprus", "CZ": "Czechia",
"DK": "Denmark", "EE": "Estonia", "FI": "Finland",
"FR": "France", "DE": "Germany", "GR": "Greece",
"HU": "Hungary", "IE": "Ireland", "IT": "Italy",
"LV": "Latvia", "LT": "Lithuania", "LU": "Luxembourg",
"MT": "Malta", "NL": "Netherlands", "PL": "Poland",
"PT": "Portugal", "RO": "Romania", "SK": "Slovakia",
"SI": "Slovenia", "ES": "Spain", "SE": "Sweden"
}
COUNTRY_NAMES = {value: key for key, value in COUNTRY_CODES.items()}
DIMENSIONS = (11.7, 8.3)
DPI = 100
def get_initiative_data(url: str) -> dict:
with requests.get(f"{ECI_API_URL}/{url[-14:-3]}") as response:
if response.status_code != 200:
raise ValueError(f"request failed with status code {response.status_code}")
data = response.json()
return data
def get_thresholds(registration_date: datetime) -> dict:
thresholds = {}
with requests.get(THRESHOLDS_URL) as response:
if response.status_code != 200:
raise ValueError(f"request failed with status code {response.status_code}")
soup = bs4.BeautifulSoup(response.content, "html.parser")
index = 0
for header in soup.find_all("h2"):
words = header.text.split()
if words[8] == "on":
if datetime.strptime(words[11], "%d/%m/%Y") <= registration_date:
break
elif words[8] == "between":
if datetime.strptime(words[9], "%d/%m/%Y") <= registration_date <= datetime.strptime(words[11], "%d/%m/%Y"):
break
index += 1
table = soup.find_all("table")[index]
for row in table.tbody.children:
thresholds[COUNTRY_NAMES[row.contents[0].text]] = int(row.contents[1].text.translate(WHITESPACE_CHARACTERS))
return thresholds
def get_entry_value(entry: dict) -> float:
return entry["total"] / thresholds[entry["countryCodeType"]]
def get_date_difference(start_date: datetime, end_date: datetime) -> str:
difference = (end_date - start_date).days
if difference == 0:
return "today"
elif difference < 0:
return f"in {-difference:,} day{"s" if difference != -1 else ""}"
else:
return f"{difference:,} day{"s" if difference != 1 else ""} ago"
if __name__ == "__main__":
parser = ArgumentParser(description="Generate a horizontal bar chart of signatures divided by the threshold per country for a given ECI initiative.")
parser.add_argument("url", help="The URL to the initiative on the ECI website.")
parser.add_argument("--output_path", "-o", type=Path, help="Path to the output file. Defaults to `<common registration number>.png`.")
args = parser.parse_args()
current_date = datetime.today()
data = get_initiative_data(args.url)
crn = data["comRegNum"]
name = data["linguisticVersions"][0]["title"]
total = data["sosReport"]["totalSignatures"]
registration_date = datetime.strptime(data["registrationDate"], "%d/%m/%Y")
start_date = datetime.strptime(data["startCollectionDate"], "%d/%m/%Y")
deadline = datetime.strptime(data["deadline"], "%d/%m/%Y")
thresholds = get_thresholds(registration_date)
achieved_count = 0
labels = []
values = []
percentages = []
for entry in sorted(data["sosReport"]["entry"], key=get_entry_value):
label = COUNTRY_CODES[entry["countryCodeType"]]
value = get_entry_value(entry)
percentage = f"{value * 100:.2f}%"
if value >= 1.0:
achieved_count += 1
labels.append(label)
values.append(min(value, 1.0))
percentages.append(percentage)
fig, ax = plt.subplots()
ax.set_title(f"Signatures divided by threshold per country for initiative \"{name}\" as of {current_date.strftime("%d/%m/%Y")}")
ax.set_xlabel("Signatures / Threshold")
ax.annotate(
f"Start of the collection period: {start_date.strftime("%d/%m/%Y")} ({get_date_difference(start_date, current_date)})\nDeadline: {deadline.strftime("%d/%m/%Y")} ({get_date_difference(deadline, current_date)})",
xy=(-0.1, -0.1), xycoords="axes fraction",
ha="left", va="center",
fontsize=10
)
ax.annotate(
f"Total signatures: {total:,}/1,000,000 ({total / 10000:.2f}%)\nCountries above threshold: {achieved_count} out of 7 required",
xy=(1.1, -0.1), xycoords="axes fraction",
ha="right", va="center",
fontsize=10
)
chart = ax.barh(labels, values)
ax.bar_label(chart, labels=percentages, color="white", padding=5, bbox={"facecolor": "white", "edgecolor": "white"})
ax.bar_label(chart, labels=percentages, color="black", padding=5)
ax.set_xlim(right=1.0)
fig.set_size_inches(DIMENSIONS)
fig.set_dpi(DPI)
fig.tight_layout()
plt.savefig(args.output_path or f"{crn}.png")
#plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment