def leave_chat(): backend = get_backend() uid = userid() chat_info = backend.get_chat_info(uid) backend.send( uid, Event.LeaveEvent(chat_info.agent_index, uid, str(time.time()))) return jsonify(success=True)
def join_chat(): """Sent by clients when they enter a room. A status message is broadcast to all people in the room.""" backend = get_backend() uid = userid() chat_info = backend.get_chat_info(uid) backend.send(uid, Event.JoinEvent(chat_info.agent_index, uid, str(time.time()))) return jsonify(message=format_message("You entered the room.", True))
def typing_event(): backend = get_backend() action = request.args.get('action') uid = userid() chat_info = backend.get_chat_info(uid) backend.send( uid, Event.TypingEvent(chat_info.agent_index, action, str(time.time()))) return jsonify(success=True)
def make_offer(self, userid, amt): try: with self.conn: cursor = self.conn.cursor() u = self._get_user_info_unchecked(cursor, userid) self.send( userid, Event.OfferEvent(u.agent_index, amt, str(time.time()))) except sqlite3.IntegrityError: print("WARNING: Rolled back transaction") return None
def text(): backend = get_backend() message = request.args.get('message') displayed_message = format_message("You: {}".format(message), False) uid = userid() time_taken = float(request.args.get('time_taken')) received_time = time.time() start_time = received_time - time_taken chat_info = backend.get_chat_info(uid) backend.send( uid, Event.MessageEvent(chat_info.agent_index, message, str(received_time), str(start_time))) return jsonify(message=displayed_message)
def select(self, userid, idx): try: with self.conn: cursor = self.conn.cursor() u = self._get_user_info_unchecked(cursor, userid) scenario = self.scenario_db.get(u.scenario_id) kb = scenario.get_kb(u.agent_index) item = kb.items[idx] self.send(userid, Event.SelectionEvent(u.agent_index, item, str(time.time()))) return item except sqlite3.IntegrityError: print("WARNING: Rolled back transaction") return None
def render_chat(chat, agent=None, partner_type='human'): events = [Event.from_dict(e) for e in chat["events"]] if len(events) == 0: return False, None chat_html = [ '<div class=\"chatLog\">', '<div class=\"divTitle\"> Chat Log </div>', '<table class=\"chat\">' ] agent_str = {0: '', 1: ''} # Used for visualizing chat during debugging if agent is not None: agent_str[agent] = 'Agent %d (you)' % agent agent_str[1 - agent] = 'Agent %d (%s)' % (1 - agent, partner_type) elif 'agents' in chat and chat['agents']: for agent in (0, 1): agent_str[agent] = 'Agent %d (%s)' % ( agent, AGENT_NAMES[chat['agents'][str(agent)]]) else: for agent in (0, 1): agent_str[agent] = 'Agent %d (%s)' % (agent, 'unknown') for event in events: t = datetime.datetime.fromtimestamp(float( event.time)).strftime('%Y-%m-%d %H:%M:%S') a = agent_str[event.agent] if event.action == 'message': s = event.data elif event.action == 'select': # s = 'SELECT (' + ' || '.join(event.data.values()) + ')' event_vals = ast.literal_eval(event.data).values() # import pdb; pdb.set_trace() s = 'SELECT (' + ' || '.join(event_vals) + ')' row = '<tr class=\"agent%d\">\ <td class=\"time\">%s</td>\ <td class=\"agent\">%s</td>\ <td class=\"message\">%s</td>\ </tr>' % (event.agent, t, a, s) chat_html.append(row) chat_html.extend(['</table>', '</div>']) completed = False if chat["outcome"] is None or chat["outcome"][ "reward"] == 0 else True return completed, chat_html
def text(): backend = get_backend() message = request.args.get('message') logger.debug("User %s said: %s" % (userid_prefix(), message)) # utf-8 encoded_message = message.encode('utf-8') displayed_message = format_message("You: {}".format(encoded_message), False) uid = userid() time_taken = float(request.args.get('time_taken')) received_time = time.time() start_time = received_time - time_taken chat_info = backend.get_chat_info(uid) backend.send( uid, Event.MessageEvent(chat_info.agent_index, message, str(received_time), str(start_time))) return jsonify(message=displayed_message)
def convert_events_to_json(chat_id, cursor, scenario_db): try: cursor.execute( 'SELECT agent, action, time, data, start_time FROM event WHERE chat_id=? ORDER BY time ASC', (chat_id, )) logged_events = cursor.fetchall() except sqlite3.OperationalError: cursor.execute( 'SELECT agent, action, time, data FROM event WHERE chat_id=? ORDER BY time ASC', (chat_id, )) logged_events = cursor.fetchall() events = [] for i, (agent, action, time, data) in enumerate(logged_events): events.append((agent, action, time, data, time)) logged_events = events cursor.execute('SELECT scenario_id, outcome FROM chat WHERE chat_id=?', (chat_id, )) (uuid, outcome) = cursor.fetchone() try: outcome = json.loads(outcome) except ValueError: outcome = {'reward': 0} try: cursor.execute('SELECT agent_types FROM chat WHERE chat_id=?', (chat_id, )) agent_types = cursor.fetchone()[0] agent_types = json.loads(agent_types) except sqlite3.OperationalError: agent_types = {0: HumanSystem.name(), 1: HumanSystem.name()} chat_events = [] for (agent, action, time, data, start_time) in logged_events: if action == 'join' or action == 'leave': continue if action == 'select': data = json.loads(data) time = convert_time_format(time) start_time = convert_time_format(start_time) event = Event(agent, time, action, data, start_time) chat_events.append(event) return Example(scenario_db.get(uuid), uuid, chat_events, outcome, chat_id, agent_types)
def get_chat_events(cls, cursor, chat_id): """Read all events in the chat specified by chat_id. Returns: [Event] """ cursor.execute('SELECT * FROM event WHERE chat_id=? ORDER BY time ASC', (chat_id, )) logged_events = cursor.fetchall() chat_events = [] agent_chat = {0: False, 1: False} for row in logged_events: # Compatible with older event structure agent, action, time, data = [ row[k] for k in ('agent', 'action', 'time', 'data') ] try: start_time = row['start_time'] except IndexError: start_time = time try: metadata = json.loads(row['metadata']) except IndexError: metadata = None if action == 'join' or action == 'leave' or action == 'typing': continue if action == 'message' and len(data.strip()) == 0: continue data = cls.process_event_data(action, data) agent_chat[agent] = True time = cls.convert_time_format(time) start_time = cls.convert_time_format(start_time) # event = Event(agent, time, action, data, start_time, metadata=metadata) event = Event(agent, time, action, data, start_time) chat_events.append(event) return chat_events
def select(self, item): return Event(agent=self.agent, time=None, action='select', data=item)
def message(self, text): return Event(agent=self.agent, time=None, action='message', data=text)
def message(self, text, state=None): event = Event(agent=self.agent, time=None, action='message', data=text) event.state = state return event