Skip to content

Commit

Permalink
ryddet litt i koden og lagt til kommentarer
Browse files Browse the repository at this point in the history
  • Loading branch information
springvalley committed Feb 23, 2024
1 parent 9b93923 commit 40a0e45
Show file tree
Hide file tree
Showing 11 changed files with 82 additions and 54 deletions.
54 changes: 27 additions & 27 deletions WMS/Ortofoto.py
Original file line number Diff line number Diff line change
@@ -1,73 +1,73 @@
import os
import requests
from datetime import datetime
import urllib.parse
from dotenv import load_dotenv
import json
from WMS import util

def generate_orto_picture():
# Finner path til .env filen som ligger i ngisopenapi mappen
'''
This function is used to generate a photo using Norkart's WMS with orthophoto capabilities.
Returns:
True (Bool) if the image was generated
False (Bool) otherwise
'''

#Defines the URL for the WMS to be used
wms_url = 'https://waapi.webatlas.no/wms-orto/'

#Finds the path to the enviornment file in the NGISopenAPI directory and the path to the coordinates file
current_script_directory = os.path.dirname(os.path.abspath(__file__))
env_file_path = os.path.join(current_script_directory, "..", "ngisopenapi", ".env")
coordinates_file_path = os.path.join(current_script_directory, 'resources', 'coordinates.json')

# Laster .env fra riktig path
#Loads environment variables from the right file
load_dotenv(env_file_path)

# Henter API nøkkelen fra .env
api_key = os.getenv('NK_WMS_API_KEY')

# Definerer WMS url
wms_url = 'https://waapi.webatlas.no/wms-orto/'

# Leser inn koordinatene fra JSON-filen
#Reads the coordinates from the coordinates-JSON file
coordinates = util.read_file(coordinates_file_path)['Coordinates']

# Beregner bbox fra koordinatene gitt i applikasjonen
#Calculates a bbox based on the coordinates
bbox = util.create_bbox(coordinates)

# Setter directory for lagring av bilde
#Directory where the image will be saved
images_directory = "rawphotos"

# Lager hele pathen i samme mappe
images_directory_path = os.path.join(current_script_directory, images_directory)

# Angi hvilke layers, bbox og hva enn du er interessert i
#Parameters for the WMS call
params = {
"api_key": api_key,
"api_key": os.getenv('NK_WMS_API_KEY'),
"request": "GetMap",
"width" : "1600",
"height": "1600",
"layers": "ortofoto",
"srs": "EPSG:25832",
'format': 'image/png', # Fil format
'bbox': bbox, # Oppdaterer bbox med de nye verdiene
'format': 'image/png',
'bbox': bbox,
}

# Build the full URL with the parameters and headers
encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)

# Build and print the full URL
full_url = f"{wms_url}?{encoded_params}"

# Headers som legger en browser request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}

# Oppretter en get request til WMS serveren gjennom url og api nøkkel
#Uses the request library to make a request to the url
response = requests.get(full_url, headers=headers) # Ensure the request is made to `full_url`

#Check if the response from the server was OK
if response.status_code == 200:
#Define the file name and path for the image
file_name = f"orto.png"

# Hele fil pathen
image_path = os.path.join(images_directory_path, file_name)


#Save the image
with open(image_path, 'wb') as file:
file.write(response.content)
print(f"Bildet ble lagret i {image_path}.")
return True
else:
#If something went wrong, print the status code and explanation
print(f"Kunne ikke lagre ortofoto-bilde, statuskode: {response.status_code}")
print(f"Error in creating ortophoto: {response.reason}" )
return False
49 changes: 25 additions & 24 deletions WMS/Sanderscript.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,35 @@
#Dette scriptet genererer treningsdata
import os
import urllib.parse
import json
import requests
from datetime import datetime
from WMS import util

def generate_wms_picture():
'''
This function is used to generate a photo using a WMS.
Returns:
True (Bool) if the image was generated
False (Bool) otherwise
'''

# URL til WMS
#Defines the URL for the WMS to be used
base_url = "https://openwms.statkart.no/skwms1/wms.fkb"

# Bruker riktig path til scriptet
#Finds the path to the coordinates file
current_script_directory = os.path.dirname(os.path.abspath(__file__))

# Leser koordinatene fra JSON-filen
coordinates_file_path = os.path.join(current_script_directory, 'resources', 'coordinates.json')

#Reads the coordinates from the coordinates-JSON file
coordinates = util.read_file(coordinates_file_path)['Coordinates']

# Beregner bbox fra koordinatene gitt i json fila
#Calculates a bbox based on the coordinates
bbox = util.create_bbox(coordinates)

# Velger et sted å lagre bildene
#Directory where the image will be saved
images_directory = "rawphotos"

# Lagrer alt i mappen definert
images_directory_path = os.path.join(current_script_directory, images_directory)

# WMS parametere, de tomme feltene blir definert videre i koden
#Parameters for the WMS call
wms_params = {
'SERVICE': 'WMS',
'VERSION': '1.3.0',
Expand All @@ -46,15 +48,15 @@ def generate_wms_picture():
'sld_body': ''
}

