Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

Commit

Permalink
Merge branch 'main' of github.com:fox918/EndlessHunger
Browse files Browse the repository at this point in the history
  • Loading branch information
fox918 committed Oct 29, 2023
2 parents 4c24316 + 7a60e75 commit d2d4b51
Show file tree
Hide file tree
Showing 8 changed files with 3,795 additions and 15,057 deletions.
32 changes: 12 additions & 20 deletions backend/app.py
Expand Up @@ -11,34 +11,26 @@
@app.route('/locations')

def locations():
coopData = getCoopLocations("Basel", 10)
coopData = getCoopLocations("Basel")
return jsonify(coopData)


# @app.route('/route/<variable1>/<variable2>')
# def route(variable1, variable2):
# # variable1 und variable2 sind die empfangenen URL-Parameter
# return f'Variable 1: {variable1}, Variable 2: {variable2}'

# @app.route('/search/<searchstring>', methods=['GET'])

# def serach(searchstring):
# originCoordinates, coopLocations = getCoopLocations(searchstring, 10, time_filter=False)
# calculationDatas = getAllRoutes("driving-car", coopLocations)
# return jsonify(calculationDatas)

@app.route('/calculations', methods=['GET'])
def calculations():
location = request.args.get('location')
filter_value = request.args.get('filter')
originCoordinates, coopLocations = getCoopLocations(location, 10, time_filter=False)
originCoordinates, coopLocations = getCoopLocations(location, time_filter=False)
# calculationDatas = getAllRoutes("driving-car", coopLocations, originCoordinates)
body = {"coordinates": [[originCoordinates.get("Longitude"),originCoordinates.get("Latitude")]]}
return jsonify({**body, **coopLocations})

@app.route('/routeing', methods=['GET'])
def routeing():
routingProfile = request.args.get('routingprofile')
location = request.args.get('location')
filter_value = request.args.get('filter')
originCoordinates, coopLocations = getCoopLocations(location, time_filter=False)
calculationDatas = getAllRoutes("driving-car", coopLocations, originCoordinates)
return jsonify(calculationDatas)

# location = request.args.get('location')
# filter_value = request.args.get('filter')

# return f'Location: {location}, Filter: {filter_value}'

if __name__ == '__main__':
app.run()
41 changes: 29 additions & 12 deletions backend/coop_locations.py
Expand Up @@ -40,51 +40,68 @@ def get_unique_format_ids(lat, lng, numCoops):

# get_unique_format_ids(lat, lng, numCoops)

import requests
import json

def fetch_swiss_cities():
overpass_url = "http://overpass-api.de/api/interpreter"

# This query fetches all populated places (cities, towns, villages, etc.) in Switzerland.
# This query fetches all populated places (cities, towns, villages, etc.) in Switzerland
# and their associated canton.
overpass_query = """
[out:json];
area["ISO3166-1"="CH"][admin_level=2];
(node["place"~"city|town|village"](area);
(
node["place"~"city|town|village"](area);
way["place"~"city|town|village"](area);
relation["place"~"city|town|village"](area);
);
out center;
foreach(
is_in->.a;
area.a["admin_level"="4"];
out tags;
);
"""

response = requests.get(overpass_url, params={'data': overpass_query})
data = response.json()

cities = []
for element in data['elements']:
if 'tags' in element:
idx = 0

while idx < len(data['elements']):
element = data['elements'][idx]

if element['type'] in ['node', 'way', 'relation'] and 'tags' in element:
name = element['tags'].get('name', 'Unknown')
population = int(element['tags'].get('population', 0)) # Convert population to integer
cities.append((name, population))
population = int(element['tags'].get('population', 0))

# Increment index to capture the canton information
idx += 1
canton_element = data['elements'][idx]
canton = canton_element['tags'].get('ref', 'Unknown')

cities.append((f"{name}, {canton}", population))

idx += 1

# Sort cities by population in descending order
cities.sort(key=lambda x: x[1], reverse=True)

return cities

