creating Barchart instead of Screenshot

This commit is contained in:
schrom01 2023-09-30 16:46:31 +02:00
parent 70c6c0d63d
commit 3da728df7d
3 changed files with 86 additions and 33 deletions

40
Balkendiagram.py Normal file
View File

@ -0,0 +1,40 @@
import matplotlib.pyplot as plt
import numpy as np
def create_barchart(barChartMonth, barChartData, color, image_folder_barcharts, image_filename):
barChartMonth.reverse()
barChartData.reverse()
max_wert = max(barChartData)
min_wert = min(barChartData)
skala = max_wert + max_wert * 0.1
plt.figure(figsize=(7, 3))
plt.bar(barChartMonth, barChartData, color=color)
plt.ylabel('Stromproduktion in Franken', fontsize=12)
plt.ylim(0, skala)
# Turn off the frame (border) around the graphic
ax = plt.gca() # Get the current axis
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
plt.xticks(barChartMonth)
# Set the x-axis limits to remove extra space on the right
# plt.xlim(barChartMonth[0], barChartMonth[-1])
plt.savefig(f"{image_folder_barcharts}{image_filename}", bbox_inches='tight')
plt.show()
barChartMonth = [8, 7, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9]
barChartMonth = [str(item) for item in barChartMonth]
barChartData=[612.9508602242413, 774.9497310367794, 905.1661458663121, 700.3920174038531, 455.8453881411557, 362.9725109507848, 243.91420489011418, 106.40652073925607, 98.73508056571949, 140.51124465669344, 293.31970563938467, 442.59112071461107]
image_folder_barcharts = "barcharts/"
image_filename = "test-file.png"
color = "red"
create_barchart(barChartMonth, barChartData, color, image_folder_barcharts, image_filename)

View File

