Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask,request,url_for,redirect,render_template
- import json
- import sched
- import time
- import requests
- from datetime import datetime
- import pyttsx3
- import configparser
- import logging
- import os
- #initiate the logging file and set logging level
- logging.basicConfig(filename='data.log',level=logging.INFO)
- #set the directory of the logging file
- log_dir = os.path.join(os.path.normpath(os.getcwd() + os.sep + os.pardir), 'logs')
- log_fname = os.path.join(log_dir,'data.log')
- #initiate global lists and scheduler
- s = sched.scheduler(time.time,time.sleep)
- events = []
- alarms = []
- log = []
- #initiate flask application and set route
- app = Flask(__name__)
- @app.route("/")
- #The main functionality of the program, will render the webpage
- def main() -> int and list:
- #retrieve log
- global log
- #call to retrieve api keys
- apis=get_apis()
- #call weather using first api key
- weather_api = apis[0]
- #call news using second api key
- news_api = apis[1]
- news = get_news(news_api)
- weather = get_weather(weather_api)
- #set each variable for weather and news to indexs in each array
- temperature = weather[0]
- pressure = weather[1]
- humidity = weather[2]
- description = weather[3]
- story1 = news[0]
- story2 = news[1]
- story3 = news[2]
- #retrieve log
- notif_log = get_alarm()
- #refresh every 60 seconds
- s.enter(60,1,main)
- notif_log = log
- s.run(blocking=False)
- #set blocking to false to allow the user to continue using the application
- #split the queue to allow for correct formatting in html
- return render_template("index.html",
- temperature=temperature,pressure=pressure,humidity=humidity,description=description,news = news,
- story1=story1,story2=story2,story3=story3,notif_log=notif_log)
- #render page whilst passing variables
- #function used to parse config file and retrieve api keys
- def get_apis():
- #set flask_app as path directory name
- flask_app = os.path.dirname(os.path.abspath(__file__))
- #assign configuration file
- config_file = os.path.join(flask_app,'config.json')
- with open(config_file) as f:
- #open and extract api keys from config file
- data = json.load(f)
- weather_api = data["weather"]
- news_api = data["news"]
- #return api keys
- return weather_api,news_api
- #Function to update the notifications log to be displayed to the user
- def update_log(text_var: str) -> list:
- global log
- #append text variable to log array
- log.append(text_var)
- logging.info(str(text_var))
- #log the event as an INFO
- return log
- app.route("/get_alarm")
- #set route to get_alarm
- #Function called when the user is trying to add an alarm
- def get_alarm() -> str and list:
- global alarms,events
- #check to see if user is cancelling alarm
- alarm_to_cancel = request.args.get("alarm_to_cancel")
- if alarm_to_cancel:
- #if yes call cancel alarm and pass time variable
- cancel_alarm(alarm_to_cancel)
- alarm = request.args.get("alarm")
- #check to see if alarm is being set
- #declare list strings which will be displayed on html
- if alarm:
- user = request.args.get("user")
- #request the user name
- engine = pyttsx3.init()
- #initiate engine to speak
- alarm_date_time = time.strptime(alarm,'%Y-%m-%dT%H:%M')
- alarm_date_time = time.mktime(alarm_date_time)
- #set alarm to a readable format for scheduler
- alarm_formatted = alarm.replace("T"," ").strip("''")
- #format to be readable to human
- if alarm_formatted in alarms:
- #if alarm is already in alarms set
- engine.say("You have already set an alarm for this time")
- update_log("Alarm already set for that time. No alarm added.")
- else:
- engine.say("Your alarm has been set")
- update_log("Your alarm has been set for "+ str(alarm_formatted) + " with the name "+ str(user))
- #log and tell the user that their alarm has been set
- event = s.enterabs(alarm_date_time,1,alarm_over,argument =(alarm,user,))
- #set the alarm using scheduler
- events.append(event)
- #append the alarm to global array alarms
- s.run(blocking=False)
- #run the alarm
- engine.runAndWait()
- return log
- #Called when a schedualed alarm is over
- def alarm_over(alarm: datetime ,user: str):
- engine = pyttsx3.init()
- engine.say("Alarm set is over")
- update_log("Alarm for "+str(user)+" is over.")
- engine.runAndWait()
- #Function to show the user the latest news
- def get_news(news_api: str) -> str:
- api_key = str(news_api)
- #set api key to string
- url = ('https://newsapi.org/v2/top-headlines?'
- 'sources=bbc-news&'
- 'apiKey='+api_key)
- response = requests.get(url)
- #request json from full url
- n = response.json()
- titles = []
- if n["status"] == "ok":
- for i in n["articles"]:
- title = (i["title"])
- titles.append(title)
- #parse through json and retrieve list of all headlines
- story1 = titles[0]
- story2 = titles[1]
- story3= titles[2]
- #take the first 3 headlines
- return story1,story2,story3
- #return first 3 headlines
- #Function to gather data of the latest weather in Exeter
- def get_weather(weather_api: str) -> str:
- api_key = weather_api
- weather_url = "http://api.openweathermap.org/data/2.5/weather?"
- complete_url = weather_url + "appid=" + api_key + "&q=exeter"
- response = requests.get(complete_url)
- #get respones from full url including api key
- w = response.json()
- if w["cod"] != "404":
- y = w["main"]
- current_temperature = y["temp"]
- current_pressure = y["pressure"]
- current_humidiy = y["humidity"]
- z = w["weather"]
- weather_description = z[0]["description"]
- temperature = (" Temperature (in kelvin unit) = " +
- str(current_temperature))
- pressure = ("Atmospheric pressure (in hPa unit) = " +
- str(current_pressure))
- humidity = ("Humidity (in percentage) = " + str(current_humidiy))
- description = ("Description = " + str(weather_description))
- #parse through json file extracting temp, humidity,description and current pressure
- return temperature,pressure,humidity,description
- app.route("/")
- #Function used to cancel any currently set alarms
- def cancel_alarm(alarm: datetime):
- global events
- alarm_to_cancel = alarm
- #set alarm to cancel as the alarm
- alarm_to_cancel = time.strptime(alarm_to_cancel,'%Y-%m-%dT%H:%M')
- alarm_to_cancel = time.mktime(alarm_to_cancel)
- #format to a executable format for scheduler
- alarm_formatted = alarm.replace("T"," ").strip("''")
- #format to readable for human
- if len(events) == 0:
- update_log("No alarm has been set:")
- #check if any alarms have been set
- else:
- cancelled = False
- for event in events:
- #iterate through all set alarms
- for var in event:
- if var == alarm_to_cancel:
- #check if time set in event is equal to time requested for cancelling
- s.cancel(event)
- update_log("Alarm set for " + str(alarm_formatted)+" has been cancelled.")
- cancelled = True
- #log the alarm has been cancelled and set cancelled to true
- if not cancelled:
- #if alarm has not been cancelled log to user
- update_log("No alarm has been found with this time.")
- if __name__ == '__main__':
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement