Пример #1
0
def new_reply_with_array_obj_input(body):  # noqa: E501
    # 拒絕非認證的來源 refuse user or origin
    Origin = connexion.request.headers["Sec-Fetch-Site"] if "Sec-Fetch-Site" in connexion.request.headers else \
    connexion.request.headers["Origin"] if "Origin" in connexion.request.headers else None
    if Origin != "same-site" and Origin != "same-origin" and Origin != "https://goodclass.cf":
        return {"ERROR": "Unauthorized USER"}, 401, header

    if connexion.request.is_json:
        body_json = connexion.request.get_json()
        body = Comment.from_dict(body_json)  # noqa: E501
        try:
            c = operation()
            comment_id = body_json['comment_id']
            user_memo = body_json['user_memo']

            _ = c.new_reply_byid(comment_id=comment_id, user_memo=user_memo)

            return Message(msg="ok").to_dict(), 200, header
        except Exception as e:
            return Message(
                request_status="error",
                msg="UNKNOWERROR: {}".format(e)).to_dict(), 200, header
    else:
        error_msg = Message(request_status="error",
                            msg="connexion.request.is_json")
        return error_msg.to_dict(), 500, header
Пример #2
0
def delete_reply_with_array_obj_input(reply_id):  # noqa: E501
    # 拒絕非認證的來源 refuse user or origin
    Origin = connexion.request.headers["Sec-Fetch-Site"] if "Sec-Fetch-Site" in connexion.request.headers else \
    connexion.request.headers["Origin"] if "Origin" in connexion.request.headers else None
    if Origin != "same-site" and Origin != "same-origin" and Origin != "https://goodclass.cf":
        return {"ERROR": "Unauthorized USER"}, 401, header
    try:
        c = operation()

        c.delete_reply_byid(reply_id=reply_id)
        return Message(msg="ok").to_dict(), 200, header
    except Exception as e:
        return Message(request_status="error",
                       msg="UNKNOWERROR: {}".format(e)).to_dict(), 200, header
Пример #3
0
    def __init__(self, question_number):
        """
		Initialize the class
		:param question_number: which question number this is
		"""
        self._question_number = question_number
        self._now = datetime.datetime.now()
        self._results = []
        self._num_results = 0
        # Create the message object and fill it with attributes about the response
        self.message = Message()
        self.message.type = "translator_reasoner_message"
        self.message.tool_version = RTXConfiguration.version
        self.message.schema_version = "0.9.2"
        self.message.message_code = "OK"
        #self.message.code_description = "Placeholder for description"
        self.message.code_description = "%s results found" % self._num_results

        #### Create an empty master knowledge graph
        self.message.knowledge_graph = KnowledgeGraph()
        self.message.knowledge_graph.nodes = []
        self.message.knowledge_graph.edges = []

        #### Create an internal lookup dict of nodes and edges for maintaining the master knowledge graph
        self._node_ids = dict()
        self._edge_ids = dict()
        self._edge_counter = 0
def new_class_with_array_obj_input(body):  # noqa: E501
    # 拒絕非認證的來源 refuse user or origin
    Origin = connexion.request.headers["Sec-Fetch-Site"] if "Sec-Fetch-Site" in connexion.request.headers else \
    connexion.request.headers["Origin"] if "Origin" in connexion.request.headers else None
    if Origin != "same-site" and Origin != "same-origin" and Origin != "https://goodclass.cf":
        return {"ERROR": "Unauthorized USER"}, 401, header
    """Info of class

     # noqa: E501

    :param body: Pet object that needs to be added to the store
    :type body: dict | bytes

    :rtype: object
    """
    if connexion.request.is_json:
        body_json = connexion.request.get_json()
        body = Comment.from_dict(body_json)  # noqa: E501
        try:
            c = comment_operation()
            major = body_json[
                'major'] if 'major' in body_json else "這傢伙很懶,什麼都沒有寫"
            midexam = body_json[
                'midexam'] if 'midexam' in body_json else "這傢伙很懶,什麼都沒有寫"
            endexam = body_json[
                'endexam'] if 'endexam' in body_json else "這傢伙很懶,什麼都沒有寫"
            value = body_json[
                'value'] if 'value' in body_json else "這傢伙很懶,什麼都沒有寫"
            cost = body_json['cost'] if 'cost' in body_json else "這傢伙很懶,什麼都沒有寫"
            classcall = body_json[
                'classcall'] if 'classcall' in body_json else 2
            homework = body_json['homework'] if 'homework' in body_json else 2
            classexam = body_json[
                'classexam'] if 'classexam' in body_json else 2
            _ = c.new_comment_byid(body.class_name, body.teacher_name, major,
                                   midexam, endexam, body.user_memo, value,
                                   cost, classcall, homework, classexam)

            return Message(msg="ok").to_dict(), 200, header
        except Exception as e:
            return Message(
                request_status="error",
                msg="UNKNOWERROR: {}".format(e)).to_dict(), 200, header
    else:
        error_msg = Message(request_status="error",
                            msg="connexion.request.is_json")
        return error_msg.to_dict(), 500, header
