def run_bot(tags, intents): conversation = Conversation(tags, intents) while not conversation.is_finished(): sentence = str(input("Human: ")) answer = conversation.input_sentence(sentence) print('Bot :', answer)
def new_conversation(self, worker, user): worker = int(worker) user = int(user) conv = Conversation(worker, user) self.active_conversations.append(conv) self.waiting_queue.remove(user)
def _load_model(): global sentiment_analysis global conversation with graph.as_default(): sentiment_analysis = SentimentAnalysis(SA_TOKENIZER, SA_MODEL) conversation = Conversation(CONVERSATION_MODEL)
def getConversation(self, converseid): query = "PREPARE stmt(text) AS " \ "SELECT * FROM conversation WHERE converseid = $1;" \ "EXECUTE stmt('" + str(converseid) + "');" conversation = Database.connectDB(self, query) if not conversation: conversation = 0 else: conversation = conversation[0] conzip = json.loads(conversation[3]) speakers = [] descrips = [] links = [] images = [] for converse in conzip.values(): speakers.append(converse[0]) descrips.append(converse[1]) links.append(converse[2]) images.append(converse[3]) conversation = Conversation(conversation[0], conversation[1], conversation[2], speakers, descrips, links, images, conversation[4], conversation[5], conversation[6]) return conversation
def getccEndorsed(self, threshold): query = "PREPARE stmt(int) AS " \ "SELECT * FROM conversation WHERE endorsements >= $1;" \ "EXECUTE stmt(" + str(threshold) + ");" conversations = Database.connectDB(self, query) conversation_list = [] for i, conversation in enumerate(conversations): conzip = json.loads(conversation[3]) speakers = [] descrips = [] links = [] images = [] for converse in conzip.values(): speakers.append(converse[0]) descrips.append(converse[1]) links.append(converse[2]) images.append(converse[3]) conversation_list.append( Conversation(conversation[0], conversation[1], conversation[2], speakers, descrips, links, images, conversation[4], conversation[5], conversation[6])) return conversation_list
def getConversations(self, promoted): if promoted == 0: query = "SELECT * FROM conversation WHERE faculty = '0'" else: query = "SELECT * FROM conversation WHERE faculty != '0'" conversations = Database.connectDB(self, query) conversation_list = [] for i, conversation in enumerate(conversations): conzip = json.loads(conversation[3]) speakers = [] descrips = [] links = [] images = [] for converse in conzip.values(): speakers.append(converse[0]) descrips.append(converse[1]) links.append(converse[2]) images.append(converse[3]) conversation_list.append( Conversation(conversation[0], conversation[1], conversation[2], speakers, descrips, links, images, conversation[4], conversation[5], conversation[6])) return conversation_list
def __init__(self): self.trip_date = "" # The date of the trip self.trip_forecast = "" # The forecast for the trip self.check_date = False # Flag for verify date in user input self.other_trip = False # Flag for checking if we will provide info for other trip self.conversation = Conversation(current_app) self.bot = create_chatbot()
def get_message_history(): conversation_db_path = get_conversation_db_path_for_users(request.form) conversation = Conversation(conversation_db_path) history = conversation.get_history() return jsonify({"history": history})
def start(update, context): if update.effective_user.id not in ADMINS_IDS: return text = 'Админка. Для отмены, нажмите "готово".' buttons = [] for i, question in enumerate(Conversation().questions): q_text = _truncate(question['text']) buttons.append([ InlineKeyboardButton(text=q_text, callback_data=f'{DETAIL_QUESTION}_{i}'), InlineKeyboardButton(text='📝', callback_data=f'{CHANGING_QUESTION}_{i}'), InlineKeyboardButton(text='🗑️', callback_data=f'{REMOVING_QUESTION}_{i}'), ]) buttons.extend([ [InlineKeyboardButton(text='Добавить вопрос', callback_data=str(ADDING_QUESTION))], [InlineKeyboardButton(text='Изменить информацию', callback_data=str(CH_INFO))], [InlineKeyboardButton(text='Изменить приветствие', callback_data=str(CH_HELLO))], [InlineKeyboardButton(text='Изменить прощание', callback_data=str(CH_BYE))], [InlineKeyboardButton(text='Готово', callback_data=str(END))] ]) keyboard = InlineKeyboardMarkup(buttons) if update.callback_query: update.callback_query.edit_message_text(text=text, reply_markup=keyboard) else: update.message.reply_text(text=text, reply_markup=keyboard) context.user_data[START_OVER] = True return SELECTING_ACTION
def play_game(li, game_id, control_queue, engine_factory, user_profile, config): updates = li.get_game_stream(game_id).iter_lines() #Initial response of stream will be the full game info. Store it game = model.Game(json.loads(next(updates).decode('utf-8')), user_profile["username"], li.baseUrl) board = setup_board(game) engine = engine_factory(board) conversation = Conversation(game, engine, li, __version__) print("+++ {}".format(game)) engine.pre_game(game) engine_cfg = config["engine"] if (engine_cfg["polyglot"] == True): board = play_first_book_move(game, engine, board, li, engine_cfg) else: board = play_first_move(game, engine, board, li) try: for binary_chunk in updates: upd = json.loads( binary_chunk.decode('utf-8')) if binary_chunk else None u_type = upd["type"] if upd else "ping" if u_type == "chatLine": conversation.react(ChatLine(upd), game) elif u_type == "gameState": game.state = upd moves = upd["moves"].split() board = update_board(board, moves[-1]) if is_engine_move(game, moves): best_move = None if (engine_cfg["polyglot"] == True and len(moves) <= (engine_cfg["polyglot_max_depth"] * 2) - 1): best_move = get_book_move(board, engine_cfg) if best_move == None: best_move = engine.search(board, upd["wtime"], upd["btime"], upd["winc"], upd["binc"]) li.make_move(game.id, best_move) game.abort_in(20) elif u_type == "ping": if game.should_abort_now() and len(game.state["moves"]) < 6: print(" Aborting {} by lack of activity".format( game.url())) li.abort(game.id) except (RemoteDisconnected, ConnectionError, ProtocolError, HTTPError) as exception: print("Abandoning game due to connection error") traceback.print_exception(type(exception), exception, exception.__traceback__) finally: print("--- {} Game over".format(game.url())) engine.quit() # This can raise queue.NoFull, but that should only happen if we're not processing # events fast enough and in this case I believe the exception should be raised control_queue.put_nowait({"type": "local_game_done"})
def finish_add_question(update, context): text = update.message.text try: Conversation().add_question(text) except ValueError as e: update.message.reply_text(str(text)) return _return(update)
def test_process_string(self): app = MagicMock() conversation = Conversation(app) test_cases = [("Hello there!", ['hello', 'there']), ("LIfe is g00d", ['life', 'is', 'g00d']), ("00 123 nananA", ['00', '123', 'nanana'])] for option, answer in test_cases: self.assertEqual(conversation.process_string(option), answer)
def save_conversation(cls, output_stream): """ Outputs conversation. """ if cls.conversation.is_valid(): with open(ParserSettings.output_dir + output_stream, "a", encoding="utf-8") as f: f.write(str(cls.conversation) + "\n") cls.conversation = Conversation()
def get_or_create(self, recipient_id): conversation = self.conversations.get(recipient_id) if conversation: return conversation conversation = Conversation(recipient_id) self.conversations[recipient_id] = conversation return conversation
def create_conversation_db(): conversations_db_path = get_conversation_db_path_for_users(request.form) if not os.path.exists(conversations_db_path): conversation = Conversation(conversations_db_path) conversation.initialise_table() return jsonify({"success": True})
def create_loop(): conversation = Conversation() while True: inp = input('>>> ') if len(inp) > 0: print('<<< ' + str(conversation.respond(inp)))
def parse_input_file(self, hangouts_file_name, user_phone_number): """Parse the Hangouts JSON file containing SMS/MMS messages. :param hangouts_file_name: filename of the Hangouts messages :param user_phone_number: phone number of the user (some messages are missing this) :return: list of Conversation objects, GAIA ID of the user """ conversations = [] self_gaia_id = None # gaia_id for the phone owner with open(hangouts_file_name, 'r') as data_file: # Read the Hangouts JSON file and turn into objects data = json.load(data_file, object_hook=lambda d: Namespace(**d)) # Iterate through each conversation in the list for conversation_state in data.conversation_state: # Get the nested conversation_state state = getattr(conversation_state, "conversation_state", None) if state is not None: # Get the conversation object conversation = getattr(state, "conversation", None) if conversation is None: continue # Create a new conversation and store its properties current_conversation = Conversation() current_conversation.network_types = getattr( conversation, "network_type", None) self_conversation_state = getattr( conversation, "self_conversation_state", None) if self_conversation_state is not None: current_conversation.active_timestamp = self._try_int_attribute( self_conversation_state, "active_timestamp") self_read_state = getattr(self_conversation_state, "self_read_state", None) if self_read_state is not None: current_conversation.self_latest_read_timestamp = \ self._try_int_attribute(self_read_state, "latest_read_timestamp") participant_id = getattr(self_read_state, "participant_id", None) if participant_id is not None: current_self_gaia_id = self._try_int_attribute( participant_id, "gaia_id") if current_self_gaia_id is not None: self_gaia_id = current_self_gaia_id # Get the conversation participants participant_data = getattr(conversation, "participant_data", None) read_state = getattr(conversation, "read_state", None) if participant_data is not None: current_conversation.participants = self._extract_participants( conversation.participant_data, read_state, user_phone_number, self_gaia_id) # Get the conversation messages events = getattr(state, "event", None) if events is not None: current_conversation.messages = self._process_messages( events) conversations.append(current_conversation) return conversations, self_gaia_id
def test_is_negative(self): app = MagicMock() conversation = Conversation(app) test_cases = [("no", True), ("cancel", True), ("dont", True), ("don't", True), ("not", True), ("nope", True), ("n", True), ("0", True), ("hi", False), ("hellow", False), ("1", False)] for option, answer in test_cases: self.assertEqual(conversation.is_negative(option), answer)
def test_is_goodbye(self): app = MagicMock() conversation = Conversation(app) test_cases = [("bye", True), ("see you", True), ("au revoir", True), ("goobye", True), ("bye-bye", True), ("cheers", True), ("farewell", True), ("take care", True), ("hi", False), ("hellow", False)] for option, answer in test_cases: self.assertEqual(conversation.is_goodbye(option), answer)
def finish_change_question(update, context): old_text_id = context.user_data.pop(CHANGING_QUESTION) new_text = update.message.text try: Conversation().change_question(int(old_text_id), new_text) except ValueError as e: update.message.reply_text(text="Произошла ошибка: %s" % str(e)) return _return(update)
def play_game(li, game_id, control_queue, engine_factory, user_profile, config): updates = li.get_game_stream(game_id).iter_lines() #Initial response of stream will be the full game info. Store it game = model.Game(json.loads(next(updates).decode('utf-8')), user_profile["username"], li.baseUrl, config.get("abort_time", 20)) board = setup_board(game) engine = engine_factory(board) conversation = Conversation(game, engine, li, __version__) print("+++ {}".format(game)) engine_cfg = config["engine"] polyglot_cfg = engine_cfg.get("polyglot", {}) book_cfg = polyglot_cfg.get("book", {}) if not polyglot_cfg.get("enabled") or not play_first_book_move(game, engine, board, li, book_cfg): play_first_move(game, engine, board, li) engine.set_time_control(game) try: for binary_chunk in updates: upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None u_type = upd["type"] if upd else "ping" if u_type == "chatLine": conversation.react(ChatLine(upd), game) elif u_type == "gameState": game.state = upd moves = upd["moves"].split() board = update_board(board, moves[-1]) if is_engine_move(game, moves): if config.get("fake_think_time") and len(moves) > 9: delay = min(game.clock_initial, game.my_remaining_seconds()) * 0.015 accel = 1 - max(0, min(100, len(moves) - 20)) / 150 sleep = min(5, delay * accel) time.sleep(sleep) best_move = None if polyglot_cfg.get("enabled") and len(moves) <= polyglot_cfg.get("max_depth", 8) * 2 - 1: best_move = get_book_move(board, book_cfg) if best_move == None: best_move = engine.search(board, upd["wtime"], upd["btime"], upd["winc"], upd["binc"]) li.make_move(game.id, best_move) game.abort_in(config.get("abort_time", 20)) elif u_type == "ping": if game.should_abort_now(): print(" Aborting {} by lack of activity".format(game.url())) li.abort(game.id) except (RemoteDisconnected, ChunkedEncodingError, ConnectionError, ProtocolError, HTTPError) as exception: print("Abandoning game due to connection error") traceback.print_exception(type(exception), exception, exception.__traceback__) finally: print("--- {} Game over".format(game.url())) engine.quit() # This can raise queue.NoFull, but that should only happen if we're not processing # events fast enough and in this case I believe the exception should be raised control_queue.put_nowait({"type": "local_game_done"})
def _handle_activity(self, activity: dict): conversation_key = f"{activity['channelId']}||{activity['conversation']['id']}" if conversation_key not in self.conversations.keys(): self.conversations[conversation_key] = Conversation( self, conversation_key, activity) log.info(f'Created new conversation {conversation_key}') conversation = self.conversations[conversation_key] conversation.handle_activity(activity)
def __init__(self, server_ip, dialogflow_key_file, dialogflow_agent_id): """ :param server_ip: IP address of Social Interaction Cloud server :param dialogflow_key_file: path to Google's Dialogflow key file (JSON) :param dialogflow_agent_id: ID number of Dialogflow agent to be used (project ID) """ self.sic = BasicSICConnector( server_ip, 'en-US', dialogflow_key_file, dialogflow_agent_id) self.conversation = Conversation(self.sic, robot_present=True, animation=True) self.story = Story(interactive=True)
def new_conversation(self, worker_id, user_id): worker = User(worker_id) user = User(user_id) req = self.conversation_requests.get_request_by_user(user.user_id) conv = Conversation(worker, user, req.type) self.active_conversations.append(conv) self.conversation_requests.close(req)
def conv_handler(bot, update): conv = Conversation() name_str = 'chat_{chat_id}'.format(chat_id=update.message.chat_id) conv.set_session(name_str) conv.make_question(update.message.text) answer = conv.get_answer() if answer: update.message.reply_text(answer)
def run(self): if 'first_name' in self.config: salutation = ("How can I be of service, %s?" % self.config["first_name"]) else: salutation = "How can I be of service?" self.mic.say(salutation) conversation = Conversation("JASPER", self.mic, self.config) conversation.handleForever()
def __init__(self, coref_solver, file="", verbose=False): self.end_sentences = [ "exit", "enough for now", "goodbye", "goodnight", "bye", "that is all", "that's all for now" ] self.greetings = [ "hi", "hello", "hi there", "hello there", "good morning", "good afternoon", "hey", "hei", ] self.wh_list = ["who", "what", "where", "why", "when", "which", "how"] self.yes_no_list = [ "is", "are", "am", "will", "could", "would", "may", "can", "have", "has", "had", "did", "do", "does", ] self.end_replies = ["Glad we talked!", "Happy to help!", "Gooodbye!"] self.greetings_replies = [ "Hello! What a wonderful day!", "At your disposal!", "Hi there!" ] self.verbose = verbose if file: self.c = Conversation(file=file) else: self.c = Conversation() self.coref_solver = coref_solver
def create_new_conversation(idd): client, conv_file, extra_config = CLIENTS[idd] config_ = dict(config) config_.update(extra_config) conversation = Conversation(filename=conv_file, client=client, **config_) t = threading.Thread(target=conversation.execute) conversation.set_thread(t) conversation.set_idd(idd) CONVERSATIONS[idd] = conversation audio.enable_server(client) return conversation
def finish_remove_question(update, context): if update.callback_query.data.endswith('1'): return start(update, context) question_id = context.user_data.pop(REMOVING_QUESTION) try: Conversation().remove_question(question_id) except ValueError as e: update.message.reply_text(text="Произошла ошибка: %s" % str(e)) return _return(update)
def get_new_messages(): data = request.form conversation_db_path = get_conversation_db_path_for_users(data) conversation_db = Conversation(conversation_db_path) timestamp = data['timestamp'] requester_username = data['user_one'] new_messages = conversation_db.get_new_messages(timestamp, requester_username) return jsonify({'messages': new_messages})