@ -71,12 +71,12 @@ def search_adresses(adress_list, filename_adresslist, driver, mainText):
image_folder_barcharts = "barcharts/"
if(not os.path.exists(image_folder_map[:-1])):
os.makedirs(image_folder_map[:-1], exist_ok=False)
if(not os.path.exists(image_folder_production[:-1])):
os.makedirs(image_folder_production[:-1], exist_ok=False)
# if(not os.path.exists(image_folder_production[:-1])):
# os.makedirs(image_folder_production[:-1], exist_ok=False)
if (not os.path.exists(image_folder_qrcode[:-1])):
os.makedirs(image_folder_qrcode[:-1], exist_ok=False)
if (not os.path.exists(image_folder_barcharts[:-1])):
os.makedirs(image_folder_qrcode[:-1], exist_ok=False)
os.makedirs(image_folder_barcharts[:-1], exist_ok=False)
startTime = datetime.datetime.now()
address_count = len(adress_list)
@ -90,6 +90,7 @@ def search_adresses(adress_list, filename_adresslist, driver, mainText):
sumRoofArea = "not-found"
featureId = "not-found"
response_all_roofs_decoded = "not-found"
coordinates = ("not-found", "not-found")
found = True
line = adress_list[i]
adress = line.split(file_split_char)
@ -146,9 +147,8 @@ def search_adresses(adress_list, filename_adresslist, driver, mainText):
response_one_roof = requests.get('https://api3.geo.admin.ch/rest/services/api/MapServer/identify',
params=params)
response_one_roof_decoded = json.loads(response_one_roof.content.decode())
results = (response_one_roof_decoded['results'])
# for result in results:
# print(result)
# results = (response_one_roof_decoded['results'])
building_id = (response_one_roof_decoded)['results'][0]['attributes']['building_id']
except:
found = False
@ -175,18 +175,19 @@ def search_adresses(adress_list, filename_adresslist, driver, mainText):
barChartMonth = response_all_roofs_decoded[0]['attributes']['monate']
barChartData = [0] * 12
for roof in response_all_roofs_decoded:
for i in range(12):
barChartData[i] = barChartData[i] + float(roof['attributes']['monats_ertrag'][i]) * float(roof['attributes']['flaeche']) * electricityPrice
energy = float(roof['attributes']['gstrahlung'])*0.2*0.8
if(energy > bestRoofEnergy):
bestRoofEnergy = energy
bestRoof = roof
if(float(roof['attributes']['flaeche']) > minRoofSize and int(roof['attributes']['klasse']) >= minSuitability):
for month_count in range(12):
barChartData[month_count] = barChartData[month_count] + float(
roof['attributes']['monats_ertrag'][month_count]) * float(
roof['attributes']['flaeche']) * electricityPrice
sumEnergyRoofs = sumEnergyRoofs + energy
sumRoofArea = sumRoofArea + float(roof['attributes']['flaeche'])
suitabilities.append(int(roof['attributes']['klasse']))
print(barChartMonth)
print(barChartData)
featureId = str(bestRoof['featureId'])
url = "https://www.uvek-gis.admin.ch/BFE/sonnendach/index.html?featureId=" + featureId + "&lang=de"
suitability = max(suitabilities)
@ -214,7 +215,7 @@ def search_adresses(adress_list, filename_adresslist, driver, mainText):
repsonse_solar_panel = requests.get('https://api3.geo.admin.ch/rest/services/api/MapServer/find',
params=params)
repsonse_solar_panel_decoded = json.loads(repsonse_solar_panel.content.decode())
print(repsonse_solar_panel_decoded)
results = (repsonse_solar_panel_decoded['results'])
if(len(results) > 0):
existing_solar_panel_power = results[0]['attributes']['total_power']
@ -226,7 +227,17 @@ def search_adresses(adress_list, filename_adresslist, driver, mainText):
if(found and createImages.get() > 0 and roof_is_suitable and (not roof_has_solarpanel)):
image_filename = address_string + ".png"
barchart_color = "red"
barchart_color = ""
if(suitability == 1):
barchart_color = "#00c5ff"
elif(suitability == 2):
barchart_color = "#ffff00"
elif(suitability == 3):
barchart_color = "#ffaa00"
elif(suitability == 4):
barchart_color = "#ff5500"
elif(suitability == 5):
barchart_color = "#a80000"
create_images(address_string, driver, image_filename, image_folder_map, image_folder_production, image_folder_qrcode, image_folder_barcharts,
url, barChartMonth, barChartData, barchart_color)
@ -373,25 +384,26 @@ def create_images(address_string, driver, image_filename, image_folder_map, imag
image_folder_map + image_filename)
# Create Screenshot of Chart
try:
chartElement = driver.find_elements(By.XPATH, "//div[@id='chart']//*")[0]
location = chartElement.location
size = chartElement.size
x = location["x"]
y = location["y"]
w = x + size["width"]
h = size["height"]
area = (x, 0, w, h)
driver.execute_script("window.scrollTo(0, " + str(y) + ")")
time.sleep(1)
driver.save_screenshot(image_folder_production + image_filename)
time.sleep(0.2)
Image.open(image_folder_production + image_filename).crop(area).save(
image_folder_production + image_filename)
except:
pass
# try:
# chartElement = driver.find_elements(By.XPATH, "//div[@id='chart']//*")[0]
# location = chartElement.location
# size = chartElement.size
# x = location["x"]
# y = location["y"]
# w = x + size["width"]
# h = size["height"]
# area = (x, 0, w, h)
# driver.execute_script("window.scrollTo(0, " + str(y) + ")")
#
# time.sleep(1)
# driver.save_screenshot(image_folder_production + image_filename)
# time.sleep(0.2)
# Image.open(image_folder_production + image_filename).crop(area).save(
# image_folder_production + image_filename)
# except:
# pass
# Create barchar with matplotlib.pyplot
try:
barChartMonth.reverse()
barChartMonth = [str(item) for item in barChartMonth]
@ -419,7 +431,6 @@ def create_images(address_string, driver, image_filename, image_folder_map, imag
# plt.xlim(barChartMonth[0], barChartMonth[-1])
plt.savefig(f"{image_folder_barcharts}{image_filename}", bbox_inches='tight')
plt.show()
except:
pass

View File

@ -2,7 +2,7 @@
import json
import requests
search_string = "Toggenburgstrasse 31 8245 Feuerthalen"
search_string = "Mattenweg 29 5600 Lenzburg"
#Address to coordinates
params={
@ -54,4 +54,6 @@ response_all_roofs = requests.get('https://api3.geo.admin.ch/rest/services/api/M
response_all_roofs_decoded = json.loads(response_all_roofs.content.decode())['results']
for roof in response_all_roofs_decoded:
# print(roof['attributes'].keys())
print("URL:", "https://www.uvek-gis.admin.ch/BFE/sonnendach/index.html?featureId=" + str(roof['featureId']) + "&lang=de", "Fläche:", roof['attributes']['flaeche'], "Eignung(1-5):", roof['attributes']['klasse'], "PV100:", float(roof['attributes']['gstrahlung']*0.2*0.8))
print("URL:", "https://www.uvek-gis.admin.ch/BFE/sonnendach/index.html?featureId=" + str(roof['featureId']) + "&lang=de", "Fläche:", roof['attributes']['flaeche'], "Eignung(1-5):", roof['attributes']['klasse'], "PV100:", float(roof['attributes']['gstrahlung']*0.2*0.8))
print(roof)