Пример #5
0
    def create_message(self, describe=False):
        """
        Creates a basic empty Message object with basic boilerplate metadata
        :return: Response object with execution information and the new message object inside the data envelope
        :rtype: Response
        """

        # Internal documentation setup
        #allowable_parameters = { 'action': { 'None' } }
        allowable_parameters = {
            'dsl_command': '`create_message()`'
        }  # can't get this name at run-time, need to manually put it in per https://www.python.org/dev/peps/pep-3130/
        if describe:
            allowable_parameters[
                'brief_description'] = """The `create_message` method creates a basic empty Message object with basic boilerplate metadata
            such as reasoner_id, schema_version, etc. filled in. This DSL command takes no arguments"""
            return allowable_parameters

        #### Define a default response
        response = Response()
        self.response = response

        #### Create the top-level message
        response.info("Creating an empty template ARAX Message")
        message = Message()
        self.message = message

        #### Fill it with default information
        message.id = None
        message.type = "translator_reasoner_message"
        message.reasoner_id = "ARAX"
        message.tool_version = RTXConfiguration().version
        message.schema_version = "0.9.3"
        message.message_code = "OK"
        message.code_description = "Created empty template Message"
        message.context = "https://raw.githubusercontent.com/biolink/biolink-model/master/context.jsonld"

        #### Why is this _datetime ?? FIXME
        message._datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        #### Create an empty master knowledge graph
        message.knowledge_graph = KnowledgeGraph()
        message.knowledge_graph.nodes = []
        message.knowledge_graph.edges = []

        #### Create an empty query graph
        message.query_graph = QueryGraph()
        message.query_graph.nodes = []
        message.query_graph.edges = []

        #### Create empty results
        message.results = []
        message.n_results = 0

        #### Return the response
        response.data['message'] = message
        return response
Пример #6
0
def update_reply_with_array_obj_input(body):  # noqa: E501
    # 拒絕非認證的來源 refuse user or origin
    Origin = connexion.request.headers["Sec-Fetch-Site"] if "Sec-Fetch-Site" in connexion.request.headers else \
    connexion.request.headers["Origin"] if "Origin" in connexion.request.headers else None
    if Origin != "same-site" and Origin != "same-origin" and Origin != "https://goodclass.cf":
        return {"ERROR": "Unauthorized USER"}, 401, header

    error_msg = Message(request_status="error", msg="NotImplementedError")
    return error_msg.to_dict(), 500, header
Пример #7
0
def message_get():
    """
    message_get
    Returns a greeting.

    :rtype: Message
    """
    response = Message()
    response.message = 'Hello World'
    return response
