This is gonna be a merge hell

This commit is contained in:
Whizel 2019-04-07 01:53:22 +02:00
commit 6d3afabb1a
14 changed files with 85 additions and 67 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

View file

@ -1,6 +1,5 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { MyCameraService } from '../../services/my-camera-service'; import { MyCameraService } from '../../services/my-camera-service';
import { Image } from 'tns-core-modules/ui/image'
@Component({ @Component({
selector: 'ns-camera-button', selector: 'ns-camera-button',

View file

@ -23,8 +23,7 @@ export class HomePageComponent implements OnInit {
flat_earth: boolean; flat_earth: boolean;
in_australia: boolean; in_australia: boolean;
constructor(private myHttpPostSerivce: MyHttpPostService, constructor(private routerExtensions: RouterExtensions,
private routerExtensions: RouterExtensions,
) { } ) { }
ngOnInit(): void { ngOnInit(): void {
@ -32,35 +31,5 @@ export class HomePageComponent implements OnInit {
public onTap(args: GestureEventData): void { public onTap(args: GestureEventData): void {
this.routerExtensions.navigateByUrl("/result-page"); this.routerExtensions.navigateByUrl("/result-page");
/* return this.cameraService.takePicture().
then(picture => {
this.image = JSON.stringify(picture);
//console.log('this is picture in json', JSON.stringify(picture));
this.getLocation();
}) */
} }
/* public getLocation(): any {
this.geoLocationService.getLocation().then(location => {
this.locationData = location;
//console.log('this is locationData', this.locationData);
this.submit();
}).catch(error => {
});
}
public submit(): void {
this.makePostRequest();
}
private makePostRequest(): void {
this.myHttpPostSerivce
.postData({ position: this.locationData, image: this.image, flat_earth: true, in_australia: true, })
.subscribe(res => {
//console.log('This is res', res);
this.myReturnJSON = res;
console.log('THis is myreturnJSON', this.myReturnJSON);
this.routerExtensions.navigateByUrl("/result-page");
});
} */
} }

View file

@ -1 +1,19 @@
/* Add mobile styles for the component here. */ .title-container
{
font-family: 'Times New Roman', Times, serif;
font-size: 20px;
color: black;
padding: 5px;
text-align: center;
}
.page {
background-color: lightskyblue;
}
.item-header {
font-family: 'Times New Roman', Times, serif;
font-size: 14px;
}
.item-header {
font-family: 'Times New Roman', Times, serif;
font-size: 10px;
}

View file

@ -1,7 +1,18 @@
<ActionBar title="Result" class="action-bar"></ActionBar> <ActionBar title="Result" class="action-bar"></ActionBar>
<ScrollView class="page"> <StackLayout class="page" height="100%">
<AbsoluteLayout> <StackLayout height="10%" class="title-container">
<Button class="btn btn-primary" text="Home" [nsRouterLink]="['/home-page']"></Button> <Label text="{{night}}"></Label>
</AbsoluteLayout> <Label text="{{percentage}}"></Label>
</StackLayout>
<ScrollView height='90%'>
<ListView [items]="reasons" class="list-group">
<ng-template let-reason="item" let-i="index" let-odd="odd" let-even="even">
<StackLayout orientation="vertical" class="list-group-item">
<Label class="item-header" [text]="reason.str" width="100%" textWrap="true"></Label>
<Label class="item-item" [text]="reason.causestring" width="100%" textWrap="true"></Label>
</StackLayout>
</ng-template>
</ListView>
</ScrollView> </ScrollView>
</StackLayout>

View file

@ -7,6 +7,12 @@ import { MyCameraService } from '../services/my-camera-service'
import { RouterExtensions } from 'nativescript-angular/router'; import { RouterExtensions } from 'nativescript-angular/router';
import { Location } from 'nativescript-geolocation'; import { Location } from 'nativescript-geolocation';
class Reason {
constructor(public str: string, public causestring: string) {
}
}
@Component({ @Component({
selector: 'result-page', selector: 'result-page',
templateUrl: './result-page.component.html', templateUrl: './result-page.component.html',
@ -21,13 +27,16 @@ export class ResultPageComponent implements OnInit {
image: any; image: any;
flat_earth: boolean; flat_earth: boolean;
in_australia: boolean; in_australia: boolean;
night: string = "";
percentage: string = "";
JSONObject;
public reasons: Array<Reason>;
constructor(private myHttpPostSerivce: MyHttpPostService, constructor(private myHttpPostSerivce: MyHttpPostService,
private routerExtensions: RouterExtensions, private routerExtensions: RouterExtensions,
private geoLocationService: MyGeoLocationService, private geoLocationService: MyGeoLocationService,
private batterInfoService: MyBatteryInfoService, private batterInfoService: MyBatteryInfoService,
private cameraService: MyCameraService, private cameraService: MyCameraService,){ }
) { }
ngOnInit(): Promise<void> { ngOnInit(): Promise<void> {
return this.cameraService.takePicture(). return this.cameraService.takePicture().
@ -55,8 +64,8 @@ private makePostRequest(): void {
.postData({ position: this.locationData, image: this.image, flat_earth: true, in_australia: true, }) .postData({ position: this.locationData, image: this.image, flat_earth: true, in_australia: true, })
.subscribe(res => { .subscribe(res => {
//console.log('This is res', res); //console.log('This is res', res);
this.myReturnJSON = res; this.JSONObject = res;
console.log('THis is myreturnJSON', this.myReturnJSON); //console.log('THis is myreturnJSON', this.myReturnJSON);
}); });
} }

View file

@ -10,27 +10,29 @@ from typing import List
import requests_cache import requests_cache
from flask import Flask, jsonify, logging, request from flask import Flask, jsonify, logging, request
from .strategies import miloStrats, iss, cars_in_traffic, tide_strat, upstairs_neighbour, bing, battery from .strategies import miloStrats, iss, cars_in_traffic, tide_strat, upstairs_neighbour, bing, svm_strat, battery, just_eat
from .util import Context from .util import Context
app = Flask(__name__) app = Flask(__name__)
logger = logging.create_logger(app) logger = logging.create_logger(app)
logger.setLevel(DEBUG) logger.setLevel(DEBUG)
requests_cache.install_cache("requests_cache", expire_after=timedelta(minutes=10)) requests_cache.install_cache("requests_cache", expire_after=timedelta(minutes=2))
strategies = { strategies = {
# name: (weight, probability function) # name: (weight, probability function)
"tv2news": miloStrats.tv2newsStrat, "TV2 News": miloStrats.tv2newsStrat,
"australia": miloStrats.australiaStrat, "Australia": miloStrats.australiaStrat,
"camera": miloStrats.camImgStrat, "Camera Image": miloStrats.camImgStrat,
"iss": iss.night_on_iss, "The International Space Station": iss.night_on_iss,
"cars_in_traffic": cars_in_traffic.cars_in_traffic, "Nearby Traffic situation": cars_in_traffic.cars_in_traffic,
"tide": tide_strat.is_tide, "Tidal Measurements": tide_strat.is_tide,
"upstairs_neighbour": upstairs_neighbour.check_games, "Legends of Nighttime": upstairs_neighbour.check_games,
"bing": bing.clock, "Bing AI": bing.clock,
"battery_level": battery.battery_level, "ML Parking": svm_strat.perform_svm_pred,
"Phone Battery Level": battery.battery_level,
"Pizza Availability": just_eat.do_just_eat_strat,
} }
@ -86,6 +88,9 @@ def probabilities():
# If this prediction disagrees with the consensus it contributed negatively # If this prediction disagrees with the consensus it contributed negatively
if prediction["night"] != night: if prediction["night"] != night:
prediction["contribution"] *= -1 prediction["contribution"] *= -1
predictions.sort(key=lambda p: (p["contribution"], p["probability"]), reverse=True)
return jsonify({ return jsonify({
"predictions": predictions, "predictions": predictions,
"weighted_probabilities_mean": mean, "weighted_probabilities_mean": mean,

View file

@ -40,11 +40,11 @@ def night_on_iss(context: Context) -> Prediction:
side = "same" if on_iss_time else "other" side = "same" if on_iss_time else "other"
p.reasons.append(f"{the_iss} is {int(distance)} km away, so we are on the {side} side of the earth.") p.reasons.append(f"{the_iss} is {int(distance)} km away, so we are on the {side} side of the earth.")
for i in itertools.count(1): for i in itertools.count(1):
iss_tz = tf.closest_timezone_at(lng=float(iss_position["longitude"]), iss_tz = tf.closest_timezone_at(lng=float(iss_position["longitude"]), lat=float(iss_position["latitude"]),
lat=float(iss_position["latitude"]),
delta_degree=i) delta_degree=i)
if iss_tz is not None: if iss_tz is not None:
break break
iss_time = datetime.now(pytz.timezone(iss_tz)) iss_time = datetime.now(pytz.timezone(iss_tz))
iss_night = iss_time.hour < 6 or iss_time.hour >= 22 iss_night = iss_time.hour < 6 or iss_time.hour >= 22
@ -75,6 +75,9 @@ def haversine(pos1, pos2):
lat2 = float(pos2["latitude"]) lat2 = float(pos2["latitude"])
long2 = float(pos2["longitude"]) long2 = float(pos2["longitude"])
lat1 = 0 # we're only interested in the distance in the longitude for the timezone calculation
lat2 = 0
degree_to_rad = float(pi / 180.0) degree_to_rad = float(pi / 180.0)
d_lat = (lat2 - lat1) * degree_to_rad d_lat = (lat2 - lat1) * degree_to_rad

View file

@ -1,12 +1,8 @@
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from datetime import datetime, timedelta
import requests_cache
from ..util import Context, Prediction from ..util import Context, Prediction
requests_cache.install_cache("requests_cache", expire_after=timedelta(minutes=10))
def is_restaurant_open(name, open, close) -> Prediction: def is_restaurant_open(name, open, close) -> Prediction:
p = Prediction() p = Prediction()
@ -44,4 +40,7 @@ def is_restaurant_open(name, open, close) -> Prediction:
def do_just_eat_strat(context: Context) -> Prediction: def do_just_eat_strat(context: Context) -> Prediction:
"""
Is this random Kiosk in Vester Alle open?
"""
return is_restaurant_open('stop2shop', 12, 23) return is_restaurant_open('stop2shop', 12, 23)

View file

@ -51,7 +51,7 @@ def tv2newsStrat(context : Context) -> Prediction:
r = requests.get('http://mpx.services.tv2.dk/api/latest') r = requests.get('http://mpx.services.tv2.dk/api/latest')
data = r.json() data = r.json()
publish_dates = [(x['pubDate'])//1000 for x in data][:10] publish_dates = [(x['pubDate'])//1000 for x in data[:5]]
delta_times = [] delta_times = []
for i in range(len(publish_dates)): for i in range(len(publish_dates)):
if i == 0 : continue if i == 0 : continue
@ -66,6 +66,7 @@ def tv2newsStrat(context : Context) -> Prediction:
p.weight = 0.0 p.weight = 0.0
else: else:
p.weight = 0.7 p.weight = 0.7
p.probability = 1.0 if avg_timestamp > 50 else 0.0 print(avg_timestamp)
p.reasons.append('There were ' + ('few' if avg_timestamp > 50 else 'many') + ' recent articles on TV2 News') p.probability = 0.75 if avg_timestamp > 40 else 0.25
p.reasons.append('There were ' + ('few' if avg_timestamp > 40 else 'many') + ' recent articles on TV2 News')
return p return p

View file

@ -0,0 +1 @@
{"help": "https://portal.opendata.dk/api/3/action/help_show?name=datastore_search", "success": true, "result": {"include_total": true, "resource_id": "2a82a145-0195-4081-a13c-b0e587e9b89c", "fields": [{"type": "int", "id": "_id"}, {"type": "text", "id": "date"}, {"type": "text", "id": "garageCode"}, {"type": "int4", "id": "totalSpaces"}, {"type": "int4", "id": "vehicleCount"}], "records_format": "objects", "records": [{"_id": 1, "date": "2019/04/06 22:30:01", "garageCode": "NORREPORT", "totalSpaces": 80, "vehicleCount": 61}, {"_id": 2, "date": "2019/04/06 22:30:01", "garageCode": "SCANDCENTER", "totalSpaces": 1240, "vehicleCount": 442}, {"_id": 6, "date": "2019/04/06 22:30:01", "garageCode": "SALLING", "totalSpaces": 700, "vehicleCount": 290}, {"_id": 7, "date": "2019/04/06 22:30:01", "garageCode": "DOKK1", "totalSpaces": 1000, "vehicleCount": 0}, {"_id": 8, "date": "2019/04/06 22:30:01", "garageCode": "Navitas", "totalSpaces": 449, "vehicleCount": 161}, {"_id": 9, "date": "2019/04/06 22:30:01", "garageCode": "NewBusgadehuset", "totalSpaces": 105, "vehicleCount": 99}, {"_id": 3, "date": "2019/04/06 22:30:01", "garageCode": "BRUUNS", "totalSpaces": 953, "vehicleCount": 598}, {"_id": 4, "date": "2019/04/06 22:30:01", "garageCode": "MAGASIN", "totalSpaces": 378, "vehicleCount": 65}, {"_id": 5, "date": "2019/04/06 22:30:01", "garageCode": "KALKVAERKSVEJ", "totalSpaces": 210, "vehicleCount": 278}, {"_id": 10, "date": "2019/04/06 22:30:01", "garageCode": "Urban Level 1", "totalSpaces": 319, "vehicleCount": 32}, {"_id": 11, "date": "2019/04/06 22:30:01", "garageCode": "Urban Level 2+3", "totalSpaces": 654, "vehicleCount": 66}], "_links": {"start": "/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c", "next": "/api/3/action/datastore_search?offset=100&resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c"}, "total": 11}}

View file

@ -1,3 +1,5 @@
from pathlib import Path
from sklearn import svm from sklearn import svm
from sklearn.externals import joblib from sklearn.externals import joblib
import requests import requests
@ -5,11 +7,9 @@ import glob
import json import json
import numpy as np import numpy as np
from .strat_utils import write_json from .strat_utils import write_json
from ..util import Context, Prediction from ..util import Context, Prediction
def write_data(time): def write_data(time):
write_json("https://portal.opendata.dk/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c", "parking_aarhus", time) write_json("https://portal.opendata.dk/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c", "parking_aarhus", time)
@ -38,12 +38,15 @@ def train():
joblib.dump(classifier, "nightness_classifier.pkl") joblib.dump(classifier, "nightness_classifier.pkl")
def predict(X): def predict(X):
classifier = joblib.load("nightness_classifier.pkl") classifier = joblib.load(str(Path(__file__).parent.joinpath("nightness_classifier.pkl")))
prob = classifier.predict_proba(np.array(X).reshape(1, -1)) prob = classifier.predict_proba(np.array(X).reshape(1, -1))
return prob[0, 1] return prob[0, 1]
def perform_svm_pred(context: Context) -> Prediction: def perform_svm_pred(context: Context) -> Prediction:
"""
An SVM trained on two data points, which is capable of guessing 0.5 no matter what.
"""
p = Prediction() p = Prediction()
data = requests.get('https://portal.opendata.dk/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c') data = requests.get('https://portal.opendata.dk/api/3/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c')
@ -54,5 +57,5 @@ def perform_svm_pred(context: Context) -> Prediction:
p.reasons.append("Our only two data points have 11 dimensions") p.reasons.append("Our only two data points have 11 dimensions")
p.reasons.append("We are using a SVM") p.reasons.append("We are using a SVM")
p.probability = predict(X) p.probability = float(predict(X))
return p return p