forked from openinframap/openinframap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.py
145 lines (122 loc) · 5.02 KB
/
data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import json
import re
import aiohttp
from async_lru import alru_cache
from starlette.exceptions import HTTPException
from config import database
from itertools import chain
from more_itertools import windowed
VOLTAGE_SCALE = [0, 10, 25, 52, 132, 220, 330, 550]
async def get_countries():
return await database.fetch_all(
query="""SELECT "union" FROM countries.country_eez
WHERE "union" != \'Antarctica\'
AND pol_type IN (\'Union EEZ and country\', \'Landlocked country\')
ORDER BY "union" ASC"""
)
async def get_plant(plant_id, country_gid):
res = await database.fetch_one(
"""SELECT osm_id, ST_GeometryType(geometry) AS geom_type, name, tags->'name:en' AS name_en, source,
convert_power(tags->'plant:output:electricity') AS output,
hstore_to_json(tags) AS tags
FROM power_plant, countries.country_eez
WHERE gid = :country_gid
AND power_plant.osm_id = :plant_id
AND ST_Contains(country_eez.geom, ST_Transform(power_plant.geometry, 4326))""",
{"plant_id": plant_id, "country_gid": country_gid},
)
if res is None:
return None
res = dict(res)
res["tags"] = json.loads(res["tags"])
return res
async def get_plant_generator_summary(plant_id):
res = await database.fetch_all(
"""SELECT g.source,
convert_power(g.tags->'generator:output:electricity') AS output,
sum(convert_power(g.tags->'generator:output:electricity')) AS total_output, count(*)
FROM osm_power_generator g, osm_power_plant p
WHERE p.osm_id = :plant_id and ST_Contains(p.geometry, g.geometry)
GROUP BY g.source, convert_power(g.tags->'generator:output:electricity')""",
{"plant_id": plant_id},
)
if not res and plant_id < 0:
res = await database.fetch_all(
"""SELECT tags->'generator:source' AS source,
convert_power(tags->'generator:output:electricity') AS output,
sum(convert_power(tags->'generator:output:electricity')) AS total_output, count(*)
FROM osm_power_plant_relation_member
WHERE osm_id = :plant_id
AND tags->'power' = 'generator'
GROUP BY source, convert_power(tags->'generator:output:electricity')
""",
{"plant_id": plant_id},
)
return res
async def stats_power_line(country=None):
stats_date = (await database.fetch_one("SELECT max(time) FROM stats.power_line"))[0]
values = {"time": stats_date}
country_clause = ""
if country:
country_clause = " AND country = :country"
values["country"] = country
lines = {}
for low, high in windowed(chain(VOLTAGE_SCALE, [None]), 2):
low = low * 1000
query = (
"SELECT sum(length) FROM stats.power_line WHERE time = :time AND voltage >= :low"
+ country_clause
)
vals = values.copy()
vals["low"] = low
if high is not None:
high = high * 1000
query += " AND voltage < :high"
vals["high"] = high
res = await database.fetch_one(query, vals)
lines[(low, high)] = res[0] or 0
unspecified = await database.fetch_one(
"SELECT sum(length) FROM stats.power_line WHERE time = :time AND voltage IS NULL"
+ country_clause,
values,
)
total = await database.fetch_one(
"SELECT sum(length) FROM stats.power_line WHERE time = :time" + country_clause,
values,
)
data = {
"date": stats_date.date(),
"lines": lines,
"total": total[0] or 0.01,
"unspecified": unspecified[0] or 0,
}
return data
@alru_cache(maxsize=1000)
async def get_wikidata(wikidata_id):
wikidata_id = wikidata_id.upper()
if not re.match(r"^Q[0-9]+$", wikidata_id):
return None
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.wikidata.org/entity/{wikidata_id}.json"
) as resp:
if resp.status != 200:
raise HTTPException(503, "Error while fetching wikidata")
data = await resp.json()
# ID may have changed if it redirects to another. Fetch the first
# (hopefully only) ID in the list.
wikidata_id = list(data["entities"].keys())[0]
return data["entities"][wikidata_id]
@alru_cache(maxsize=1000)
async def get_commons_thumbnail(filename, width=300):
url = (
"https://commons.wikimedia.org/w/api.php?"
f"action=query&titles=Image:{filename}&prop=imageinfo"
f"&iiprop=url&iiurlwidth={width}&format=json"
)
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status != 200:
raise HTTPException(503, "Error while fetching wikimedia commons image")
data = await resp.json()
return list(data["query"]["pages"].values())[0]