Пример #8
0
def main():

    #### Create a response object
    response = Response()

    #### Create an ActionsParser object
    from actions_parser import ActionsParser
    actions_parser = ActionsParser()
 
    #### Set a simple list of actions
    actions_list = [
        "filter(start_node=1, maximum_results=10, minimum_confidence=0.5)",
        "return(message=true,store=false)"
    ]

    #### Parse the action_list and print the result
    result = actions_parser.parse(actions_list)
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=Response.DEBUG))
        return response
    actions = result.data['actions']

    #### Read message #2 from the database. This should be the acetaminophen proteins query result message
    sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../UI/Feedback")
    from RTXFeedback import RTXFeedback
    araxdb = RTXFeedback()
    message_dict = araxdb.getMessage(2)

    #### The stored message comes back as a dict. Transform it to objects
    sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../OpenAPI/python-flask-server/")
    from swagger_server.models.message import Message
    message = Message().from_dict(message_dict)

    #### Create a filter object and use it to apply action[0] from the list
    filter = ARAXFilter()
    result = filter.apply(message,actions[0]['parameters'])
    response.merge(result)
    if result.status != 'OK':
        print(response.show(level=Response.DEBUG))
        return response
    response.data = result.data

    #### Show the final message
    print(response.show(level=Response.DEBUG))
    response.data['message_stats'] = { 'n_results': message.n_results, 'id': message.id,
        'reasoner_id': message.reasoner_id, 'tool_version': message.tool_version }
    print(json.dumps(ast.literal_eval(repr(response.data['parameters'])),sort_keys=True,indent=2))
    for result in message.results:
        if result.essence is not None:
            essence = result.essence
        else:
            essence = f"{len(result.node_bindings)} node bindings, {len(result.edge_bindings)} edge bindings"
        print(f" - {essence}")
    print(json.dumps(ast.literal_eval(repr(response.data['message_stats'])),sort_keys=True,indent=2))
