def __init__(self, portname, debug = False): ''' Create BG Monitor object ''' self.debug = debug self.bgm = AconBGM(portname, debug) self.polly = Polly() random.seed()
#!/usr/bin/env python3 import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) import paho.mqtt.client as mqtt import subprocess import urllib2 import speech_recognition as sr import os from time import ctime import time import datetime import sys from polly import Polly tts = Polly('Matthew') #globals light=0 seeds=100 user1="Anuj" user2="Abhishek" user1s=300 user2s=300 waste=0 live=0 GPIO.setup(17, GPIO.IN) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) GPIO.setup(26, GPIO.IN)
class VoiceBGM: ''' Voice-enabled Blood Glucose Monitor ''' # Status message dictionary status_dict = { AconBGM.BGM_STATUS_COMM_STATE: 'BG meter is ready. Please insert a test strip', AconBGM.BGM_STATUS_STRIP_INSERTED: 'Checking strip. Please wait...', AconBGM.BGM_STATUS_APPLY_SAMPLE: 'Apply blood sample to the test strip', AconBGM.BGM_STATUS_SAMPLE_APPLIED: 'Checking your blood sugar. Please wait...', AconBGM.BGM_STATUS_POWER_DOWN: 'Meter is turning off...', AconBGM.BGM_STATUS_RAW_DATA_READY: 'Raw data is ready', AconBGM.BGM_STATUS_STRIP_REMOVED: 'Strip has been removed', AconBGM.BGM_STATUS_TEST_COMPLETE: 'BG test complete', AconBGM.BGM_STATUS_REMOVE_STRIP: 'Please remove the test strip', } # Error message dictionary error_dict = { AconBGM.BGM_ERROR_METER: "Hardware failure", AconBGM.BGM_ERROR_CALIBRATION: "Internal calibration error", AconBGM.BGM_ERROR_SAMPLE_EARLY: "Blood sample applied too early", AconBGM.BGM_ERROR_USED_STRIP: "Contaminated or used strip", AconBGM.BGM_ERROR_SAMPLE_SMALL: "Blood sample too small", AconBGM.BGM_ERROR_TEMPERATURE_HIGH: "Temperature above limit", AconBGM.BGM_ERROR_TEMPERATURE_LOW: "Temperature below limit", AconBGM.BGM_ERROR_STRIP_CODE: "Strip code error", AconBGM.BGM_ERROR_HCT: "Hematocrit error", AconBGM.BGM_ERROR_CRC: "CRC error", AconBGM.BGM_ERROR_STRIP_REMOVED: "Strip removed while testing", AconBGM.BGM_ERROR_POWER: "Power error", } # Health tips tips = [ # Healthy eating tips 'Did you know that keeping healthy snacks with you like almonds can help you avoid overeating?', 'Did you know that the best time to eat a higher carb meal is right after you exercise?', 'Did you know that if you eat regularly throughout the day, you will have plenty of energy to complete your daily workout?', 'Did you know that whole grains are a healthy food-choice?', # Lifestyle tips 'Did you know that sitting for long periods of time can increase your risk of chronic disease?', 'Did you know that walking for an additional 20 minutes each day can help you lose around 7 pounds each year?', 'Did you know that walking briskly for 15 minutes will burn 100 calories?', 'Did you know that gardening for 30 minutes will burn 100 calories?', 'Did you know that doing housework for 30 minutes will burn 100 calories?', 'Did you know that it takes 21 days to form a habit?', 'Did you know that it is never too late to live a more active lifestyle?', 'Did you know that living an active lifestyle will improve your immune system, making you better able to fight off colds and infection?', 'Did you know that practicing yoga is a great way to reduce stress and anxiety?', 'Did you know that you are more likely to achieve your goals if you write them down?', 'Did you know that frequent reminders to make healthy choices will help you reach your goals?', 'Did you know that just 10 minutes of activity each day can improve your brain function?', 'Did you know that daily or weekly goals are more attainable than long-term goals?', 'Did you know that by starting your day with a workout, you are more likely to make healthy choices throughout the rest of the day?', 'Did you know that small changes can make big differences in your health?', 'Did you know that by eating a healthy diet and exercising regularly, you can keep your cholesterol and blood pressure in check?', # Other tips 'Did you know that traveling in an airplane can dehydrate you? Ask for water instead of soda to keep you hydrated throughout your flight.', 'Did you know that drinking a glass of water per hour when flying can prevent dehydration and minimize jet lag?', 'Did you know that taking a short walk after eating can aid in healthy digestion?', ] # Last BG (TODO: read these from a file) last_bg = 120 last_bg_time = 1550000000 def __init__(self, portname, debug = False): ''' Create BG Monitor object ''' self.debug = debug self.bgm = AconBGM(portname, debug) self.polly = Polly() random.seed() def play_mp3(self, filename): ''' Play MP3 audio file ''' subprocess.call(['mpg321', '-q', filename]) def speak_text(self, text): ''' Speak plain text ''' if self.debug: logging.debug(('Speaking: %s' %(text))) filename = self.polly.text_to_mp3(text) self.play_mp3(filename) def speak_random_tip(self): ''' Speak random health tip ''' cnt = len(self.tips) n = random.randint(0, cnt - 1) tip = 'Here\'s your daily health tip. ' + self.tips[n] self.speak_text(tip) def on_status(self, status): ''' Handle status change ''' if status not in self.status_dict: text = 'Unknown status' else: text = self.status_dict[status] self.speak_text(text) def on_result(self, bg, control): ''' Handle BG result ''' now = time.time() if control: text = 'Control solution sugar is {} mg per deciliter' else: text = 'Your blood sugar is {} mg per deciliter' self.speak_text(text.format(bg)) if not control: if self.last_bg: delta_bg = bg - self.last_bg if delta_bg > 1: text = 'This is {} points higher than'.format(delta_bg) elif delta_bg > 0: text = 'This is one point higher than' elif delta_bg < -1: text = 'This is {} points lower than'.format(abs(delta_bg)) elif delta_bg < 0: text = 'This is one point lower than' else: text = 'This is the same as' text += ' your last measurement, taken ' delta_t = int((now - self.last_bg_time) / 60) if delta_t < 15: text += 'a few minutes ago.' elif delta_t < 60: text += 'less than an hour ago.' elif delta_t < 120: text += 'about an hour ago.' elif delta_t < 1440: text += '{} hours ago.'.format(int(delta_t / 60)) else: t = time.localtime(self.last_bg_time) text += time.strftime('on %B %d at %I:%M %p.', t) self.speak_text(text) time.sleep(1) self.speak_random_tip() # Save current BG value and time self.last_bg = bg self.last_bg_time = now def on_error(self, error): ''' Handle error ''' if error not in self.error_dict: text = 'Unknown error' else: text = self.error_dict[error] text += '. Please remove the test strip and try again with a new strip.' self.speak_text(text) def test_voice(self): ''' Test all voice messages ''' # Speak all status messages for i in self.status_dict: self.on_status(i) # Speak all error messages for i in self.error_dict: self.on_error(i) # Speak BG result bgm.on_result(120, False) bgm.on_result(101, True) # Speak health tips for tip in self.tips: self.speak_text(tip) def run(self): ''' Run BG meter event loop ''' while True: msg = self.bgm.read_message() print("msg =", msg) self.bgm.handle_event(msg, self)
elif goal.funcion == 3: polly.borrarAudio(goal.nombreArchivo) # Error else: print( "Error: no se ha seleccionado ninguna hacion a realizar con el audio" ) result = AwsPollyResult() # se construye el mensaje de respuesta result.success = True server.set_succeeded(result) # se ha ennviado el goal OK except: result = AwsPollyResult() # se construye el mensaje de respuesta result.success = False server.set_succeeded(result) # se ha ennviado el goal OK # ---------------------------------------------------------------------------------------------------------------------------------------- # Main # ---------------------------------------------------------------------------------------------------------------------------------------- rospy.init_node('aws_polly_action') server = actionlib.SimpleActionServer( 'awsPolly', AwsPollyAction, callbackAwsPolly, False) # creamos el servidor de la accion # Los parametros son: nombre del servidor, tipo de la accion, funcion a ejecutar y variable que posibilita el inicio atomatico del servidor server.start() # iniciamos el servidor rospy.loginfo("Lanzamos el servidor aws_polly_action") polly = Polly(AWSsesion, rutaCatkin + '/audios') # Ejecutamos el contructor de polly rospy.spin() # el server queda a la espera de recibir el goal
app.config['BASIC_AUTH_PASSWORD'] = conf["flask_password"] app.config['BASIC_AUTH_FORCE'] = False app.config['SECRET_KEY'] = 'secret!' #Dice san google que no se puede poner *, por que se esta usando el tag # de credenciales, entonces en origins tenemos que poner, # el origin de la consulta que le mandamos desde el navegador :D CORS(app, resources={ r'/*': {'origins': ['http://localhost:4200']}}, supports_credentials=True) socketio = SocketIO(app, async_mode=async_mode,cors_allowed_origins='http://localhost:4200') #run_with_ngrok(socketio) thread = None thread_lock = Lock() polly = Polly('Joanna') s3client = boto3.resource('s3') rekoclient=boto3.client('rekognition') dynamodb = boto3.resource('dynamodb') dbPiFaces = dynamodb.Table('PiFaces_two') dbPiNgRok = dynamodb.Table('PiNgRok') dbPiMessages = dynamodb.Table('PiMessages_two') dbPiNotification= dynamodb.Table('PiNotification_two') expiresIn=5*24*3600 #expires recorded voice after 5 days basic_auth = BasicAuth(app) last_epoch = 0 last_upload = 0 motionCounter = 0
from polly import Polly import paho.mqtt.client as mqtt import sys print("Starting MQTTS") sys.stdout.flush() polly_tts = Polly('Brian') def on_connect(client, userdata, flags, rc): # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. print("ONCONNECT") client.subscribe("jarvis/tts") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): if msg.topic == "jarvis/tts": txt = msg.payload.decode("utf-8") print("TTS: " + txt) sys.stdout.flush() fname = polly_tts.processText(txt) print(fname) sys.stdout.flush() polly_tts.cleanup() client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message
from polly import Polly print("Starting TTS") tts = Polly('Brian') #tts.say('Hi there, I\'m very glad you\'re reading my article. Leave a comment if you find it useful.') fname = tts.processText('Test from laptop, with some more text') print(fname)