class HazardDetectionTests(unittest.TestCase): def setUp(self): rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') self.ch = RappPlatformAPI() def test_lightLeftOn(self): imagepath = path.join(self.pkgDir, 'test_data', 'hazard_detection_samples', 'lamp_on.jpg') response = self.ch.hazardDetectionLights(imagepath) self.assertEqual(response['error'], u'') self.assertEqual(response['light_level'] > 50, True) def test_erroneousPath(self): imagepath = path.join(self.pkgDir, 'test_data', 'lamp_on.jpg') response = self.ch.hazardDetectionLights(imagepath) self.assertNotEqual(response['error'], u'') def test_wrongPathType(self): imagepath = 3 response = self.ch.hazardDetectionLights(imagepath) self.assertNotEqual(response['error'], u'')
class QrDetectionTests(unittest.TestCase): def setUp(self): rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') self.ch = RappPlatformAPI() def test_detect_qr(self): imagepath = path.join(self.pkgDir, 'test_data','qr_code_rapp.jpg') valid_results = { 'qr_centers': [{'y': 165, 'x': 165}], 'qr_messages': ['rapp project qr sample'], 'error': '' } response = self.ch.qrDetection(imagepath) self.assertEqual(response, valid_results) def test_detect_qr_erroneous(self): response = self.ch.qrDetection('') self.assertNotEqual(response['error'], u'') response = self.ch.qrDetection(3) self.assertNotEqual(response['error'], u'') response = self.ch.qrDetection([]) self.assertNotEqual(response['error'], u'')
def RappObjectRecCaffe(self, imageString, image): path = imageORimageString(imageString, image) #path of saved image. ch = RappPlatformAPI(address=addr) response = ch.objectRecognitionCaffe( path) # Use the server's path of the image. return response
class DenoiseProfileTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') def test_setNoiseProfile(self): response = self.ch.setNoiseProfile(\ os.path.join(self.pkgDir, 'test_data', 'denoise_source.wav'), 'nao_wav_1_ch'\ ) self.assertEqual(response['error'], u'') def test_setNoiseProfile_noExistentFile(self): response = self.ch.setNoiseProfile('vim.exe', 'nao_wav_1_ch') self.assertNotEqual(response['error'], u'') def test_setNoiseProfile_wrongFileInputType(self): response = self.ch.setNoiseProfile(3, 'nao_wav_1_ch') self.assertNotEqual(response['error'], u'') def test_setNoiseProfile_wrongAudioTypeInputType(self): response = self.ch.setNoiseProfile('', []) self.assertNotEqual(response['error'], u'')
def RappSpeechDetectionGoogle(self, audioString, audioFile, language, audioSource): path = audioFileORaudioString(audioString, audioFile) ch = RappPlatformAPI() ###address = addr response = ch.speechRecognitionGoogle(path, audioSource, language) return response
class ObjectRecognitionTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') def test_cat_test(self): imagepath = path.join(self.pkgDir, 'test_data', 'cat.jpg') validResponse = { 'object_class': 'boa constrictor, Constrictor constrictor', 'error': '' } response = self.ch.objectRecognitionCaffe(imagepath) self.assertEqual(response, validResponse) def test_wrongPath(self): imagepath = path.join(self.pkgDir, '', 'cat.jpg') response = self.ch.objectRecognitionCaffe(imagepath) self.assertNotEqual(response['error'], u'') def test_wrongPathType(self): imagepath = 3 response = self.ch.objectRecognitionCaffe(imagepath) self.assertNotEqual(response['error'], u'')
def RappGeolocation(self, IP): #sys.path.append('../../../Thesis/rapp_portable/rapp-api/python') ch = RappPlatformAPI() #address = addr response = ch.geolocation(IP) if response.get('error') is not "": abort(500, response.get('error')) return response
class QrDetectionTests(unittest.TestCase): def setUp(self): rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') self.ch = RappPlatformAPI() def test_detect_qr(self): imagepath = path.join(self.pkgDir, 'test_data', 'qr_code_rapp.jpg') valid_results = { 'qr_centers': [{ 'y': 165, 'x': 165 }], 'qr_messages': ['rapp project qr sample'], 'error': '' } response = self.ch.qrDetection(imagepath) self.assertEqual(response, valid_results) def test_detect_qr_erroneous(self): response = self.ch.qrDetection('') self.assertNotEqual(response['error'], u'') response = self.ch.qrDetection(3) self.assertNotEqual(response['error'], u'') response = self.ch.qrDetection([]) self.assertNotEqual(response['error'], u'')
class HumanDetectionTests(unittest.TestCase): def setUp(self): rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') self.ch = RappPlatformAPI() def test_humanDetectionTest(self): image = path.join(self.pkgDir, 'test_data', 'human_detection_samples', 'NAO_picture_3.png') valid_humans = [{ 'up_left_point': {'y': 30.0, 'x': 48.0}, 'down_right_point': {'y': 399.0, 'x': 232.0} }] response = self.ch.humanDetection(image) self.assertEqual(response['error'], u'') self.assertEqual(response['humans'], valid_humans) def test_humanDetectionTest_wrongPath(self): image = path.join(self.pkgDir, '', 'human_detection_samples', 'NAO_picture_3.png') response = self.ch.humanDetection(image) self.assertNotEqual(response['error'], u'') def test_humanDetectionTest_wrongPathType(self): image = 3 response = self.ch.humanDetection(image) self.assertNotEqual(response['error'], u'')
def RappLightDetection(self, imageString, image): path = imageORimageString(imageString, image) #path of saved image. ch = RappPlatformAPI(address=addr) response = ch.hazardDetectionLights( path) # Use the server's path of the image. return response
def RappText2Speech(self, text, language): ch = RappPlatformAPI(address=addr) response = ch.textToSpeech(text, language, RAPPtext2speech_full_path) f = open( RAPPtext2speech_full_path, 'r' ) #at RPi: f = open(RAPPtext2speech_full_path).read() #serializable return f
def __init__(self, creds={}, recipients=[]): """ Default Constructor.""" self.language = 'el' self.askValidation = True self.waitOnAnswer = 5 self.rh = RappRobot() self.ch = RappPlatformAPI() self.emailCreds = {'username': '', 'password': ''} self.__load_email_credentials() if 'username' in creds: self.emailCreds['username'] = creds['username'] if 'password' in creds: self.emailCreds['password'] = creds['password'] print self.emailCreds if self.emailCreds['username'] == '' or self.emailCreds[ 'password'] == '': self.say( u'Δεν βρήκα καταχωρημένα τα στοιχεία λογαριασμού ηλεκτρονικού ταχυδρομίου. Παρακαλώ επικοινώνησε με την τεχνική υπηρεσια.' ) self.rh.humanoid_motion.goToPosture('Sit', 0.5) sys.exit(1) self.emailTitle = "NAO SendMail RApp" self.emailBody = "Hello I am NAO robot :)\n\n" + \ "This is an automated email that the user" + \ " requested to send among with the attachment files!\n\n" + \ "Robots are awesome!! :-)" self.recipients = recipients
def RappQrDetection(self, imageString, image): path = imageORimageString(imageString, image) #path of saved image. ch = RappPlatformAPI() ###############address = addr response = ch.qrDetection(path) # Use the server's path of the image. if not response.get('error') == "": abort(500, response.get('error')) return response
def __init__(self): """ Default Constructor.""" self.language = 'el' self.askValidation = True self.waitOnAnswer = 5 self.rh = RappRobot() self.ch = RappPlatformAPI() self._loc = self.ch.geolocation(Net.ipaddr_connected()) print '[*] Current Location: {0}'.format(self._loc)
def __init__(self): self.frames = [] self.pa = pyaudio.PyAudio() self.stream = self.open_mic_stream() self.tap_threshold, self.noise_threshold = self.calibrate() self.hear = False self.ch = RappPlatformAPI() topic = rospy.get_param("rec_topic") self.publisher = rospy.Publisher(topic, String, queue_size=10)
def getExercise(test_type="", test_subtype="", test_diff="", test_index=""): ch = RappPlatformAPI() response = ch.cognitiveExerciseSelect(test_type=test_type, test_subtype=test_subtype, test_diff=test_diff, test_index=test_index) if response['error'] != '': print response['error'] sys.exit(0) for key, val in response.iteritems(): print key, val testInstance = response['test_instance'] testType = response['test_type'] testSubType = response['test_subtype'] questions = response['questions'] possibAns = response['possib_ans'] correctAns = response['correct_ans'] language = response['lang'] cogTest = CognitiveTest(testType, testSubType, testInstance, questions, possibAns, correctAns, language) if testType == 'ArithmeticCts': if testSubType == 'BasicArithmeticCts': return BasicArithmericCts(cogTest) elif testSubType == 'TimeDifferenceCts': return TimeDifferenceCts(cogTest) elif testSubType == 'TransactionChangeCts': return TransactionChangeCts(cogTest) else: return None elif testType == 'AwarenessCts': if testSubType == 'TimeDayYearCts': return TimeDayYearCts(cogTest) else: return None elif testType == 'ReasoningCts': if testSubType == 'StoryTellingCts': return StoryTellingCts(cogTest) elif testSubType == 'WordRememberingCts': return WordRememberingCts(cogTest) else: return None else: return None
def setUp(self): self.ch = RappPlatformAPI() # Wait till the service is up using an erroneous call for fast return counter = 0 timeout = 120 while counter < timeout: counter = counter + 1 res = self.ch.cognitiveExerciseSelect(0) if res['error'] != u'Connection Error': break time.sleep(1) print 'Waiting for service... ' + str(timeout - counter) if counter == timeout: self.assertEqual('Connection error', True)
def RappDoorDetection(self, imageString, image): path = imageORimageString(imageString, image) #path of saved image. ch = RappPlatformAPI() #################address = addr #im=Image.open(image) #im.save("/home/panos/Desktop/Swagger/finalTest/test_v5/Door.png","PNG", progressive = True) #Path to save the image on the server. ### deinterlacing # #size=list(im.size) #size[0] /= 2 #size[1] /= 2 #downsized=im.resize(self, size, Image.NEAREST) # NEAREST drops the lines #downsized.save("/home/panos/Desktop/Swagger/finalTest/test_v5/Door.png") ####### response = ch.hazardDetectionDoor( path) # Use the server's path of the image. return response
def __init__(self, email_username, email_pass, recipients=[]): """ Default Constructor.""" self.language = 'el' self.askValidation = True self.waitOnAnswer = 5 self.rh = RappRobot() self.ch = RappPlatformAPI() self.emailUsername = email_username self.emailPass = email_pass self.emailTitle = "NAO SendMail RApp" self.emailBody = "Hello I am NAO robot :)\n\n" + \ "This is an automated email that the user" + \ " requested to send among with the attachment files!\n\n" + \ "Robots are awesome!! :-)" self.recipients = recipients
class TextToSpeechTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() def test_greek_test(self): destFilePath = '/tmp/ttsClient.wav' response = self.ch.textToSpeech('Καλησπέρα. Είμαι ο ναο', 'el', destFilePath) self.assertEqual(response['error'], u'') self.assertEqual(os.path.getsize(destFilePath) > 0, True) def test_tts_erroneous(self): destFilePath = '/tmp/ttsClient.wav' response = self.ch.textToSpeech(3, 'el', destFilePath) self.assertNotEqual(response['error'], u'') response = self.ch.textToSpeech([], 'el', destFilePath) self.assertNotEqual(response['error'], u'') #response = self.ch.textToSpeech('Καλησπέρα. Είμαι ο ναο', '', destFilePath) #self.assertNotEqual(response['error'], u'') response = self.ch.textToSpeech('Καλησπέρα. Είμαι ο ναο', 3, destFilePath) self.assertNotEqual(response['error'], u'') response = self.ch.textToSpeech('Καλησπέρα. Είμαι ο ναο', [], destFilePath) self.assertNotEqual(response['error'], u'') #response = self.ch.textToSpeech('Καλησπέρα. Είμαι ο ναο', 'el', '') #self.assertNotEqual(response['error'], u'') response = self.ch.textToSpeech('Καλησπέρα. Είμαι ο ναο', 'el', []) self.assertNotEqual(response['error'], u'') response = self.ch.textToSpeech('Καλησπέρα. Είμαι ο ναο', 'el', 3) self.assertNotEqual(response['error'], u'')
class SppechDetectionGoogleTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') def test_speechNormal(self): audioFile = path.join(self.pkgDir, 'test_data', 'speech_detection_samples', 'recording_sentence1.ogg') valid_words_found = ['I', 'want', 'to', 'go', 'out'] response = self.ch.speechRecognitionGoogle(audioFile, 'nao_ogg', 'en') self.assertEqual(response['error'], u'') self.assertEqual(response['words'], valid_words_found) def test_erroneous(self): audioFile = path.join(self.pkgDir, 'test_data', 'speech_detection_samples', 'recording_sentence1.ogg') response = self.ch.speechRecognitionGoogle('', 'nao_ogg', 'en') self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle(3, 'nao_ogg', 'en') self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle([], 'nao_ogg', 'en') self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle(audioFile, '', 'en') self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle(audioFile, 3, 'en') self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle(audioFile, [], 'en') self.assertNotEqual(response['error'], u'') # response = self.ch.speechRecognitionGoogle(audioFile, 'nao_ogg', 'klklklkl') # self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle(audioFile, 'nao_ogg', '') self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle(audioFile, 'nao_ogg', 3) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionGoogle(audioFile, 'nao_ogg', []) self.assertNotEqual(response['error'], u'')
def RappSpeechDetectionSphinx(self, audioString, audioFile, language, audioSource, words=None, sentences=None, grammar=None): path = audioFileORaudioString(audioString, audioFile) ch = RappPlatformAPI(address=addr) response = ch.speechRecognitionSphinx(path, language=language, audio_source=audioSource, words=words, sentences=sentences, grammar=grammar) #f=open('/home/panos/Desktop/Swagger/finalTest/test_v3/RappGoogle.wav','r') return response
def __init__(self, cog_test): """ Constructor """ self.language = cog_test.language self.audioSource = Constants.AUDIO_SOURCE self.tempDir = Constants.TEMP_DIR self.cogTest = cog_test self.recordTime = 5 self.maxReruns = 3 self.askValidation = True self.rh = RappRobot() self.ch = RappPlatformAPI() self.performance = { 'correct_answers': 0, 'wrong_answers': 0, 'final_score': 0 } self.print_info()
def __init__(self): self.rh = RappRobot() self.ch = RappPlatformAPI() rospy.Timer(rospy.Duration(0.1), self.sonarsCallback) rospy.Timer(rospy.Duration(5), self.qrDetectionCallback) #self.pub = rospy.Publisher('/inner/sonar_measurements', LaserScan, queue_size=1) self.pub1 = rospy.Publisher('/inner/qr_detection', RfidSensorMeasurementMsg, queue_size=1) self.s = rospy.Service('set_object', SetObject, self.setNewObjectCallback) self.s1 = rospy.Service('get_objects', GetObjects, self.getObjectsCallback) self.objects = {} self.static_objects = []
class HumanDetectionTests(unittest.TestCase): def setUp(self): rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') self.ch = RappPlatformAPI() def test_humanDetectionTest(self): image = path.join(self.pkgDir, 'test_data', 'human_detection_samples', 'NAO_picture_3.png') valid_humans = [{ 'up_left_point': { 'y': 30.0, 'x': 48.0 }, 'down_right_point': { 'y': 399.0, 'x': 232.0 } }] response = self.ch.humanDetection(image) self.assertEqual(response['error'], u'') self.assertEqual(response['humans'], valid_humans) def test_humanDetectionTest_wrongPath(self): image = path.join(self.pkgDir, '', 'human_detection_samples', 'NAO_picture_3.png') response = self.ch.humanDetection(image) self.assertNotEqual(response['error'], u'') def test_humanDetectionTest_wrongPathType(self): image = 3 response = self.ch.humanDetection(image) self.assertNotEqual(response['error'], u'')
class CognitiveTestHistoryTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() def test_historyArithmetic(self): response = self.ch.cognitiveGetHistory('ArithmeticCts', 0, 100000000) self.assertEqual(response['error'], u'') self.assertNotEqual(len(response['records']), 0) def test_historyReasoning(self): response = self.ch.cognitiveGetHistory('ReasoningCts', 0, 100000000) self.assertEqual(response['error'], u'') self.assertNotEqual(len(response['records']), 0) def test_historyAwareness(self): response = self.ch.cognitiveGetHistory('AwarenessCts', 0, 100000000) self.assertEqual(response['error'], u'') self.assertNotEqual(len(response['records']), 0) def test_historyAll(self): response = self.ch.cognitiveGetHistory('', 0, 100000000) self.assertEqual(response['error'], u'') self.assertNotEqual(len(response['records']), 0) def test_history_wrongType(self): response = self.ch.cognitiveGetHistory('T', 0, 100000000) self.assertNotEqual(response['error'], u'') def test_history_wrongTypeType(self): response = self.ch.cognitiveGetHistory(0, 0, 100000000) self.assertNotEqual(response['error'], u'') def test_history_wrongFromType(self): response = self.ch.cognitiveGetHistory('', '0', 100000000) self.assertNotEqual(response['error'], u'') def test_history_wrongToType(self): response = self.ch.cognitiveGetHistory('T', 0, '100000000') self.assertNotEqual(response['error'], u'')
class CognitiveTestScoresTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() def test_scoresArithmetic(self): response = self.ch.cognitiveGetScores('ArithmeticCts', 100000000) self.assertEqual(response['error'], u'') self.assertEqual(len(response['scores']), 1) self.assertEqual(len(response['test_classes']), 1) def test_scoresAwareness(self): response = self.ch.cognitiveGetScores('AwarenessCts', 100000000) self.assertEqual(response['error'], u'') self.assertEqual(len(response['scores']), 1) self.assertEqual(len(response['test_classes']), 1) def test_scoresReasoning(self): response = self.ch.cognitiveGetScores('ReasoningCts', 100000000) self.assertEqual(response['error'], u'') self.assertEqual(len(response['scores']), 1) self.assertEqual(len(response['test_classes']), 1) def test_scoresAll(self): response = self.ch.cognitiveGetScores('', 100000000) self.assertEqual(response['error'], u'') self.assertEqual(len(response['scores']) > 0, True) self.assertEqual(len(response['test_classes']) > 0, True) def test_scoresWrongType(self): response = self.ch.cognitiveGetScores(3, 100000000) self.assertNotEqual(response['error'], u'') def test_scoresWrongTypeList(self): response = self.ch.cognitiveGetScores([], 100000000) self.assertNotEqual(response['error'], u'') def test_scoresWrongType_to(self): response = self.ch.cognitiveGetScores('', '100000000') self.assertNotEqual(response['error'], u'')
class SendMail(object): ## Default constructor def __init__(self, email_username, email_pass, recipients=[]): """ Default Constructor.""" self.language = 'el' self.askValidation = True self.waitOnAnswer = 5 self.rh = RappRobot() self.ch = RappPlatformAPI() self.emailUsername = email_username self.emailPass = email_pass self.emailTitle = "NAO SendMail RApp" self.emailBody = "Hello I am NAO robot :)\n\n" + \ "This is an automated email that the user" + \ " requested to send among with the attachment files!\n\n" + \ "Robots are awesome!! :-)" self.recipients = recipients def run(self): try: self.rh.motion.enableMotors() self.rh.humanoid_motion.goToPosture('Sit', 0.5) self.intro() emails = self.get_available_emails() self.ask_for_recipients(emails) recDest = self.phase_record_speech() imgDest = self.phase_capture_photo() files = [] if recDest is not None: files.append(recDest) if imgDest is not None: files.append(imgDest) print files zipDest = self.make_zip(files) resp = self.ch.emailSend(self.emailUsername, self.emailPass, 'smtp.gmail.com', '587', self.recipients, self.emailBody, self.emailTitle, zipDest) self.rh.humanoid_motion.goToPosture('Sit', 0.5) self.rh.motion.disableMotors() except Exception as e: print e.message self.error_termination() if resp['error'] != '': print resp['error'] self.say(u'Αποτυχία αποστολής μέιλ.') self.say(u'Τερματισμός εφαρμογής.') sys.exit(1) else: self.say(u'Το μέιλ στάληκε επιτυχώς') self.say(u'Τερματισμός εφαρμογής.') sys.exit(0) def intro(self): msg = u'Καλησπέρα. Η εφαρμογή αυτή θα σε καθοδηγήσει στο να φτιάξεις και να στείλεις ένα μέιλ.' msg += u' Μπορείς να στείλεις ένα ηχογραφημένο ηχητικό μήνυμα, ή και μία φωτογραφία.' msg += u' Άς ξεκινήσουμε.' self.say(msg) def say(self, msg, animated=True): self.rh.audio.speak(msg, self.language, animated=animated) def phase_record_speech(self): msg = u'Θες να ηχογραφήσω ηχητικό μήνυμα?' self.say(msg) detected = 'Rerun' while detected == 'Rerun': detected = self.detect_yes() if detected == 'Rerun': continue elif detected: break elif not detected: return None else: pass detected = 'Rerun' msg = u'Επέλεξε διάρκεια ηχογράφησης σε δευτερόλεπτα.' self.say(msg) msg = u' Δέκα? Είκοσι? Τριάντα? Σαράντα? Πενήντα? ή Εξήντα?' self.say(msg) while detected == 'Rerun': voc = [ u'δέκα', u'είκοσι', u'τριάντα', u'σαράντα', u'πενήντα', u'εξήντα' ] resp = self.rh.audio.speechDetection(voc, self.waitOnAnswer, self.language) try: print 'Detect-Words: word: {0}, probability: {1}, error: {2}'.format( resp['word'], resp['probability'], resp['error']) except Exception as e: print e.message if resp['error'] or resp['probability'] < 0.4: # Threshold prob self.rh.audio.speak(u'Δεν άκουσα. Μιλήστε πιο δυνατά παρακαλώ', self.language, True) detected = 'Rerun' continue elif self.askValidation: usrAns = self.ask_validation(resp['word'].decode('utf8')) if not usrAns: detected = 'Rerun' self.say(u'Επανέλαβε την απάντηση παρακαλώ.') continue break if resp['word'].decode('utf8').lower() in [u'δέκα', u'δεκα']: recT = 10 elif resp['word'].decode('utf8').lower() in [u'είκοσι', u'εικοσι']: recT = 20 elif resp['word'].decode('utf8').lower() in [u'τριάντα', u'τριαντα']: recT = 30 elif resp['word'].decode('utf8').lower() in [u'σαράντα', u'σαραντα']: recT = 40 elif resp['word'].decode('utf8').lower() in [u'πενήντα', u'πενηντα']: recT = 50 elif resp['word'].decode('utf8').lower() in [u'εξήντα', u'εξηντα']: recT = 60 self.rh.humanoid_motion.goToPosture('Sit', 0.5) self.say(u'Θα ξεκινήσω την ηχογράφηση σε,', animated=False) self.say(u'Τρία', animated=False) time.sleep(1) self.say(u'Δύο', animated=False) time.sleep(1) self.say(u'Ένα', animated=False) time.sleep(1) self.say(u'Η ηχογράφηση ξεκίνησε', animated=False) fDest = self.record(recT) self.say(u'Τερματισμός ηχογράφησης.', animated=False) return fDest def phase_capture_photo(self): msg = u'Θες να στείλεις φωτογραφία στο μέιλ?' self.say(msg) detected = 'Rerun' while detected == 'Rerun': detected = self.detect_yes() if detected == 'Rerun': continue elif detected: break elif not detected: return None else: pass self.say(u'Παρακαλώ πάρε θέση μπροστά από εμένα και κοίτα στην κάμερα που βρίσκεται στο κεφάλι μου.') self.rh.humanoid_motion.goToPosture('Sit', 0.5) self.say(u'Θα φωτογραφίσω σε,', animated=False) self.say(u'Τρία', animated=False) time.sleep(1) self.say(u'Δύο', animated=False) time.sleep(1) self.say(u'Ένα', animated=False) time.sleep(1) photoDest = self.take_picture() self.say(u'Οκ, η φωτογραφία είναι έτοιμη.') return photoDest def take_picture(self): photoDest = "{0}/photo-{1}.{2}".format(Constants.TEMP_DIR, ''.join([str(randint(0, 9)) for p in range(0, 9)]), 'jpg') self.rh.vision.capturePhoto(photoDest, 'front', '640x480') return photoDest def record(self, recordTime): """ Use this method to record users speech. @type recordTime: Int @param recordTime: Duration of the recording in seconds """ taskId = self.rh.sensors.rastaLedsOn() recDest = "{0}/micrec-{1}.{2}".format(Constants.TEMP_DIR, ''.join([str(randint(0, 9)) for p in range(0, 9)]), 'wav') self.rh.audio.record(recDest, recordTime, 'wav', 16000, [0, 0, 1, 0]) self.rh.sensors.rastaLedsOff(taskId) return recDest def error_termination(self): """ Inform on termination with error.""" self.rh.audio.speak(u'Κατι πήγε λαθος στο σύστημα. Άμεσος τερματισμός!', self.language, True) sys.exit(0) def detect_words(self, possibAns, correctAns, waitT): """ Detect words given by possible answers and correct answer. Using the SpeechDetectionSphinx4 Platform service to perform speech detection. @param possibAns @param correctAns @param waitT """ print color.cyan + '----------> Detect Words' + color.clear print "Words:" for w in possibAns: print w.encode("utf-8") print "ans: " + correctAns.encode("utf-8") print color.cyan + '<----------------------' + color.clear for i in range(0, len(possibAns)): possibAns[i] = possibAns[i].replace(" ", "-") correctAns = correctAns.replace(" ", "-") resp = self.rh.audio.speechDetection(possibAns, waitT, self.language) try: print 'Detect-Words: word: {0}, probability: {1}, error: {2}'.format( resp['word'], resp['probability'], resp['error']) except Exception as e: print e.message if resp['error'] or resp['probability'] < 0.4: # Threshold prob self.rh.audio.speak(u'Δεν άκουσα. Μιλήστε πιο δυνατά παρακαλώ', self.language, True) return 'Rerun', '<unk>' if self.askValidation: usrAns = self.ask_validation(resp['word'].decode('utf8')) if not usrAns: return 'Rerun', '<unk>' if resp['word'] == correctAns.encode('utf8'): return True, resp['word'].replace("-", " ") else: return False, resp['word'].replace("-", " ") def detect_yes(self, waitT=5.0): """ Method to recognize yes/no (ναι/οχι) words.""" if self.language == 'el': possibAns = [u'ναι', u'οχι'] correctAns = u'ναι' elif self.language == 'en': possibAns = ['yes', 'no'] correctAns = 'yes' else: pass resp = self.rh.audio.speechDetection(possibAns, waitT, self.language) try: print 'Detect-Yes: word: {0}, probability: {1}, error: {2}'.format( resp['word'], resp['probability'], resp['error']) except Exception as e: print e.message if resp['error'] or resp['probability'] < 0.4: # Threshold prob self.rh.audio.speak(u'Δεν άκουσα. Μιλήστε πιο δυνατά παρακαλώ', self.language, True) return 'Rerun' elif resp['word'] == correctAns.encode('utf8'): return True else: return False def ask_validation(self, ans): while True: self.rh.audio.speak(u'Είπατε... %s ?' % ans, self.language, True) detected = self.detect_yes() if detected == 'Rerun': pass else: return detected def make_zip(self, files=[]): if isinstance(files, list): if len(files) == 0: print "No attachment files" return '' dest = '{0}/archive.zip'.format(Constants.TEMP_DIR) zfh = zipfile.ZipFile(dest, 'w') for idx, val in enumerate(files): zfh.write(val, path.basename(val)) zfh.printdir() zfh.close() return dest else: raise TypeError('Argument files must be of type list') return None def get_available_emails(self): resp = self.ch.userPersonalInfo() emails = resp['emails'] if len(emails) == 0: self.say(u'Ο συγκεκριμένος χρήστης δεν έχει καταχωρημένες διευθύνσεις αποστολής ηλεκτρονικών μηνυμάτων.') self.say(u'Τερματισμός εφαρμογής') sys.exit(1) return emails def ask_for_recipients(self, emails): while True: for idx, val in enumerate(emails): msg = u'Να προσθέσω τον χρήστη {0} στην λίστα με τους παραλήπτες?'.format(emails[idx]['user']) self.say(msg) detected = 'Rerun' while detected == 'Rerun': detected = self.detect_yes() if detected == 'Rerun': continue elif detected: self.recipients.append(emails[idx]['email_address']) elif not detected: break else: pass if len(self.recipients) == 0: self.say('Παρακαλώ επέλεξε τουλάχιστον ένα παραλήπτη') else: break print self.recipients
class CognitiveExercise(object): """ Cognitive Exercises Base Class.""" def __init__(self, cog_test): """ Constructor """ self.language = cog_test.language self.audioSource = Constants.AUDIO_SOURCE self.tempDir = Constants.TEMP_DIR self.cogTest = cog_test self.recordTime = 5 self.maxReruns = 3 self.askValidation = True self.rh = RappRobot() self.ch = RappPlatformAPI() self.performance = { 'correct_answers': 0, 'wrong_answers': 0, 'final_score': 0 } self.print_info() def run(self): """ Execute this cognitive exercise application. """ try: self.rh.motion.enableMotors() self.rh.humanoid_motion.goToPosture("Sit", 0.5) self.intro() self.pronounce_questions() ex = self.score() self.rh.humanoid_motion.goToPosture("Sit", 0.5) self.rh.motion.disableMotors() except Exception as e: print e.message self.error_termination() if ex: sys.exit(0) # Process exit success status else: sys.exit(1) # Process exit error status def record_voice(self, recordTime): """ Use this method to record users speech. @type recordTime: Int @param recordTime: Duration of the recording in seconds """ taskId = self.rh.sensors.rastaLedsOn() recDest = "{0}/micrec-{1}.{2}".format(Constants.TEMP_DIR, ''.join([str(randint(0, 9)) for p in range(0, 9)]), 'wav') self.rh.audio.record(recDest, recordTime, 'wav', 16000, [0, 0, 1, 0]) self.rh.sensors.rastaLedsOff(taskId) return recDest def error_termination(self): """ Inform on termination with error.""" self.rh.audio.speak(u'Κατι πήγε λαθος στο σύστημα. Άμεσος τερματισμός!', self.language, True) sys.exit(0) def detect_words(self, language, possibAns, correctAns, waitT): """ Detect words given by possible answers and correct answer. Using the SpeechDetectionSphinx4 Platform service to perform speech detection. @param language @param possibAns @param correctAns @param waitT """ print color.cyan + '----------> Detect Words' + color.clear print "Words:" for w in possibAns: print w.encode("utf-8") print "ans: " + correctAns.encode("utf-8") print color.cyan + '<----------------------' + color.clear for i in range(0, len(possibAns)): possibAns[i] = possibAns[i].replace(" ", "-") correctAns = correctAns.replace(" ", "-") resp = self.rh.audio.speechDetection(possibAns, waitT, self.language) try: print 'Detect-Words: word: {0}, probability: {1}, error: {2}'.format( resp['word'], resp['probability'], resp['error']) except Exception as e: print e.message if resp['error'] or resp['probability'] < 0.4: # Threshold prob self.rh.audio.speak(u'Δεν άκουσα. Μιλήστε πιο δυνατά παρακαλώ', self.language, True) return 'Rerun', '<unk>' if self.askValidation: usrAns = self.ask_validation(resp['word'].decode('utf8')) if not usrAns: return 'Rerun', '<unk>' if resp['word'] == correctAns.encode('utf8'): return True, resp['word'].replace("-", " ") else: return False, resp['word'].replace("-", " ") def intro(self): """Intro to cognitive exercises.""" self.rh.audio.speak(u'Ας ξεκινήσουμε τα παιχνίδια γνώσεων', self.language, True) # TODO inform user on selected exercise class. # self.tts(u'Η κατηγορία ασκήσεων είναι... ' + ) flag = False waitOnAnswer = 3 # seconds while not flag: self.rh.audio.speak(u'Εισαι ετοιμος για να ξεκινήσουμε το παιχνίδι?', self.language, True) detected = self.detect_yes(self.language, waitOnAnswer) if detected == 'Rerun': pass elif detected: self.rh.audio.speak(u'Τέλεια! Ας ξεκινήσουμε.', self.language, True) flag = True elif not detected: self.rh.audio.speak(u'Τερματισμός ασκήσεων γνώσης.', self.language, True) sys.exit(0) else: pass def print_info(self): """Print Selected cognitive exercise general information.""" print color.ok + "\n" + \ '**************************************************' + '\n' + \ '******** [Cognitive Exercises Information] *******' + '\n' + \ '**************************************************' + '\n' + \ color.clear + color.yellow + '\n' + \ '- [Test type]: ' + color.clear + self.cogTest.testType + \ color.yellow + '\n\n' + \ '- [Test Instance]: ' + color.clear + self.cogTest.instance + \ color.yellow + '\n\n' + \ '- [Test SubType]: ' + color.clear + self.cogTest.testSubType + \ color.yellow + '\n\n' + \ '- [Questions]:' + color.clear for q in self.cogTest.questions: print ' %s] ' % (self.cogTest.questions.index(q) + 1) + \ q.encode('utf8') print color.yellow + '\n' + '- [Possible Answers]: ' + color.clear for outer in self.cogTest.possibAns: qIndex = self.cogTest.possibAns.index(outer) print ' * Question #%s: %s' % ( qIndex, self.cogTest.questions[qIndex].encode('utf8')) for a in outer: aIndex = outer.index(a) print ' %s] ' % (aIndex) + a.encode('utf-8') print color.yellow + '\n' + '- [Correct Answers]' + color.clear for ca in self.cogTest.correctAns: print ' * Question #%s: %s' % \ (self.cogTest.correctAns.index(ca), ca.encode('utf-8')) print color.ok + "\n" + \ '**************************************************' + '\n' + \ '**************************************************' + '\n' + \ color.clear def print_score_info(self): """ Print final performance results. """ print color.ok + "\n" + \ '**************************************************' + '\n' + \ '********** [Cognitive Exercises Results] *********' + '\n' + \ '**************************************************' + '\n' + \ color.clear print color.success + '[Correct Answers]: ' + color.cyan + \ str(self.performance['correct_answers']) + color.clear + '\n' print color.success + '[Wrong Answers]: ' + color.cyan + \ str(self.performance['wrong_answers']) + color.clear + '\n' print color.yellow + '[Final Score]: ' + color.cyan + \ str(self.performance['final_score']) + color.clear def score(self): """ Calculate final score, pronounce it and send to the Cloud to record user's performance under the ontology. """ numQ = len(self.cogTest.questions) self.performance['final_score'] = 100.0 * \ self.performance['correct_answers'] / numQ self.print_score_info() self.rh.audio.speak(u'Το σκορ είναι', self.language, True) msg = u'%s σωστές απαντήσεις από τις %s ερωτήσεις' % \ (self.performance['correct_answers'], numQ) self.rh.audio.speak(msg, self.language, True) time.sleep(1) # -------------------------------------------------------------------- # Call this Platform service in order to record users performance taskId = self.rh.sensors.randomEyesOn() response = self.ch.cognitiveRecordPerformance( test_instance=self.cogTest.instance, score=self.performance['final_score']) self.rh.sensors.randomEyesOff(taskId) # -------------------------------------------------------------------- if response['error']: print response['error'] msg = u'Αποτυχία εγγραφής του τελικού σκορ' self.rh.audio.speak(msg, self.language, True) return False else: msg = u'Το σκορ σας καταγράφηκε στο σύστημα' self.rh.audio.speak(msg, self.language, True) return True def detect_yes(self, language, waitT=5.0): """ Method to recognize yes/no (ναι/οχι) words.""" if language == 'el': possibAns = [u'ναι', u'οχι'] correctAns = u'ναι' elif language == 'en': possibAns = ['yes', 'no'] correctAns = 'yes' else: pass resp = self.rh.audio.speechDetection(possibAns, waitT, self.language) try: print 'Detect-Yes: word: {0}, probability: {1}, error: {2}'.format( resp['word'], resp['probability'], resp['error']) except Exception as e: print e.message if resp['error'] or resp['probability'] < 0.4: # Threshold prob self.rh.audio.speak(u'Δεν άκουσα. Μιλήστε πιο δυνατά παρακαλώ', self.language, True) return 'Rerun' elif resp['word'] == correctAns.encode('utf8'): return True else: return False def pronounce_questions(self): """ Core of the Exercise execution. - Pronounce questions. - Capture answers. - Recognise answer based on Platform's Speech-Recognition service. - Validate answer. """ waitOnAnswer = 5 # Seconds numQ = len(self.cogTest.questions) self.rh.audio.speak(u'Έχω ετοιμάσει %s ερωτήσεις' % numQ, self.language, True) time.sleep(1) self.rh.audio.speak(u'Ας ξεκινήσουμε τις ερωτήσεις', self.language, True) for i in range(0, numQ): reruns = 0 detected = 'Rerun' self.rh.audio.speak(u'Ερώτηση %s' % (i+1), self.language, True) # time.sleep(1) self.rh.audio.speak(self.cogTest.questions[i], self.language, True) # time.sleep(1) possAns = self.cogTest.possibAns[i] correctAns = self.cogTest.correctAns[i] while detected == 'Rerun': detected, wordDetected = self.detect_words(self.language, possAns, correctAns, waitOnAnswer) if detected == 'Rerun': reruns = reruns + 1 if reruns == self.maxReruns: self.rh.audio.speak( u'{0} αποτυχημένες προσπάθειες.'.format(reruns), self.language, True) self.ask_random_ans(possAns, correctAns) break # Break while loop else: # Rerun self.rh.audio.speak( u'Επανέλαβε την απάντηση παρακαλώ.', self.language, True) elif detected: self.performance['correct_answers'] += 1 self.rh.audio.speak(u'Σωστό!', self.language, True) elif not detected: self.performance['wrong_answers'] += 1 self.rh.audio.speak(u'Λάθος απάντηση', self.language, True) else: pass def ask_random_ans(self, possAns, correctAns): randAns = possAns[randint(0, len(possAns) - 1)] isValid = True if \ randAns.encode('utf8') == correctAns.encode('utf8') else False while True: self.rh.audio.speak(u'Είναι η σωστή απάντηση ... %s ?' % randAns, self.language, True) detected = self.detect_yes(self.language, self.recordTime) if detected == 'Rerun': self.rh.audio.speak(u'Επανάληψη.', self.language, True) pass elif detected == isValid: self.performance['correct_answers'] += 1 self.rh.audio.speak(u'Σωστό!', self.language, True) return True else: self.performance['wrong_answers'] += 1 self.rh.audio.speak(u'Λάθος απάντηση', self.language, True) return False def ask_validation(self, ans): while True: self.rh.audio.speak(u'Είπατε... %s ?' % ans, self.language, True) detected = self.detect_yes(self.language, self.recordTime) if detected == 'Rerun': pass else: return detected
class SpeechDetectionSphinxTests(unittest.TestCase): def setUp(self): rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') self.ch = RappPlatformAPI() def test_ogg_oxi(self): audioFile = path.join(self.pkgDir, 'test_data', 'speech_detection_samples', 'recording_oxi.ogg') response = self.ch.speechRecognitionSphinx(audioFile, 'nao_ogg', 'el',\ [u'ναι', u'οχι']) valid_words_found = [u'οχι'] self.assertEqual(response['error'], u'') self.assertEqual(response['words'], valid_words_found) def test_ogg_no(self): audioFile = path.join(self.pkgDir, 'test_data', 'speech_detection_samples', 'recording_no.ogg') response = self.ch.speechRecognitionSphinx(audioFile, 'nao_ogg', 'en',\ [u'yes', u'no']) valid_words_found = [u'no'] self.assertEqual(response['error'], u'') self.assertEqual(response['words'], valid_words_found) def test_wav_1_ch_yes_no(self): audioFile = path.join(self.pkgDir, 'test_data', 'yes-no.wav') response = self.ch.speechRecognitionSphinx(audioFile, 'nao_wav_1_ch', 'en',\ [u'yes', u'no']) valid_words_found = [u'yes', u'no'] self.assertEqual(response['error'], u'') self.assertEqual(response['words'], valid_words_found) def test_wav_1_ch_nai_oxi(self): audioFile = path.join(self.pkgDir, 'test_data', 'nai-oxi-test.wav') response = self.ch.speechRecognitionSphinx(audioFile, 'nao_wav_1_ch', 'el',\ [u'ναι', u'οχι', u'ισως']) valid_words_found = [u'ναι', u'οχι', u'ισως'] self.assertEqual(response['error'], u'') self.assertEqual(response['words'], valid_words_found) def test_headset_nai_oxi(self): audioFile = path.join(self.pkgDir, 'test_data', 'microphone_nai.wav') response = self.ch.speechRecognitionSphinx(audioFile, 'headset', 'el',\ [u'ναι', u'οχι']) valid_words_found = [u'ναι'] self.assertEqual(response['error'], u'') self.assertEqual(response['words'], valid_words_found) def test_speech_erroneous(self): audioFile = path.join(self.pkgDir, 'test_data', 'microphone_nai.wav') response = self.ch.speechRecognitionSphinx('', 'headset', 'el', [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx([], 'headset', 'el', [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(3, 'headset', 'el', [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, '', 'el', [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, [], 'el', [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, 3, 'el', [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, 'headset', '', [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, 'headset', [], [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, 'headset', 3, [u'ναι', u'οχι']) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, 'headset', 'el', 3) self.assertNotEqual(response['error'], u'') response = self.ch.speechRecognitionSphinx(audioFile, 'headset', 'el', '') self.assertNotEqual(response['error'], u'')
if head_yaw < -limit: joints = ["RShoulderRoll", "RShoulderPitch", "RElbowRoll"] head_yaw = -head_yaw # Else the Left is selected else: joints = ["LShoulderRoll", "LShoulderPitch", "LElbowRoll"] # Give the command to the hand rh.humanoid_motion.setJointAngles( joints, [head_yaw, head_pitch, -0.0349], 0.2) # Create an object in order to call the desired functions rh = RappRobot() ch = RappPlatformAPI() home = expanduser("~") + '/Pictures/' rh.audio.speak('I will scan for objects') objects = {} qr_messages = [] global_counter = 0 # Loop to perform search in 9 directions for i in range(0, 3): for j in range(0, 3): global_counter += 1
class CognitiveTestChooserTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() # Wait till the service is up using an erroneous call for fast return counter = 0 timeout = 120 while counter < timeout: counter = counter + 1 res = self.ch.cognitiveExerciseSelect(0) if res['error'] != u'Connection Error': break time.sleep(1) print 'Waiting for service... ' + str(timeout - counter) if counter == timeout: self.assertEqual('Connection error', True) def test_selectArithmeticTest(self): res = self.ch.cognitiveExerciseSelect('ArithmeticCts', 'TransactionChangeCts', '1', '1') self.assertEqual(res['error'], u"") self.assertNotEqual(res['test_instance'], u"") self.assertNotEqual(res['test_type'], u"") self.assertNotEqual(res['test_subtype'], u"") self.assertNotEqual(res['questions'], u"") self.assertNotEqual(res['possib_ans'], u"") self.assertNotEqual(res['correct_ans'], u"") def test_selectArithmeticTest_default_params(self): res = self.ch.cognitiveExerciseSelect('ArithmeticCts') self.assertEqual(res['error'], u"") self.assertNotEqual(res['test_instance'], u"") self.assertNotEqual(res['test_type'], u"") self.assertNotEqual(res['test_subtype'], u"") self.assertNotEqual(res['questions'], u"") self.assertNotEqual(res['possib_ans'], u"") self.assertNotEqual(res['correct_ans'], u"") def test_selectAwarenessTest(self): res = self.ch.cognitiveExerciseSelect('AwarenessCts') self.assertEqual(res['error'], u"") self.assertNotEqual(res['test_instance'], u"") self.assertNotEqual(res['test_type'], u"") self.assertNotEqual(res['test_subtype'], u"") self.assertNotEqual(res['questions'], u"") self.assertNotEqual(res['possib_ans'], u"") self.assertNotEqual(res['correct_ans'], u"") def test_selectReasoningTest(self): res = self.ch.cognitiveExerciseSelect('ReasoningCts') self.assertEqual(res['error'], u"") self.assertNotEqual(res['test_instance'], u"") self.assertNotEqual(res['test_type'], u"") self.assertNotEqual(res['test_subtype'], u"") self.assertNotEqual(res['questions'], u"") self.assertNotEqual(res['possib_ans'], u"") self.assertNotEqual(res['correct_ans'], u"") def test_selectNotExistentTest(self): res = self.ch.cognitiveExerciseSelect('KoukouroukouCts') self.assertNotEqual(res['error'], u"") def test_selectWrongType_TestType(self): res = self.ch.cognitiveExerciseSelect(3) self.assertNotEqual(res['error'], u"") def test_selectWrongType_TestSubtype(self): res = self.ch.cognitiveExerciseSelect('ArithmeticCts', 3) self.assertNotEqual(res['error'], u"") def test_selectWrongType_TestDiff(self): res = self.ch.cognitiveExerciseSelect('ArithmeticCts', '', 4) self.assertNotEqual(res['error'], u"") def test_selectWrongType_TestIndex(self): res = self.ch.cognitiveExerciseSelect('ArithmeticCts', '', '1', 3) self.assertNotEqual(res['error'], u"")
def setUp(self): rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') self.ch = RappPlatformAPI()
def RappWeatherCurrent(self, city, weatherReporter, metric): ch = RappPlatformAPI() #########address = addr response = ch.weatherReportCurrent(city, weatherReporter, metric) return response
class PathPlanningTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() rospack = rospkg.RosPack() self.pkgDir = rospack.get_path('rapp_testing_tools') def test_plan_2d(self): testDatapath = path.join(self.pkgDir, 'test_data', 'path_planning') poseStart = { 'header':{ 'seq': 0, 'stamp':{'sec': 0, 'nsecs': 0}, 'frame_id': '' }, 'pose': { 'position': {'x': 1, 'y': 1, 'z': 0}, 'orientation': {'x': 0, 'y': 0, 'z': 0, 'w': 0} } } poseGoal = { 'header':{ 'seq': 0, 'stamp':{'sec': 0, 'nsecs': 0}, 'frame_id': '' }, 'pose': { 'position': {'x': 5.3, 'y': 4, 'z': 0}, 'orientation': {'x': 0, 'y': 0, 'z': 20, 'w': 0} } } yamlFile = path.join(testDatapath, '523_m_obstacle_2.yaml') pngFile = path.join(testDatapath, '523_m_obstacle_2.png') map_name='523_m_obstacle_2' resp = self.ch.pathPlanningUploadMap(map_name, pngFile, yamlFile) self.assertEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(map_name, 'NAO', poseStart,\ poseGoal) self.assertEqual(resp['error'], u'') self.assertEqual(resp['plan_found'], 0) def test_plan_2d_erroneous(self): testDatapath = path.join(self.pkgDir, 'test_data', 'path_planning') poseStart = { 'pose': { 'position': {'x': 1, 'y': 1, 'z': 0}, 'orientation': {'x': 0, 'y': 0, 'z': 0, 'w': 0} } } poseGoal = { 'pose': { 'position': {'x': 5.3, 'y': 4, 'z': 0}, 'orientation': {'x': 0, 'y': 0, 'z': 20, 'w': 0} } } yamlFile = path.join(testDatapath, '523_m_obstacle_2.yaml') pngFile = path.join(testDatapath, '523_m_obstacle_2.png') map_name='523_m_obstacle_2' resp = self.ch.pathPlanningUploadMap(map_name, pngFile, yamlFile) self.assertEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D('', 'NAO', poseStart, poseGoal) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(4, 'NAO', poseStart, poseGoal) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(map_name, 3, poseStart, poseGoal) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(map_name, [], poseStart, poseGoal) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(map_name, 'NAO', 0, poseGoal) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(map_name, 'NAO', poseStart, 0) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(map_name, 'NAO', [], poseGoal) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningPlan2D(map_name, 'NAO', poseStart, []) self.assertNotEqual(resp['error'], u'') def test_upload_map(self): testDatapath = path.join(self.pkgDir, 'test_data', 'path_planning') yamlFile = path.join(testDatapath, '523_m_obstacle_2.yaml') pngFile = path.join(testDatapath, '523_m_obstacle_2.png') map_name='523_m_obstacle_2' resp = self.ch.pathPlanningUploadMap(map_name, pngFile, yamlFile) self.assertEqual(resp['error'], u'') def test_upload_map_erroneous(self): testDatapath = path.join(self.pkgDir, 'test_data', 'path_planning') yamlFile = path.join(testDatapath, '523_m_obstacle_2.yaml') pngFile = path.join(testDatapath, '523_m_obstacle_2.png') map_name='523_m_obstacle_2' resp = self.ch.pathPlanningUploadMap(map_name, '', yamlFile) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningUploadMap(map_name, pngFile, '') self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningUploadMap(map_name, 3, yamlFile) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningUploadMap(map_name, [], yamlFile) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningUploadMap(map_name, pngFile, 3) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningUploadMap(map_name, pngFile, []) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningUploadMap(3, pngFile, yamlFile) self.assertNotEqual(resp['error'], u'') resp = self.ch.pathPlanningUploadMap([], pngFile, yamlFile) self.assertNotEqual(resp['error'], u'')
def setUp(self): self.ch = RappPlatformAPI()
class CognitiveTestRecordTests(unittest.TestCase): def setUp(self): self.ch = RappPlatformAPI() def test_recordReasoning(self): response = self.ch.cognitiveExerciseSelect('ReasoningCts') self.assertEqual(response['error'], u'') self.assertNotEqual(response['test_instance'], u'') instance = response['test_instance'] response = self.ch.cognitiveRecordPerformance(instance, 50) self.assertEqual( 'CognitiveTestPerformed' in response['performance_entry'], True) def test_recordAwareness(self): response = self.ch.cognitiveExerciseSelect('AwarenessCts') self.assertEqual(response['error'], u'') self.assertNotEqual(response['test_instance'], u'') instance = response['test_instance'] response = self.ch.cognitiveRecordPerformance(instance, 50) self.assertEqual( 'CognitiveTestPerformed' in response['performance_entry'], True) def test_recordArithmetic(self): response = self.ch.cognitiveExerciseSelect('ArithmeticCts') self.assertEqual(response['error'], u'') self.assertNotEqual(response['test_instance'], u'') instance = response['test_instance'] response = self.ch.cognitiveRecordPerformance(instance, 50) self.assertEqual( 'CognitiveTestPerformed' in response['performance_entry'], True) def test_recordWrongType(self): response = self.ch.cognitiveExerciseSelect('ArithmeticCts') self.assertEqual(response['error'], u'') self.assertNotEqual(response['test_instance'], u'') instance = response['test_instance'] response = self.ch.cognitiveRecordPerformance(3, 50) self.assertNotEqual(response['error'], u'') def test_recordWrongScoreType(self): response = self.ch.cognitiveExerciseSelect('ArithmeticCts') self.assertEqual(response['error'], u'') self.assertNotEqual(response['test_instance'], u'') instance = response['test_instance'] response = self.ch.cognitiveRecordPerformance(instance, '200') self.assertNotEqual(response['error'], u'') def test_recordWrongScoreValues(self): response = self.ch.cognitiveExerciseSelect('ArithmeticCts') self.assertEqual(response['error'], u'') self.assertNotEqual(response['test_instance'], u'') instance = response['test_instance'] response = self.ch.cognitiveRecordPerformance(instance, 200) self.assertNotEqual(response['error'], u'') response = self.ch.cognitiveRecordPerformance(instance, -200) self.assertNotEqual(response['error'], u'')
class NaoInterface: def __init__(self): self.rh = RappRobot() self.ch = RappPlatformAPI() rospy.Timer(rospy.Duration(0.1), self.sonarsCallback) rospy.Timer(rospy.Duration(5), self.qrDetectionCallback) #self.pub = rospy.Publisher('/inner/sonar_measurements', LaserScan, queue_size=1) self.pub1 = rospy.Publisher('/inner/qr_detection', RfidSensorMeasurementMsg, queue_size=1) self.s = rospy.Service('set_object', SetObject, self.setNewObjectCallback) self.s1 = rospy.Service('get_objects', GetObjects, self.getObjectsCallback) self.objects = {} self.static_objects = [] def sonarsCallback(self, event): sonars = self.rh.sensors.getSonarsMeasurements()['sonars'] laser_msg = LaserScan() laser_msg.ranges.append(sonars['front_right']) laser_msg.ranges.append(sonars['front_left']) laser_msg.range_max = 1.00 laser_msg.angle_increment = 0.785398185253 laser_msg.angle_min = -0.392699092627 self.pub.publish(laser_msg) def qrDetectionCallback(self, event): print "QrDetection" rospack = rospkg.RosPack() img_path = rospack.get_path('nao_localization') + "/cfg/nao_capture.jpg" self.rh.vision.capturePhoto("/home/nao/test.jpg", "front", "640x480") print img_path self.rh.utilities.moveFileToPC("/home/nao/test.jpg", img_path) #svc = QrDetection(imageFilepath="/home/chrisa/test.jpg") response = self.ch.qrDetection(img_path) print response print response['qr_messages'] if "Localization" in response['qr_messages']: qr_msg = RfidSensorMeasurementMsg() qr_msg.rfid_tags_ids.append(response['qr_messages']) self.pub1.publish(qr_msg) head_yaw = self.rh.humanoid_motion.getJointAngles(["HeadYaw"])['angles'][0] print head_yaw def setNewObjectCallback(self, req): print "setNewObjectCallback" print req self.objects[req.object.message] = req.object res = SetObjectResponse() res.success = True return res def getObjectsCallback(self, req): res = GetObjectsResponse() if req.localization_type == "dynamic": for i in range(0, len(self.objects)): obj = ObjectMsg() obj.x = self.objects.values()[i].x obj.y = self.objects.values()[i].y obj.message = self.objects.values()[i].message obj.type = self.objects.values()[i].type if req.object_type == self.objects.values()[i].type or req.object_type == "all" or req.object_type == "": if obj.message in res.objects: continue res.objects.append(obj) elif req.localization_type == "static": for i in range(0, len(self.static_objects)): obj = ObjectMsg() obj.x = static_objects[i].x obj.y = static_objects[i].y obj.message = static_objects[i].message obj.type = static_objects[i].type res.objects.append(obj) elif req.localization_type == "all": for i in range(0, len(self.objects)): obj = ObjectMsg() obj.x = self.objects.values()[i].x obj.y = self.objects.values()[i].y obj.message = self.objects.values()[i].message obj.type = self.objects.values()[i].type if req.object_type == self.objects.values()[i].type or req.object_type == "all" or req.object_type == "": if obj.message in res.objects: continue res.objects.append(obj) for i in range(0, len(self.static_objects)): obj = ObjectMsg() obj.x = static_objects[i].x obj.y = static_objects[i].y obj.message = static_objects[i].message obj.type = static_objects[i].type res.objects.append(obj) else: print "No such type" res.success = True print res.objects return res
class WeatherReport(object): ## Default constructor def __init__(self): """ Default Constructor.""" self.language = 'el' self.askValidation = True self.waitOnAnswer = 5 self.rh = RappRobot() self.ch = RappPlatformAPI() self._loc = self.ch.geolocation(Net.ipaddr_connected()) print '[*] Current Location: {0}'.format(self._loc) def run(self): try: self.rh.motion.enableMotors() self.rh.humanoid_motion.goToPosture('Sit', 0.5) mode = self._mode_selection() if mode == 'current': self._mode_current() elif mode == 'forecast': self._mode_forecast() self.say(u'Τερματισμός εφαρμογής') self.rh.humanoid_motion.goToPosture('Sit', 0.5) self.rh.motion.disableMotors() except Exception as e: print e self.error_termination() def _mode_selection(self): msg = u'Μπορείς να επιλέξεις μεταξύ' msg += u' της σημερινής και της εβδομαδιαίας πρόβλεψης του καιρού. ' msg += u'Πείτε ένα για επιλογή της σημερινής πρόβλεψης' msg += u', ή δύο για την εβδομαδιαία.' self.say(msg) detected = 'Rerun' while detected == 'Rerun': voc = [u'σημερινή', u'εβδομαδιαία', u'ένα', u'δύο'] resp = self.rh.audio.speechDetection(voc, self.waitOnAnswer, self.language) try: print 'Detect-Words: word: {0}, probability: {1}, error: {2}'.format( resp['word'], resp['probability'], resp['error']) except Exception as e: print e if resp['error'] or resp['probability'] < 0.4: # Threshold prob self.rh.audio.speak(u'Δεν άκουσα. Μιλήστε πιο δυνατά παρακαλώ', self.language, True) detected = 'Rerun' continue elif self.askValidation: usrAns = self.ask_validation(resp['word'].decode('utf8')) if not usrAns: detected = 'Rerun' self.say(u'Επανέλαβε την απάντηση παρακαλώ.') continue break if resp['word'].decode('utf8').lower() in [u'σημερινη', u'σημερινή', u'ένα', u'ενα']: return 'current' elif resp['word'].decode('utf8').lower() in [u'εβδομαδιαία', u'εβδομαδιαια', u'δύο', u'δυο']: return 'forecast' def _mode_current(self): report = self.ch.weatherReportCurrent(self._loc['city'], metric=1) if len(report['error']) != 0: self.error_termination() print "[*] Current Weather Report: {0}".format(report) date = self._timestamp_to_date(int(report['date'])) self.say('Η πρόβλεψη του καιρού για τις {0} {1}, ώρα {2}, είναι:'.format( date['day'], date['month'].encode('utf8'), date['hour'])) self.say(u'Θερμοκρασία: {0} βαθμούς κελσίου'.format( report['temperature'].encode('utf8').replace(u'.', u' κόμμα '))) if report['wind_speed'] != u'': self.say(u'Ταχύτητα ανέμου: {0} {1}'.format( report['wind_speed'].encode('utf8').replace( u'.', u' κόμμα '), u'χιλιόμετρα το δευτερόλεπτο')) if report['visibility'] != u'': self.say(u'Ορατότητα: Μέχρι τα {0} {1}'.format( report['visibility'].encode('utf8').replace(u'.', u' κόμμα '), u'χιλιόμετρα')) if report['humidity'] != u'': self.say(u'Επίπεδα υγρασίας : {0} {1}'.format( int(float(report['humidity']) * 100), u'τοις εκατό')) if report['pressure'] != u'': self.say(u'Ατμοσφερική πίεση: {0} {1}'.format( report['pressure'].encode('utf8').replace(u'.', u' κόμμα '), u'πασκάλ')) def _mode_forecast(self): resp = self.ch.weatherReportForecast(self._loc['city'], metric=1) if len(resp['error']) != 0: self.error_termination() reports = sorted(resp['forecast'], key=lambda k: k['date']) for idx, val in enumerate(reports): print "[*] Forecast Report: {0}".format(val) date = self._timestamp_to_date(int(val['date'])) self.say('Η πρόβλεψη του καιρού για τις {0} {1}, είναι:'.format( date['day'], date['month'].encode('utf8'))) self.say(u'Υψηλότερη θερμοκρασία: {0} βαθμούς κελσίου'.format( val['high_temp'].encode('utf8').replace(u'.', u' κόμμα '))) self.say(u'Χαμηλότερη θερμοκρασία: {0} βαθμούς κελσίου'.format( val['low_temp'].encode('utf8').replace(u'.', u' κόμμα '))) def _timestamp_to_date(self, ts): d = datetime.fromtimestamp(ts).strftime('%d, %B, %H:%M:%S').split(',') return { 'day': d[0].strip(), 'month': dateMap[d[1].strip()], 'hour': d[2].split(':')[0] } def say(self, msg, animated=True): self.rh.audio.speak(msg, self.language, animated=animated) def error_termination(self): """ Inform on termination with error.""" self.rh.audio.speak(u'Κατι πήγε λαθος στο σύστημα. Άμεσος τερματισμός!', self.language, True) sys.exit(1) def detect_yes(self, waitT=5.0): """ Method to recognize yes/no (ναι/οχι) words.""" if self.language == 'el': possibAns = [u'ναι', u'οχι'] correctAns = u'ναι' elif self.language == 'en': possibAns = ['yes', 'no'] correctAns = 'yes' else: pass resp = self.rh.audio.speechDetection(possibAns, waitT, self.language) try: print 'Detect-Yes: word: {0}, probability: {1}, error: {2}'.format( resp['word'], resp['probability'], resp['error']) except Exception as e: print e if resp['error'] or resp['probability'] < 0.4: # Threshold prob self.rh.audio.speak(u'Δεν άκουσα. Μιλήστε πιο δυνατά παρακαλώ', self.language, True) return 'Rerun' elif resp['word'] == correctAns.encode('utf8'): return True else: return False def ask_validation(self, ans): while True: self.rh.audio.speak(u'Είπατε... %s ?' % ans, self.language, True) detected = self.detect_yes() if detected == 'Rerun': pass else: return detected
def RappWeatherForecast(self, city, weather_reporter, metric): ch = RappPlatformAPI() ######################address = addr response = ch.weatherReportForecast(city, weather_reporter, metric) #Rapp service return response