def on_create(self): """ Creates a notification for the user that owns the shared file (does not create a new notification if you are the user) """ sf = self.sharedfile() if self.user_id != sf.user_id: notification.Notification.new_comment(self) #creates a conversation for a user if one doesn't exist. existing_conversation = conversation.Conversation.get( 'user_id = %s and sharedfile_id = %s', self.user_id, self.sharedfile_id) if not existing_conversation: new_conversation = conversation.Conversation( user_id=self.user_id, sharedfile_id=self.sharedfile_id) new_conversation.save() #creates a conversation for sharedfile.user_id if one doesn't exist existing_conversation = conversation.Conversation.get( 'user_id = %s and sharedfile_id=%s', sf.user_id, self.sharedfile_id) if not existing_conversation: new_conversation = conversation.Conversation( user_id=sf.user_id, sharedfile_id=self.sharedfile_id) new_conversation.save() # update the SF activity_at sf.activity_at = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") sf.save() # find any mentions and create notifciations mentions = self.extract_mentions() for u in mentions: notification.Notification.new_mention(u, self)
def __init__(self): super(Bob, self).__init__() question = conversation.Question(Bob._questionResponse) yell = conversation.Yell(Bob._yellResponse) silence = conversation.AwkwardSilence(Bob._silenceResponse) self._conversation = conversation.Conversation(Bob._defaultResponse, question, yell, silence)
def __init__(self, user=None, mode="human", news=None, speech_recog=False): with open("sentences/question_repeat.txt") as f: question_repeat = f.readlines() with open("sentences/continue_phrases.txt") as f: continue_phrases = f.readlines() self.Q_REPEAT_PHRASES = [x.rstrip("\n") for x in question_repeat] self.CONTINUE_PHRASES = [x.rstrip("\n") for x in continue_phrases] if not user: self.user = userprofile.UserProfile() else: self.user = user self.mode = mode self.conv = conversation.Conversation(self, news=news) self.opinion_engine = opinionengine.OpinionEngine() self.speech_recog = speech_recog # if platform.system() == 'Darwin': # OS X # self.speech_recog = False # self.say = self.osx_say # else: # Assume linux/naoqi import naoqiutils self.say = naoqiutils.speak self.newsprinter = prettynews.PrettyNews(self.conv.searcher, self.mode, self) # Commands is a dict of named conversation action scripts self.commands = { "help": self.print_commands, "quit": self.quit, "present_news": self.newsprinter.show_news, "present_news_preferences": self.newsprinter.show_news_preferences, "failed_search": self.newsprinter.search_help, "speak": self.speak, "ir_answer": self.conv.ir_parse, "read_article": self.conv.read, "update_preference": self.user.update_preferences, "get_preference": self.conv.get_preference, "present_opinion_article": self.opinion_engine.present_opinion_article, "present_opinion_subject": self.opinion_engine.present_opinion_subject, "read_text": self.conv.read_text, } debug_commands = { "topics": self.get_topics, "switch": self.switch, "quit": self.quit, } if mode == "debug": self.commands = dict(self.commands.items() + debug_commands.items()) self.posparser = posparse.POSParse()
def _retrieveConversationFor(cls, userid): '''To retrieve the conversation for a given user''' conversation = None try: conversation = cls._conversations[userid] except KeyError: conversation = conversation_module.Conversation(userid) cls._conversations[userid] = conversation return conversation
def start(self): conv = conversation.Conversation(self) if self.mode == 'human' or self.mode == 'human_speech': self.speak(conv.start_conversation()) while True: q = self.listen() if (("stop" in q or "quit" in q or "done" in q) and "conv" in q) or q == "stop" or q == "quit": break if (("stop" in q or "sleep" in q or "break") and ("another" in q or "a bit" in q or "now" in q or "a while" in q or "a second" in q or "me" in q or "i want" in q or "talking" in q)) or ("shut up" in q): time.sleep(30) self.speak("My break is over") continue if q is None: self.speak( "I assume you just want another article, don't you? Here is something." ) # currently if no question is found after 3 tries, random news # is requested. q = "What has happened in the last three days?" if self.mode == 'debug': self.process_command(q) elif self.mode.startswith('human'): # Differentiate between IR queries and opinion related stuff # Something like: read me the first article/article by title/article approxiatmely # by title? # ^ This should go into (pos)parsing! cus that class is concerned with unnderstanding # sentences. It could/should go into the process_query() method cmd, args = self.posparser.process_query(q) while cmd is not None: cmd, args = self.process_command_args(cmd, *args) if cmd is None: self.speak(choice(self.CONTINUE_PHRASES)) conv.end_conversation()
for info in audio_devices(): print(info) sys.exit() if args.google_tts: tts = "google" elif args.local_tts: tts = "local" else: tts = None # speech if not os.path.exists(os.path.join(os.getcwd(), args.audio_dir)): os.mkdir(os.path.join(os.getcwd(), args.audio_dir)) set_audio_dirname(args.audio_dir) if args.aggressiveness: vad_aggressiveness(args.aggressiveness) #audio_connect(samplerate=args.samplerate,device=args.device,activate=args.rec_voice, channels=args.channels) conversation = conversation.Conversation(filename=args.CONV, verbose=args.verbose, tts=tts, rec_voice=args.rec_voice, channels=args.channels) conversation.execute() print("Summary values:") for val, k in conversation.slots.items(): print(val, k)
def main(): try: stt = streaming.StreamingSTT( # replace with speech to text credentials username '9d28bb42-fd0f-4126-ac66-2d0882fbe7f8', # replace with speech to text credentials password 'Gixj8klOaqK4') except: fatalFailure() try: tts = textToSpeech.TextToSpeech( # replace with text to speech credentials username '6fa627fb-384e-4586-9a72-185b70c1f09a', # replace with text to speech credentials password 'zQYWSqHEA7dm') except: fatalFailure() try: convo = conversation.Conversation( # replace with conversation credentials username 'bdce62cf-d7f7-4cbc-8b0b-dee6950d1c01', # replace with conversation credentials password 'K5Cmn1aJ3He8', # replace with workspace ID. '0c3cdb7b-3258-457e-a3b7-1b1236fea9c4') except: fatalFailure() # replace with robot name name = 'Bonnie' servo_obj = servo.Servo() servoP = servoProcess.ServoProcess(servo_obj) led_obj = led.Led() ledP = ledProcess.LedProcess(led_obj) music_obj = music.Music("/home/pi/tj-python/resources/music.wav") musicP = musicProcess.MusicProcess(music_obj) time.sleep(.5) ledP.red() time.sleep(.5) ledP.green() time.sleep(.5) ledP.blue() time.sleep(.5) ledP.rainbowCycle(.0001, 99999999999999) # tts.speak("Hello, just a moment while I boot up") servoP.wave(3) """l = led.Led() le = ledProcess.LedProcess(l) print('sleeping') time.sleep(3) print('done sleeping, Lets Strobe') le.strobe() #le.customColor(255,0,0) print('sleeping') time.sleep(3) print('kill in 2') time.sleep(2) le.customColor(255,0,0) #le.stop() print('dead') """ tts.speak('Hello my name is ' + name + ' I am the CBU admissions bot') while True: ledP.blue() try: phrase = stt.get_phrase() except: ledP.red() ledP.orange() if (name in phrase) or ('bunny' in phrase) or ('body' in phrase) or ( 'Bani' in phrase): response = convo.sendMessage(phrase) ledP.green() #response = response.upper() if '~' in response: print('Command Found') if '~RED' in response: ledP.red() response = response.replace('~RED', '', 1) if '~ORANGE' in response: ledP.orange() response = response.replace('~ORANGE', '', 1) if '~YELLOW' in response: ledP.yellow() response = response.replace('~YELLOW', '', 1) if '~GREEN' in response: ledP.green() response = response.replace('~GREEN', '', 1) if '~BLUE' in response: print('Its Blue') ledP.blue() response = response.replace('~BLUE', '', 1) if '~PURPLE' in response: ledP.purple() response = response.replace('~PURPLE', '', 1) if '~PINK' in response: ledP.pink() response = response.replace('~PINK', '', 1) if '~WHITE' in response: ledP.white() response = response.replace('~WHITE', '', 1) if '~RAINBOW' in response: ledP.rainbow() response = response.replace('~RAINBOW', '', 1) if '~RAINBOWCYCLE' in response: ledP.rainbowCycle() response = response.replace('~RAINBOWCYCLE', '', 1) if '~MUSICPLAY' in response: musicP.play() response = response.replace('~MUSICPLAY', '', 1) if '~MUSICSTOP' in response: musicP.stop() response = response.replace('~MUSICSTOP', '', 1) if '~LEDOFF' in response: ledP.off() response = response.replace('~LEDOFF', '', 1) if '~ARMSTOP' in response: servoP.stop() response = response.replace('~ARMSTOP', '', 1) if '~ARMUP' in response: servoP.armUp() response = response.replace('~ARMUP', '', 1) if '~ARMDOWN' in response: servoP.armDown() response = response.replace('~ARMDOWN', '', 1) if '~DANCE' in response: servoP.wave(10) ledP.rainbowCycle(1, 50) response = response.replace('~DANCE', '', 1) if '~ARMANGLE' in response: response = response.replace('~ARMANGLE', '', 1) param = int(response.split("~", 1)[0]) response = response.split("~", 1)[1] servoP.angle(param) if '~ARMWAVECOUNT' in response: response = response.replace('~ARMWAVECOUNTARMANGLE', '', 1) param = int(response.split("~", 1)[0]) response = response.split("~", 1)[1] servoP.wave(param) if '~ARMWAVE' in response: servoP.wave(2) response = response.replace('~ARMWAVE', '', 1) if response == '': response = 'awkward silence' ledP.pink() tts.speak(response)
BoxZoomTool(), ResetTool(), PanTool(), ResizeTool(), WheelZoomTool() ] # output to static HTML file output_file("lengths.html", title="Chat lengths") p = figure(width=800, height=500, x_axis_type="datetime", tools=TOOLS) colors = brewer["Spectral"][len(messages)] for i, k in enumerate(messages): days = conversation.Conversation(messages[k]).days() dates = sorted(days.keys()) lengths = np.array([len(days[key]) for key in dates]) x_dates = np.array(sorted(days.keys()), dtype=np.datetime64) source = ColumnDataSource(data=dict( x=x_dates, y=lengths, dates=dates, # label=[k]*len(dates), )) p.line('x', 'y', source=source, color=colors[i], line_width=2) p.circle('x', 'y', source=source, color=colors[i], legend=k, size=8) # NEW: customize by setting attributes p.title = "Per day chat lengths" p.legend.orientation = "top_left"
import conversation, random, re def stripPunctuation(message): if message.endswith(('!', '?')): message = message[0:-1] return message else: return message conv = conversation.Conversation() def dialogue(): global conv # take user's message from input, make lowercase and strip punctuation userMessage = input() userMessage = userMessage.lower() userMessage = stripPunctuation(userMessage) # create a new conversation unless the message is "start over" # create objects to check for standard messages and patterns if userMessage == "start over": conv.startOver() botResponse = conv.checkMessage(userMessage) # respond according to results if botResponse: print("BOT: {}".format(botResponse)) else:
print(info) sys.exit() if args.google_tts: tts = "google" elif args.local_tts: tts = "local" else: tts = None # speech if not os.path.exists(os.path.join(os.getcwd(), args.audio_dir)): os.mkdir(os.path.join(os.getcwd(), args.audio_dir)) set_audio_dirname(args.audio_dir) if args.aggressiveness: vad_aggressiveness(args.aggressiveness) conv = conversation.Conversation(filename=args.CONV, verbose=args.verbose, tts=tts, samplerate=args.samplerate, device=args.device, rec_voice=args.rec_voice, host=args.host, port=args.port) t = threading.Thread(target=conv.execute) conv.set_thread(t) web.run_app(app, host=args.host, port=args.port)
def toconv(infile: BinaryIO) -> conversation.Conversation: """Take a file-like input object containing an XML chat log, and parse to produce a Conversation object""" logging.debug('Parsing ' + infile.name) try: dom = xml.dom.minidom.parse(infile) except xml.parsers.expat.ExpatError: # Strip ASCII control characters (sometimes found in input pasted from Microsoft apps?) logging.debug('XML processing failed with ExpatError; attempting to sanitize input and retry') infile.seek(0) instring = re.sub(r'[\x00-\x08\x0B-\x1F]', '?', infile.read().decode('utf-8-sig', errors='replace')) dom = xml.dom.minidom.parseString(instring) if dom.firstChild.nodeName != 'chat': # Do some basic sanity-checking on input logging.critical(os.path.basename(infile.name) + ' does not appear to contain <chat> element!') raise ValueError('Malformed or invalid input file') conv = conversation.Conversation() # instantiate Conversation object conv.imclient = 'Adium' # since we are only parsing Adium logs with this module conv.origfilename = os.path.basename(infile.name) # Store name of input file and store for future reference # If possible, determine the IM service based on the grandparent folder name if hierarchy is either: # /path/to/Adium Logs/AIM.myaccountname/theiraccountname/theiraccountname (date).chatlog # /path/to/Adium/Logs*/AIM.myaccountname/theiraccountname/theiraccountname (date).chatlog filepathlist = os.path.realpath(infile.name).split(os.path.sep) if os.path.splitext(conv.origfilename)[-1] == '.chatlog' \ and ((filepathlist[-4] == 'Adium Logs') or (filepathlist[-4].find('Logs') == 0 and filepathlist[-5] == 'Adium')): logging.debug(f'Detected non-bundled XML .chatlog: {conv.origfilename}') conv.service = filepathlist[-3].split('.', 1)[0] conv.localaccount = filepathlist[-3].split('.', 1)[1].lower() conv.remoteaccount = filepathlist[-2].lower() if os.path.splitext(conv.origfilename)[-1] == '.xml' \ and ((filepathlist[-5] == 'Adium Logs') or (filepathlist[-5].find('Logs') == 0 and filepathlist[-6] == 'Adium')): logging.debug(f'Detected bundled .chatlog with XML file: {conv.origfilename}') conv.service = filepathlist[-4].split('.', 1)[0] conv.localaccount = filepathlist[-4].split('.', 1)[1].lower() conv.remoteaccount = filepathlist[-3].lower() # Special handling for Facebook Chat usernames, which are stored in directory structure in an odd way if '@chat.facebook.com' in conv.remoteaccount: rawfileid = conv.remoteaccount conv.remoteaccount = re.match("^-([0-9]*)@chat\.facebook\.com$", rawfileid).group(1) conv.filenameuserid = conv.origfilename.split(' (')[0] if '@chat.facebook.com' in conv.filenameuserid: rawfilenameuserid = conv.filenameuserid conv.filenameuserid = re.match("^-([0-9]*)@chat\.facebook\.com$", rawfilenameuserid).group(1) chat = dom.firstChild # root element should always be <chat> conv.service = chat.getAttribute('service').strip() # set the service (AIM, MSN, etc.) if not conv.remoteaccount: logging.debug('Could not determine local account from input path; setting from XML') conv.set_remote_account(chat.getAttribute('account').strip().lower()) # set remote account from XML logging.debug('IM service is: ' + conv.service) logging.debug('Local account is: ' + conv.localaccount) logging.debug('Remote account is: ' + conv.remoteaccount) for e in chat.childNodes: if (e.nodeName == 'event') or (e.nodeName == 'status'): # Handle <event... /> and <status... /> msg = conversation.Message('event') msg.date = dateutil.parser.parse(e.getAttribute('time')) msg.msgfrom = e.getAttribute('sender') if e.getAttribute('type') == 'windowOpened': msg.text = 'Window opened by ' + e.getAttribute('sender') if e.getAttribute('type') == 'windowClosed': msg.text = 'Window closed by ' + e.getAttribute('sender') if e.getAttribute('type') in ['offline', 'online', 'idle', 'available']: msg.text = 'User ' + e.getAttribute('sender') + ' is now ' + e.getAttribute('type') + '.' conv.add_message(msg) elif e.nodeName == 'message': # Handle <message> msg = conversation.Message('message') msg.date = dateutil.parser.parse(e.getAttribute('time')) msg.msgfrom = e.getAttribute('sender') conv.add_participant(msg.msgfrom.lower()) if e.hasAttribute('alias'): # Facebook logs have an 'alias' attribute containing real name logging.debug(f'Alias {e.getAttribute("alias")} found for user id {msg.msgfrom}') conv.add_realname_to_userid(msg.msgfrom, e.getAttribute('alias')) ## Start debugging TODO remove me logging.debug(f'Added participant (msg.msgfrom) with user id: {msg.msgfrom.lower()}') logging.debug(f'Should {msg.msgfrom} be considered local? {(msg.msgfrom.lower() == conv.localaccount)}') logging.debug(f'Should {msg.msgfrom} be considered remote? {(msg.msgfrom.lower() == conv.remoteaccount)}') logging.debug(f'Participant user id list contains {conv.listparticipantuserids()}') for pid in conv.listparticipantuserids(): logging.debug(f'\n User ID: {conv.get_participant(pid).userid}' f'\n Position: {conv.get_participant(pid).position}' f'\n Is Local? {conv.userid_islocal(pid)}' f'\n Is Remote? {conv.userid_isremote(pid)}' f'\n Has realname? {conv.get_participant(pid).realname}') ## End Debugging msg.text = get_inner_text(e) logging.debug('Message text is: ' + msg.text) if e.firstChild.nodeName == 'div': try: msg.html = e.firstChild.firstChild.toxml() # strip outermost <div> except AttributeError: # usually this is caused by text directly inside the <div> without a <span> msg.html = e.firstChild.toxml() else: msg.html = e.firstChild.toxml() logging.debug('Message HTML is: ' + msg.html) conv.add_message(msg) logging.debug('End of message processing\n') # TODO remove me # Get date from filename, if present; otherwise use timestamp from first message if (conv.origfilename.find('(') != -1) and (conv.origfilename.find(')') != -1): filenamedatestr = adium_html.getlinecontent(conv.origfilename, '(', ')') try: filenamedate = dateutil.parser.parse(filenamedatestr.replace('.', ':')) conv.startdate = filenamedate except dateutil.parser.ParserError: logging.debug('Dateutil parser unable to parse: ' + filenamedatestr) else: conv.startdate = conv.getoldestmessage().date # If there are less than two Participants in the Conversation, pad it with 'UNKNOWN' to prevent errors later if len(conv.participants) < 2: conv.add_participant('UNKNOWN') conv.add_realname_to_userid('UNKNOWN', 'Unknown User') return conv
import conversation def postOnScreen(msg): print(msg) myConversation = conversation.Conversation(replyTo=postOnScreen) myConversation.talk("Do you have John Doe's bio?")
sys.exit() elif args.list_voices_local_tts: list_voices(engine='local') sys.exit() elif args.list_language_google_tts: list_voices(engine='google') sys.exit() if not kargs.CONV: print("No conversation file provided") p.print_usage() sys.exit() CONFIG=vars(args) CONFIG['main_path']=os.path.dirname(kargs.CONV) # Setting TTS if args.google_tts: CONFIG['tts']="google" elif args.local_tts: CONFIG['tts']="local" else: CONFIG['tts']=None # Main conversation conversation = conversation.Conversation( filename=kargs.CONV, **CONFIG) conversation.execute()
def main(): #Attempts at handling segementation faults and pipe faults signal.signal(signal.SIGPIPE, sig_handler) signal.signal(signal.SIGSEGV, sig_handler) #Creation of the LED object and Process led_obj = led.Led() ledP = ledProcess.LedProcess(led_obj) #Creation of the error handler and it passed the LED process so it can refrence it errorHandle = errorHandler.errorHandler(ledP) config = configparser.ConfigParser() #This pulls in all of the credentials from the config files #If one of these fails to pull in a fatal error is called try: config.read('/home/pi/SeniorProjectBioloid/config.cfg') sttUser = config.get('Bioloid Credentials', 'sttUser') sttPw = config.get('Bioloid Credentials', 'sttPassword') ttsUser = config.get('Bioloid Credentials', 'ttsUser') ttsPw = config.get('Bioloid Credentials', 'ttsPassword') convoUser = config.get('Bioloid Credentials', 'convoUser') convoPw = config.get('Bioloid Credentials', 'convoPassword') convoWorkSpace = config.get('Bioloid Credentials', 'convoWorkSpace') # configuration for timeout options timeoutWarning = float( config.get('Bioloid Information', 'timeoutWarning')) timeoutShutdown = float( config.get('Bioloid Information', 'timeoutShutdown')) soundsLike = config.get('Bioloid Information', 'soundsLike') except: errorHandle.fatalError(1) homophones = soundsLike.split(",") #Start Creating the Watson servicesself. #If one of them fails then it gives an erro #the credentials can be changed in the config file try: stt = streaming.StreamingSTT(sttUser, sttPw) except: errorHandle.fatalError(2) try: tts = textToSpeech.TextToSpeech(ttsUser, ttsPw) except: errorHandle.fatalError(3) try: convo = conversation.Conversation(convoUser, convoPw, convoWorkSpace) except: errorHandle.fatalError(4) #Starts up the Visual recogniton abilites. try: vr = vis.VisualRecognition() except: errorHandle.fatalError(5) #Creates the bioloid so we cna control the motors try: bioloid = bio.Bioloid() except: errorHandle.fatalError(6) #bioloid.doLookUp() #say = vr.viewObjects() #tts.speak(say, False) #say = vr.viewFaces() #tts.speak(say, False) #bioloid.doIdle(False) #Gets the name of the robot from the Config File name = config.get('Bioloid Information', 'name') #This allows to see if the robot has been inactive lastActiveTime = time.time() activeTimeCheck = True # This boolean differentiates between inactivity for 60 or 120 seconds. #bioloid.doBow() #Kind of a hello works to know TTS is working. tts.speak('Hello my name is ' + name + ' I am a big robot!') # bioloid.doPushUp(2) while True: if all([ time.time() - lastActiveTime > timeoutWarning, activeTimeCheck == True ]): bioloid.doSit() tts.speak( "I have been inactive for 1 minute. After another minute, I will shut down" ) activeTimeCheck = False if all([ time.time() - lastActiveTime > timeoutShutdown, activeTimeCheck == False ]): bioloid.doSit() tts.speak("Shutting down now.") call("sudo shutdown -h now", shell=True) """ if(lastActiveTime - time.time() > 60): #if it is inactive for 1 min then it powers down. #Go home tts.speak("I have been inactive for 1 minute. After another minute, I will shut down") """ bioloid.doListen() try: phrase = stt.get_phrase() print(phrase) except: errorHandle.error() if (name in phrase) or (checkForName(homophones, phrase)): lastActiveTime = time.time( ) #if its name is heard then we can assume it is active activeTimeCheck = True try: response = convo.sendMessage(phrase) except: print("The Response was blank") if '~' in response: response = processCommand(response, bioloid) else: bioloid.doIdle(False) tts.speak(response)
# coding: utf-8 # In[35]: import conversation as c import time x = c.Conversation() x.hello() # In[36]: def PrintPlayer(p): print p.x print p.y print p.angle print p.hp print p.ammo print p.reloading print p.alive print p.shot print p.full print p.player_nr # In[ ]: while 1 == 1: for i in range(3): k = x.shoot()