def save_to_file(cities):
with open('swiss_cities_by_population.json', 'w', encoding='utf-8') as file:
with open('swiss_cities_by_population_with_canton.json', 'w', encoding='utf-8') as file:
json.dump(cities, file, ensure_ascii=False, indent=4)


# cities = fetch_swiss_cities()
# save_to_file(cities)
# print(f"Data saved to swiss_cities_by_population.json.")
# print(f"Data saved to swiss_cities_by_population_with_canton.json.")




def getCoopLocations(locationName, search_radius=10, time_filter=True):
def getCoopLocations(locationName, search_radius=100, time_filter=False):

def getOriginCoordinates(locationName):
"""Get the latitude and longitude of the given location name."""
Expand Down Expand Up @@ -169,7 +186,7 @@ def filter_coops(coops, food_offering_formats, time_filter=True):

if formatId in food_offering_formats and distance <= search_radius * 1000 and (not time_filter or openStatus):
qualified_coops.append(create_json(coop, openingTime, closingTime, openStatus))
if len(qualified_coops) >= 10 or distance > search_radius * 1000:
if len(qualified_coops) >= 5 or distance > search_radius * 1000:
break
return qualified_coops

Expand Down
152 changes: 0 additions & 152 deletions backend/filtered_coopLocations.json

This file was deleted.

26 changes: 21 additions & 5 deletions backend/getRoutes.py
@@ -1,17 +1,23 @@
import requests
import json
import time
import os
from dotenv import load_dotenv
import xml.etree.ElementTree as ET# Constructing the XML elements and attributes
from coop_locations import getCoopLocations

from concurrent.futures import ThreadPoolExecutor

def getRoute(coopLocations, routingProfile, originCoordinates):
longitude = coopLocations.get("Longitude")
latitude = coopLocations.get("Latitude")
body = {"coordinates": [[originCoordinates.get("Longitude"),originCoordinates.get("Latitude")], [longitude, latitude]]}

load_dotenv()
authorization = os.getenv("authorization")

headers = {
'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
'Authorization': '5b3ce3597851110001cf6248bf3d9d3adcf5443db7ee91adc2489f2d',
'Authorization': authorization,
'Content-Type': 'application/json; charset=utf-8'
}
# Use the routing profile variable in the URL
Expand Down Expand Up @@ -39,8 +45,15 @@ def getAllRoutes(routingProfile, coopLocations,originCoordinates):

elif routingProfile == "driving-car" or routingProfile == "cycling-regular" or routingProfile == "foot-walking" or routingProfile == "wheelchair":

routes = list(map(lambda x: getRoute(x, routingProfile,originCoordinates), coopLocations))

# routes = list(map(lambda x: getRoute(x, routingProfile,originCoordinates), coopLocations))
routes = []
with ThreadPoolExecutor(max_workers=5) as executor: # Du kannst die Anzahl der parallelen Threads anpassen
futures = [executor.submit(getRoute, x, routingProfile, originCoordinates) for x in coopLocations]
for future in futures:
time.sleep(0.1)
result = future.result()
if result:
routes.append(result)
with open('routes.json', 'w') as json_file:
json.dump(routes, json_file, indent=4) # Save the JSON to a file with indentation
print ("Routes saved")
Expand All @@ -55,7 +68,10 @@ def getAllRoutes(routingProfile, coopLocations,originCoordinates):

else:
print("Wrong Routing Profile", routingProfile)

def getBestRoute(routingProfile, coopLocations,originCoordinates):
getAllRoutes(routingProfile, coopLocations, originCoordinates)

if __name__ == '__main__':
originCoordinates, coopLocations = getCoopLocations("Basel", 10, time_filter=False)
originCoordinates, coopLocations = getCoopLocations("Basel", time_filter=False)
ans = getAllRoutes("driving-car", coopLocations, originCoordinates)
2 changes: 1 addition & 1 deletion backend/requirements.txt
Expand Up @@ -4,4 +4,4 @@ openrouteservice
jsonify
requests
geopy

python-dotenv

0 comments on commit d2d4b51

Please sign in to comment.