#Layers to be put in the request url
layer_names = "bygning"
wms_params['LAYERS'] = layer_names

# Starter SLD body
sld_body = '''
<sld:StyledLayerDescriptor version="1.0.0" xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd">
'''

# Genererer en "NamedLayer" blokk av kode for hvert layer
#Generates a new SLD layer for each layer defined above
for layer_name in layer_names.split(','):
sld_body += f'''
<sld:NamedLayer>
Expand All @@ -74,36 +76,35 @@ def generate_wms_picture():
</sld:UserStyle>
</sld:NamedLayer>
'''

# Lukker SLD bodyen

sld_body += '</sld:StyledLayerDescriptor>'

# Putter SLD stylingen inn i wms_params
#Adds the sld parameters to the wms parameters
wms_params['sld_body'] = sld_body

# Encode parameters, including SLD body
#Build the full URL with the parameters and headers
encoded_params = urllib.parse.urlencode(wms_params, quote_via=urllib.parse.quote)

# Bygger og printer URLen med de riktige definerte WMS parameterene
full_url = f"{base_url}?{encoded_params}"

# Headers som lager en browser request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}

#Uses the request library to make a request to the url
response = requests.get(full_url, headers=headers)

#Check if the response from the server was OK
if response.status_code == 200:
#Define the file name and path for the image
file_name = f"fasit.png"

# Hele fil pathen
image_path = os.path.join(images_directory_path, file_name)


#Save the image
with open(image_path, 'wb') as file:
file.write(response.content)
print(f"Bildet ble lagret i {image_path}.")
return True
else:
#If something went wrong, print the status code and explanation
print(f"Kunne ikke lagre fasit-bilde, statuskode: {response.status_code}")
print(f"Error in creating validation photo: {response.reason}" )
return False
Expand Down
Binary file modified WMS/__pycache__/ortofoto.cpython-311.pyc
Binary file not shown.
Binary file modified WMS/__pycache__/sanderscript.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file modified WMS/__pycache__/test_util.cpython-311.pyc
Binary file not shown.
Binary file modified WMS/__pycache__/util.cpython-311.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion WMS/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import shutil
from PIL import Image
import util
from WMS import util


#Test class for the utilities library
Expand Down
2 changes: 1 addition & 1 deletion frontend/pages/order.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ <h1 class="display-4 fw-normal">Order data to email</h1>

<!-- Preview files -->
<div id="filesPreview">
<p class="form-label col-form-label col-form-label-lg "> Files:
<p class="form-label col-form-label col-form-label-lg ">
</p>
<p id="fileCountSummary"></p>
<span>
Expand Down
27 changes: 27 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,13 +291,32 @@ async def send_zip_file(request: Request):
#Route for updating the coordinate file in the WMS/Resources folder
@app.post("/updateWMSCoordinateFile")
async def update_wms_coordinate_file(input: Input):
'''
Updates the Coordinate file for WMS requests
Args:
input (Input): An object of the Input class with the required fields.
Returns:
A message if the coordinates were updated successfully
'''

data = {"Coordinates": input.input}
if(util.write_file(COORDINATE_FILE, data)):
return {"Message": "Coordinates were updated successfully"}

#Route for updating the coordinate file in the WMS/Resources folder
@app.post("/updateWMSConfigFile")
async def update_wms_config_file(configInput: ConfigInput):
'''
Updates the Config file for WMS requests
Args:
configInput (ConfigInput): An object of the ConfigInput class with the required fields.
Returns:
A message if the config was updated successfully
'''
data = {"Config": {
"data_parameters": configInput.data_parameters,
"layers": configInput.layers,
Expand All @@ -309,6 +328,13 @@ async def update_wms_config_file(configInput: ConfigInput):

@app.post("/generatePhotos")
async def generatePhotos():
'''
Makes requests to the WMSes and splits the resulting images into a valid configuration for machine learning
Returns:
A message informing if there was an error or if everything went successfully
'''

#Read config from the file
config = util.read_file(CONFIG_FILE)["Config"];

Expand All @@ -321,6 +347,7 @@ async def generatePhotos():
print("Something went wrong with generating photos")
return {"Message": "Something went wrong with generating photos"}
else:
#If the images were generated successfully it splits the images into tiles and distributes the tiles in the right folders.
util.split_image(os.path.join("WMS", "rawphotos", "fasit.png"), os.path.join("WMS", "tiles", "fasit"), 100)
tiles = util.split_image(os.path.join("WMS", "rawphotos", "orto.png"), os.path.join("WMS", "tiles", "orto"), 100)
util.split_files(os.path.join("WMS", "tiles"), os.path.join("WMS/email"), tiles, config["data_parameters"][0], config["data_parameters"][1])
Expand Down
2 changes: 1 addition & 1 deletion test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import pytest
import os
from WMS import util

from main import zip_files

#Import test client
client = TestClient(app)
Expand Down

0 comments on commit 40a0e45

Please sign in to comment.