def interpret_dication(wave_filepath): ap = AddressProvider() address = ap.get("dictation") dc = DictationClient(address) # Read wave file audio = get_audio(wave_filepath) # Run Pathfinder try: results = dc.recognize(method="sync", audio=audio) except grpc.RpcError as e: error_log( "[Server-side error] Received following RPC error from the Pathfinder service:", str(e)) import sys sys.exit(1) transcription = "" for idx, response in enumerate(results): if not len(response): log("No phrases detected.") else: transcription += "\"{}\"".format(response['transcript']) return transcription
def delete_alarm(alarmToBeDeleted): """ This function takes an alarm argument which is to be deleted. Creates a new alarms object. The old alarms gets daved in "alarms_list" If no alarms are there then it will instantiate a new clean object "alarm_list" The for loop iterates through each alarm. If an alarm time is found that is not equal to the time the user has requested to delete, that alarm object is appended to a new list 'new_alarm_objects'.The edited list of alarms is then written to the json file and the start alarm thread is reset. """ new_alarm_objects = [] with open(tmpdir + '/alarms.json', 'r') as alarms_file: try: alarm_list = json.load(alarms_file) except Exception: alarm_list = [] error_log(Exception) for alarm in alarm_list: if alarm['title'] != alarmToBeDeleted: new_alarm_objects.append(alarm) with open(tmpdir + '/alarms.json', 'w') as alarms_file: json.dump(new_alarm_objects, alarms_file, indent=2) info_log("deleted alarm" + alarmToBeDeleted)
def add_alarm(alarm: dict) -> list: """ This function reads all existing alarms from the alarms.json file, appends each one to a list, appends the new alarms to the same list and writes that list to the same json file. """ if filename.is_file(): with open(tmpdir + '/alarms.json', 'r') as alarms_file: # Attempts to load contents of the file. If it's empty, an # empty list is defined and a warning is sent to the log file. try: alarms_object = json.load(alarms_file) except Exception: alarms_object = [] error_log(Exception) alarms_object.append(alarm.copy()) with open(tmpdir + '/alarms.json', 'w') as alarms_file: json.dump(alarms_object, alarms_file, indent=2) else: print("alarm file created") with open(tmpdir + '/alarms.json', 'x') as alarms_file: alarms_file.close() print("alarm file closed") # Start alarm thread reset as the alarms json has changed. # return start_alarm() alarm_thread = Thread(target=start_alarm, args=(), daemon=True) alarm_thread.start()
def get_stock_basic(list_status='L', fields='ts_code,name,area,industry'): try: with scheduler.app.app_context(): pro = ts.pro_api() try: data = pro.stock_basic(list_status=list_status, fields=fields) except Exception as e: data = None if data is None: return data = data.dropna(axis=0, how='any') records = data.to_dict(orient='records') for record in records: ins = StockBasic.find_one(ts_code=record['ts_code']) if ins is None: StockBasic.create(commit=False, **record) else: ins.update(commit=False, **record) else: db.session.commit() info_log('update stock basic succeed') except Exception as e: error_log('update stock basic failed: %s' % (repr(e),), exc_info=True)
def get_weather(tts_enabled: bool) -> None: """ This function fetches the weather data from openweathermap using api key provided in "config.json" and stores the data in "weather.json" New Notification and info log is created each time new data is fetched """ # location location = 'New Delhi' api_key = get_api_key() url = 'https://api.openweathermap.org/data/2.5/weather?q={} \ &appid={}&units=metric'.format(location, api_key) new_weather = requests.get(url).json() with open('assets/weather.json', 'w') as weather_file: json.dump(new_weather, weather_file, indent=2) weather_notification = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'Weather', 'title': 'Current temperature in ' + new_weather['name'] + ' is ' + str(new_weather['main']['temp']) + "\n Minimum Temperature is " + str(new_weather['main']['temp_min']) + "\n and " + "\n Maximum Temperature is " + str(new_weather['main']['temp_max']), 'description': '' }) weather_log = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'weather', 'description': 'Current Weather in ' + new_weather['name'] + ' has been updated.', 'error': '' }) new_notification(weather_notification) info_log(weather_log) if tts_enabled: try: tts('Current temperature in ' + new_weather['name'] + 'is' + str(new_weather['main']['temp']) + "Minimum Temperature is" + str(new_weather['main']['temp_min']) + "and" + "Maximum Temperature is" + str(new_weather['main']['temp_max'])) except RuntimeError: error_log(RuntimeError) with open('assets/weather.json', 'w') as weather_file: json.dump(new_weather, weather_file, indent=2)
def load_week_data(frq='w', adj='qfq'): try: with scheduler.app.app_context(): stock_set = StockBasic.find_all() for stock in stock_set: end = datetime.now() start = end - timedelta(days=7) try: data = ts.pro_bar( ts_code=stock.ts_code, freq=frq, adj=adj, start_date=datetime.strftime(start, _DateFormat), end_date=datetime.strftime(end, _DateFormat) ) except Exception as e: data = None if data is None: continue try: data = data.dropna(axis=0, how='any') data = data.loc[:, ['ts_code', 'trade_date', 'pre_close']] records = data.to_dict(orient='records') for record in records: record['trade_date'] = datetime.strptime(record['trade_date'], _DateFormat).date() ins = WeekModel.find_one(ts_code=record['ts_code'], date=record['trade_date']) if ins is None: WeekModel.create( commit=False, date=record['trade_date'], ts_code=record['ts_code'], close=record['pre_close'] ) else: ins.update( commit=False, date=record['trade_date'], ts_code=record['ts_code'], close=record['pre_close'] ) else: db.session.commit() except Exception as e: error_log(repr(e), exc_info=True) except Exception as e: error_log(repr(e), exc_info=True)
def get_covid_data(tts_enabled: bool): """ This function fetches data from api.coronavirus.data.gov using get method in requests module, creates a dictionary and store it in "covid_notifications.json" file. New Notification and info log is created each time new data is found """ url = "https://api.covid19india.org/v4/data-2020-12-04.json" data = requests.get(url).json() new_covid_data = data['DL'] with open('assets/covid_notifications.json', 'w') as covid_file: json.dump(new_covid_data, covid_file, indent=2) new_covid_notification = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'Covid News', 'title': "Covid News for Delhi" + " with" + " Total confirmed cases " + str(new_covid_data['total']['confirmed']) + " Todays confirmed cases " + str(new_covid_data['delta']['confirmed']) }) covid_logs = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'Covid News', 'description': "New Covid Data for Delhi", 'error': '' }) new_notification(new_covid_notification) info_log(covid_logs) if tts_enabled: try: tts("Covid News for Delhi" + " with " + " Total confirmed cases " + str(new_covid_data['total']['confirmed']) + " Todays confirmed cases " + str(new_covid_data['delta']['confirmed'])) except RuntimeError: error_log(RuntimeError) with open('assets/covid_notifications.json', 'w') as covid_file: json.dump(new_covid_data, covid_file, indent=2)
def notification_clear(): notificationTobeDeleted = request.args.get('notif') new_notification_object = [] with open(tmpdir + '/notifications.json', 'r') as notification_file: try: notification_list = json.load(notification_file) except Exception as error: notification_list = [] error_log(error) for notification in notification_list: if notification['title'] != notificationTobeDeleted: new_notification_object.append(notification) with open(tmpdir + '/notifications.json', 'w') as notification_file: json.dump(new_notification_object, notification_file, indent=2)
def print_results(responses): if responses is None: log("Empty results - None object") return for response in responses: if response is None: print("Empty results - skipping response") continue log("Received response with status: {}".format(ResponseStatus.Name(response.status))) if response.error: error_log("[ERROR]: {}".format(response.error)) for n, res in enumerate(response.results): transcript = " ".join([word.transcript for word in res.words]) log("[{}.] {} /{}/ ({})".format(n, transcript, res.semantic_interpretation, res.confidence))
def get_alarms() -> dict: """ This function reads the alarms.json file and returns its contents to a dictionary.This dictionary is used to show alarms in UI """ if filename.is_file(): with open(tmpdir + '/alarms.json', 'r') as alarms_file: try: alarm_list = json.load(alarms_file) except Exception: alarm_list = [] error_log(Exception) return alarm_list else: print("alarm file created") with open(tmpdir + '/alarms.json', 'x') as alarms_file: alarms_file.close() print("alarm file closed") return []
def get_big_deal(): try: with scheduler.app.app_context(): stock_set = StockBasic.find_all() now = datetime.now() for stock in stock_set: ts_code = stock.ts_code code, _ = ts_code.split('.') try: data = ts.get_sina_dd(code, date=datetime.strftime( now, DATE_FORMAT)) except Exception as e: data = None if data is None: continue try: data = data.dropna(axis=0, how='any') data = data.loc[:, ['price', 'volume', 'type']] records = data.to_dict(orient='records') for record in records: BigDeal.create(commit=False, ts_code=ts_code, date=now.date(), price=record['price'], volume=record['volume'], trade_type=record['type']) else: db.session.commit() info_log('get %s trade data succeed' % (ts_code, )) except Exception as e: error_log('get %s trade data failed: %s' % (ts_code, repr(e)), exc_info=True) random_int = random.randint(1, 10) time.sleep(random_int) except Exception as e: error_log(repr(e), exc_info=True)
def get_news(tts_enbled: bool) -> None: """ This function fetches the weather data from newssapi using api key provided in "config.json" and stores the data in "news.json" New Notification and info log is created each time new data is fetched """ api_key = get_api_key() country = 'in' url = 'https://newsapi.org/v2/top-headlines?country={}&apiKey={}' \ .format(country, api_key) new_news = requests.get(url).json() with open('assets/news.json', 'w') as news_file: json.dump(new_news, news_file, indent=2) for i in range(3): news_notification = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'News', 'title': new_news['articles'][i]['title'], 'description': '' }) news_log = ({ 'timestamp': time.strftime('%H:%M:%S'), 'type': 'news', 'description': 'New news articles' + new_news['articles'][i]['title'], 'error': '' }) new_notification(news_notification) info_log(news_log) if (tts_enbled): try: tts('New news story.' + new_news['articles'][i]['title']) except RuntimeError: error_log(RuntimeError) with open('assets/news.json', 'w') as news_file: json.dump(new_news, news_file, indent=2)