Пример #9
0
    def test_message(self):
        """Test case for message

        requesting chatbot to handle task
        """
        message = Message()
        response = self.client.open(
            '/v1/bot',
            method='POST',
            data=json.dumps(message),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #10
0
    def test_add_message(self):
        """Test case for add_message

        Add a new message (to the agent's multichain stream)
        """
        body = Message()
        response = self.client.open(
            '/v0_9_1/{agentIdPath}/Messages'.format(agentIdPath='agentIdPath_example'),
            method='POST',
            data=json.dumps(body),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
def delete_class_with_array_obj_input(comment_id):  # noqa: E501
    # 拒絕非認證的來源 refuse user or origin
    Origin = connexion.request.headers["Sec-Fetch-Site"] if "Sec-Fetch-Site" in connexion.request.headers else \
    connexion.request.headers["Origin"] if "Origin" in connexion.request.headers else None
    if Origin != "same-site" and Origin != "same-origin" and Origin != "https://goodclass.cf":
        return {"ERROR": "Unauthorized USER"}, 401, header
    """Info of class

     # noqa: E501

    :param comment_id: Eamples: 1
    :type comment_id: int

    :rtype: object
    """
    try:
        c = comment_operation()

        c.delete_comment_byid(comment_id=comment_id)
        return Message(msg="ok").to_dict(), 200, header
    except Exception as e:
        return Message(request_status="error",
                       msg="UNKNOWERROR: {}".format(e)).to_dict(), 200, header
Пример #12
0
def get_message_by_id(messageId):  # noqa: E501
    """Find message by ID

    Returns a single message # noqa: E501

    :param messageId: ID of message to return
    :type messageId: str

    :rtype: Message
    """

    response = Message("A comprehensive journey into the PRESENT of DevOps")

    return response
Пример #13
0
    def integrate(self, query):
        if "options" in query and query["options"] is not None:
            if re.search("integrate=.+", query["options"]):
                integrate_option = query["options"]
                eprint(integrate_option)
                target_string = re.sub("integrate=", "", integrate_option)
                targets = re.split(",", target_string)
                eprint(targets)

                final_message = Message()

                for reasoner_id in targets:
                    eprint("Looping with reasoner_id=" + reasoner_id)
                    query["options"] = "foo"
                    url = None
                    if reasoner_id == "RTX":
                        url = "https://arax.rtx.ai/devED/api/rtx/v1/query"
                    elif reasoner_id == "Robokop":
                        url = "http://robokop.renci.org:6011/api/query"
                    elif reasoner_id == "Indigo":
                        url = "https://indigo.ncats.io/reasoner/api/v0/query"
                        url = None
                    else:
                        eprint("ERROR: Unrecognized target '" + target + "'")
                    if url is not None:
                        eprint("Querying url " + url)
                        message_content = requests.post(
                            url,
                            headers={'accept': 'application/json'},
                            json=query)
                        status_code = message_content.status_code
                        message_dict = message_content.json()
                        message = Message.from_dict(message_dict)
                        if reasoner_id == "RTX":
                            final_message = message
                        if reasoner_id == "Robokop" or reasoner_id == "Indigo":
                            #if reasoner_id == "Robokop":
                            eprint("Merging in " + reasoner_id)
                            message = self.fix_message(query, message,
                                                       reasoner_id)
                            if message.results is not None:
                                final_message = self.merge_message2(
                                    final_message, message)

                return (final_message)
            return (None)
        return (None)
Пример #14
0
    def from_dict(self, message):

        if str(message.__class__
               ) != "<class 'swagger_server.models.message.Message'>":
            message = Message().from_dict(message)
        message.query_graph = QueryGraph().from_dict(message.query_graph)
        message.knowledge_graph = KnowledgeGraph().from_dict(
            message.knowledge_graph)

        #### This is an unfortunate hack that fixes qnode.curie entries
        #### Officially a curie can be a str or a list. But Swagger 2.0 only permits one type and we set it to str
        #### so when it gets converted from_dict, the list gets converted to a str because that's its type
        #### Here we force it back. This should no longer be needed when we are properly on OpenAPI 3.0
        if message.query_graph is not None and message.query_graph.nodes is not None:
            for qnode in message.query_graph.nodes:
                if qnode.curie is not None and isinstance(qnode.curie, str):
                    if qnode.curie[0:2] == "['":
                        try:
                            qnode.curie = ast.literal_eval(qnode.curie)
                        except:
                            pass

        #new_nodes = []
        #for qnode in message.query_graph.nodes:
        #    print(type(qnode))
        #    new_nodes.append(QNode().from_dict(qnode))
        #message.query_graph.nodes = new_nodes
        #for qedge in message.query_graph.edges:
        #    new_edges.append(QEdge().from_dict(qedge))
        #message.query_graph.edges = new_edges

        if message.results is not None:
            for result in message.results:
                if result.result_graph is not None:
                    #eprint(str(result.result_graph.__class__))
                    if str(
                            result.result_graph.__class__
                    ) != "<class 'swagger_server.models.knowledge_graph.KnowledgeGraph'>":
                        result.result_graph = KnowledgeGraph().from_dict(
                            result.result_graph)

        return message
def update_class_with_array_obj_input(body):  # noqa: E501
    # 拒絕非認證的來源 refuse user or origin
    Origin = connexion.request.headers["Sec-Fetch-Site"] if "Sec-Fetch-Site" in connexion.request.headers else \
    connexion.request.headers["Origin"] if "Origin" in connexion.request.headers else None
    if Origin != "same-site" and Origin != "same-origin" and Origin != "https://goodclass.cf":
        return {"ERROR": "Unauthorized USER"}, 401, header
    """Info of class

     # noqa: E501

    :param body: Pet object that needs to be added to the store
    :type body: dict | bytes

    :rtype: object
    """
    if connexion.request.is_json:
        body = Comment.from_dict(connexion.request.get_json())  # noqa: E501
        return body, 200, header
    else:
        error_msg = Message(request_status="error",
                            msg="connexion.request.is_json")
        return error_msg.to_dict(), 500, header
Пример #16
0
    def query(self, query):

        #### Get our configuration information

        #### Create a Message object as a response
        response = Message()
        execution_string = None

        #### Determine a plan for what to do based on the input
        result = self.examine_incoming_query(query)
        if result["message_code"] != "OK":
            response.message_code = result["message_code"]
            response.code_description = result["code_description"]
            return response

        #### If we have a previous message processing plan, handle that
        if "have_previous_message_processing_plan" in result:
            rtxFeedback = RTXFeedback(
            )  # FIXME. This should be a separate class I think, not the Feedback class. TODO: Separate them
            rtxFeedback.connect()
            message = rtxFeedback.processExternalPreviousMessageProcessingPlan(
                query)
            rtxFeedback.disconnect()
            return (message)

        #### If we have a query_graph, pass this on to the QueryGraphReasoner
        if "have_query_graph" in result:
            qgr = QueryGraphReasoner()
            message = qgr.answer(query["message"]["query_graph"],
                                 TxltrApiFormat=True)
            #self.log_query(query,message,'new')
            rtxFeedback = RTXFeedback()
            rtxFeedback.connect()
            rtxFeedback.addNewMessage(message, query)
            rtxFeedback.disconnect()
            self.limit_message(message, query)
            return (message)

        #### Otherwise extract the id and the terms from the incoming parameters
        else:
            id = query["message"]["query_type_id"]
            terms = query["message"]["terms"]

        #### Check to see if the query_options indicates to query named resource and integrate the results
        if "have_query_type_id_and_terms" in result and "message" in query and "query_options" in query[
                "message"] and "integrate" in query["message"]["query_options"]:
            response = self.integrate(query)
            #self.log_query(query,response,'remote')
            return response

        #### Create an RTX Feedback management object
        #eprint(query)
        rtxFeedback = RTXFeedback()
        rtxFeedback.connect()
        cachedMessage = rtxFeedback.getCachedMessage(query)

        #### If we can find a cached message for this query and this version of RTX, then return the cached message
        if (cachedMessage is not None):
            apiMessage = Message().from_dict(cachedMessage)
            rtxFeedback.disconnect()
            self.limit_message(apiMessage, query)

            if apiMessage.message_code is None:
                if apiMessage.result_code is not None:
                    apiMessage.message_code = apiMessage.result_code
                else:
                    apiMessage.message_code = "wha??"

            self.log_query(query, apiMessage, 'cached')
            return apiMessage

        #### Still have special handling for Q0
        if id == 'Q0':
            q0 = Q0()
            message = q0.answer(terms["term"], use_json=True)
            if 'original_question' in query["message"]:
                message.original_question = query["message"][
                    "original_question"]
                message.restated_question = query["message"][
                    "restated_question"]
            message.query_type_id = query["message"]["query_type_id"]
            message.terms = query["message"]["terms"]
            id = message.id
            codeString = message.message_code
            self.log_query(query, message, 'new')
            rtxFeedback.addNewMessage(message, query)
            rtxFeedback.disconnect()
            self.limit_message(message, query)
            return (message)

        #### Else call out to original solution scripts for an answer
        else:

            #### If some previous processing has determined what the solution script to use is, then use that
            if execution_string is not None:
                command = "python3 " + execution_string

            #### Else use the ParseQuestion system to determine what the execution_string should be
            else:
                txltr = ParseQuestion()
                command = "python3 " + txltr.get_execution_string(id, terms)

            #### Set CWD to the QuestioningAnswering area and then invoke from the shell the Q1Solution code
            cwd = os.getcwd()
            os.chdir(
                os.path.dirname(os.path.abspath(__file__)) +
                "/../../../reasoningtool/QuestionAnswering")
            eprint(command)
            returnedText = subprocess.run([command],
                                          stdout=subprocess.PIPE,
                                          shell=True)
            os.chdir(cwd)

            #### reformat the stdout result of the shell command into a string
            reformattedText = returnedText.stdout.decode('utf-8')
            #eprint(reformattedText)

            #### Try to decode that string into a message object
            try:
                #data = ast.literal_eval(reformattedText)
                data = json.loads(reformattedText)
                message = Message.from_dict(data)
                if message.message_code is None:
                    if message.result_code is not None:
                        message.message_code = message.result_code
                    else:
                        message.message_code = "wha??"

            #### If it fails, the just create a new Message object with a notice about the failure
            except:
                message = Message()
                message.message_code = "InternalError"
                message.code_description = "Error parsing the message from the reasoner. This is an internal bug that needs to be fixed. Unable to respond to this question at this time. The unparsable message was: " + reformattedText

            #print(query)
            if 'original_question' in query["message"]:
                message.original_question = query["message"][
                    "original_question"]
                message.restated_question = query["message"][
                    "restated_question"]
            message.query_type_id = query["message"]["query_type_id"]
            message.terms = query["message"]["terms"]

            #### Log the result and return the Message object
            self.log_query(query, message, 'new')
            rtxFeedback.addNewMessage(message, query)
            rtxFeedback.disconnect()

            #### Limit message
            self.limit_message(message, query)
            return (message)

        #### If the query type id is not triggered above, then return an error
        message = Message()
        message.message_code = "UnsupportedQueryTypeID"
        message.code_description = "The specified query id '" + id + "' is not supported at this time"
        rtxFeedback.disconnect()
        return (message)
Пример #17
0
 def createMessage(self):
     #### Create the message object and fill it with attributes about the message
     message = Message()
     message.message_code = "OK"
     message.code_description = "??"
     return message
from swagger_server.models.message import Message

a = Message(request_status="success",msg="hi")
print(a.to_dict())