def hello_world_genqa(ctx): server = ctx.conf(key=DRQA_SERVER_ADDRESS) if not server: logger.error('Server address is not set. Shutting down GenQA.') return rs.Delete() if not server_up(server): return rs.Delete()
def send_on_telegram(ctx: rs.ContextWrapper, text: str): """ If all telegram chats should be in the same context, sends the text to every currently active chat. Otherwise it only sends output using the Pipe if it is a child process """ if not text or not isinstance(text, str): return rs.Resign() if ctx.conf(key=ALL_IN_ONE_CONTEXT_CONFIG_KEY): # TODO don't instantiate the updater every time token = ctx.conf(key=TOKEN_CONFIG_KEY) if not token: logger.error('telegram-token is not set. Shutting down telegramio') return rs.Delete() updater: Updater = Updater(token) for chat_id in active_chats.keys(): updater.bot.send_message(chat_id=chat_id, text=text) else: child_conn = ctx.conf(key=CHILD_CONN_CONFIG_KEY) if child_conn: # Child Process -> write to Pipe child_conn.send(text) else: # Master Process -> State not needed return rs.Delete()
def wildtalk_state(ctx): """ Wildtalk using a HTTP server. Post input and get answer through the HTTP interface. """ server_address = f"{ctx.conf(key=SERVER_ADDRESS_KEY)}:{ctx.conf(key=SERVER_PORT_KEY)}" if not server_up(server_address): global server_started if server_started: # don't resign if server started logger.info( "\n--------" "\nThe Wildtalk server is still starting up. It will not react to this input." "\n--------") return else: logger.error( "\n--------" "\nThe Wildtalk server does not seem to be running. Wildtalk will not work, so no fallback answers!" "\n--------") return rs.Delete(resign=True) params = {'prompt': ctx[rawio.prop_in.changed()]} for key in [TEMPERATURE_KEY, MAX_LENGTH_KEY, TOP_K_KEY, TOP_P_KEY, MAX_HISTORY_KEY]: params[key] = ctx.conf(key=key) sample = None while not sample: # sample might be "fully sanitized" and empty response = requests.get(server_address, params=params) response_json = response.json() logger.info(response_json) sample = response_json['response'].strip() ctx[rawio.prop_out] = sample
def _bootstrap_telegram_master(): """ Handle TelegramIO as the Master Process. Start the bot, and handle incoming telegram messages. """ token = ctx.conf(key=TOKEN_CONFIG_KEY) if not token: logger.error( f'{TOKEN_CONFIG_KEY} is not set. Shutting down telegramio') return rs.Delete() child_config_paths_list = ctx.conf(key=CHILD_FILES_CONFIG_KEY) if not ctx.conf(key=ALL_IN_ONE_CONTEXT_CONFIG_KEY) and ( not child_config_paths_list or not isinstance(child_config_paths_list, list) or not all( os.path.isfile(child_config_path) for child_config_path in child_config_paths_list)): logger.error( f'{CHILD_FILES_CONFIG_KEY} is not set (correctly). Shutting down telegramio' ) return rs.Delete() updater: Updater = Updater(token) # Get the dispatcher to register handlers dispatcher: Dispatcher = updater.dispatcher if ctx.conf(key=ALL_IN_ONE_CONTEXT_CONFIG_KEY): # handle noncommand-messages with the matching handler dispatcher.add_handler(MessageHandler(Filters.text, handle_text)) dispatcher.add_handler(MessageHandler(Filters.photo, handle_photo)) else: dispatcher.add_handler( MessageHandler(Filters.text | Filters.photo, handle_input_multiprocess)) # log all errors dispatcher.add_error_handler(error) # Start the Bot updater.start_polling() # non blocking if not ctx.conf(key=ALL_IN_ONE_CONTEXT_CONFIG_KEY): _manage_children(updater)
def small_talk(ctx: rs.ContextWrapper): sess: Session = mem.get_session() interloc: Node = ctx[interloc_path] if interloc.get_id( ) < 0: # ask for name, if the interlocutor is not (yet) a persistent instance pred = "NAME" else: pred = find_empty_relationship(interloc.get_relationships()) ctx[prop_subject] = interloc_path if not ctx[prop_predicate]: if pred: logger.info(f"Personal question: intent={pred}") ctx[prop_predicate] = pred ctx[rawio.prop_out] = verbaliser.get_random_question(pred) else: unused_fup_preds = PREDICATE_SET.difference( used_follow_up_preds) if not unused_fup_preds: logger.info( f"Ran out of smalltalk predicates for {interloc_path}, committing suicide..." ) return rs.Delete(resign=True) pred = random.sample( PREDICATE_SET.difference(used_follow_up_preds), 1) pred = pred[0] used_follow_up_preds.add(pred) ctx[prop_predicate] = pred relationship_ids: Set[int] = interloc.get_relationships( pred) if len(relationship_ids) > 0: # Just to be safe ... object_node_list = sess.retrieve( node_id=list(relationship_ids)[0]) if len(object_node_list) > 0: ctx[rawio. prop_out] = verbaliser.get_random_followup_question( pred).format( name=interloc.get_name(), obj=object_node_list[0].get_name()) logger.info(f"Follow-up: intent={pred}") return rs.Emit() return rs.Resign() else: # While the predicate is set, repeat the question. Once the predicate is answered, # it will be set to None, such that a new predicate is entered. ctx[rawio.prop_out] = verbaliser.get_random_question( ctx[prop_predicate])
def drqa_module(ctx): """ general question answering using DrQA through a HTTP server connection check to server post input question and get DrQA answer through the HTTP interface depending on the answer score the answer is introduced as sane or insane/unsure :) """ server = ctx.conf(key=DRQA_SERVER_ADDRESS) if not server_up(server): return rs.Delete(resign=True) params = {'question': str(ctx[rawio.prop_in]).lower()} response = requests.get(server, params=params) response_json = response.json() certainty = response_json["answers"][0]["span_score"] # sane answer if certainty > ctx.conf(key=ROBOY_ANSWER_SANITY): ctx[rawio.prop_out] = verbaliser.get_random_phrase("question-answering-starting-phrases") + " " + \ response_json["answers"][0]["span"] # insane/unsure answer else: ctx[rawio.prop_out] = verbaliser.get_random_phrase("unsure-question-answering-phrases") \ % response_json["answers"][0]["span"] \ + "\n" + "Maybe I can find out more if your rephrase the question for me."
def sync_ros_properties(ctx: rs.ContextWrapper): """ State that creates a ROS1-Node, registers all Ros1SubProperties and Ros1PubProperties in ROS1 and keeps them synced """ global global_prop_set, global_node # check for ROS1 availability if not ROS1_AVAILABLE: logger.error( "ROS1 is not available, therefore all ROS1-Properties " "will be just normal properties without connection to ROS1!") return rs.Delete() # get config stuff node_name = ctx.conf(key=NODE_NAME_CONFIG_KEY) if not node_name: logger.error( f"{NODE_NAME_CONFIG_KEY} is not set. Shutting down ravestate_ros1") return rs.Delete() spin_frequency = ctx.conf(key=SPIN_FREQUENCY_CONFIG_KEY) if spin_frequency is None or spin_frequency < 0: logger.error( f"{SPIN_FREQUENCY_CONFIG_KEY} is not set or less than 0. Shutting down ravestate_ros1" ) return rs.Delete() if spin_frequency == 0: spin_sleep_time = 0 else: spin_sleep_time = 1 / spin_frequency # Use same node_name if ROS1 was already initialized (i.e. by importing pyroboy) if rospy.get_name(): node_name = rospy.get_name()[1:] # cut off leading / # init ROS1 #rospy.init_node(node_name, disable_signals=True) global global_prop_set # current_props: hash -> Subscriber/Publisher/ServiceProxy current_props: Dict = dict() # ROS1-Context Sync Loop while not ctx.shutting_down() and not rospy.core.is_shutdown(): # remove deleted props removed_props = current_props.keys() - global_prop_set for prop_hash in removed_props: item = current_props[prop_hash] item.unregister() current_props.pop(prop_hash) # add new props new_props = global_prop_set - current_props.keys() for prop in new_props: # register subscribers in ROS1 if isinstance(prop, Ros1SubProperty): # register in context @rs.receptor(ctx_wrap=ctx, write=prop.id()) def ros_to_ctx_callback(ctx, msg, prop_name: str): ctx[prop_name] = msg prop.ros_to_ctx_callback = ros_to_ctx_callback prop.subscriber = rospy.Subscriber( prop.topic, prop.msg_type, prop.ros_subscription_callback) current_props[prop.__hash__()] = prop.subscriber # register publishers in ROS1 if isinstance(prop, Ros1PubProperty): prop.publisher = rospy.Publisher(prop.topic, prop.msg_type, queue_size=prop.queue_size) current_props[prop.__hash__()] = prop.publisher # register clients in ROS1 if isinstance(prop, Ros1CallProperty): prop.client = rospy.ServiceProxy(prop.service_name, prop.service_type) current_props[prop.__hash__()] = prop.client # replace prop with hash in global_props global_prop_set.remove(prop) global_prop_set.add(prop.__hash__()) rospy.rostime.wallsleep(spin_sleep_time) rospy.signal_shutdown("ravestate_ros1 is shutting down")
def sync_ros_properties(ctx: rs.ContextWrapper): """ State that creates a ROS2-Node, registers all Ros2SubProperties and Ros2PubProperties in ROS2 and keeps them synced """ global global_prop_set, global_node # check for ROS2 availability if not ROS2_AVAILABLE: logger.error( "ROS2 is not available, therefore all ROS2-Properties " "will be just normal properties without connection to ROS2!") return rs.Delete() # get config stuff node_name = ctx.conf(key=NODE_NAME_CONFIG_KEY) if not node_name: logger.error( f"{NODE_NAME_CONFIG_KEY} is not set. Shutting down ravestate_ros2") return rs.Delete() spin_frequency = ctx.conf(key=SPIN_FREQUENCY_CONFIG_KEY) if spin_frequency is None or spin_frequency < 0: logger.error( f"{SPIN_FREQUENCY_CONFIG_KEY} is not set or less than 0. Shutting down ravestate_ros2" ) return rs.Delete() if spin_frequency == 0: spin_sleep_time = 0 else: spin_sleep_time = 1 / spin_frequency # init ROS if not rclpy.ok(): rclpy.init() if not global_node: global_node = rclpy.create_node(node_name) global global_prop_set # current_props: hash -> subscription/publisher current_props: Dict = dict() # ROS-Context Sync Loop while not ctx.shutting_down(): # remove deleted props removed_props = current_props.keys() - global_prop_set for prop_hash in removed_props: item = current_props[prop_hash] if isinstance(item, rclpy.subscription.Subscription): global_node.destroy_subscription(item) elif isinstance(item, rclpy.publisher.Publisher): global_node.destroy_publisher(item) elif isinstance(item, rclpy.client.Client): global_node.destroy_client(item) current_props.pop(prop_hash) # add new props new_props = global_prop_set - current_props.keys() for prop in new_props: # register subscribers in ROS if isinstance(prop, Ros2SubProperty): # register in context @rs.receptor(ctx_wrap=ctx, write=prop.id()) def ros_to_ctx_callback(ctx, msg, prop_name: str): ctx[prop_name] = msg prop.ros_to_ctx_callback = ros_to_ctx_callback prop.subscription = global_node.create_subscription( prop.msg_type, prop.topic, prop.ros_subscription_callback) current_props[prop.__hash__()] = prop.subscription # register publishers in ROS if isinstance(prop, Ros2PubProperty): prop.publisher = global_node.create_publisher( prop.msg_type, prop.topic) current_props[prop.__hash__()] = prop.publisher # register clients in ROS if isinstance(prop, Ros2CallProperty): prop.client = global_node.create_client( prop.service_type, prop.service_name) current_props[prop.__hash__()] = prop.client # replace prop with hash in global_props global_prop_set.remove(prop) global_prop_set.add(prop.__hash__()) # spin once rclpy.spin_once(global_node, timeout_sec=0) time.sleep(spin_sleep_time) global_node.destroy_node() rclpy.shutdown()