Example #1
0
def data_fetch_get():  # noqa: E501
    """Fetch data to the server

    This data fetch endpoint upload the csv datafiles to the server using predeifned urls # noqa: E501


    :rtype: object
    """
    if utility.downloadData():
        return Response(True, "Data fetch successfull")
    else:
        return Response(False, "Data fetch failed")
Example #2
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._result_list = []
        self._num_results = 0
        # Create the response object and fill it with attributes about the response
        self.response = Response()
        #self.response.context = "http://translator.ncats.io"
        #self.response.id = "http://rtx.ncats.io/api/v1/response/1234"
        #self.response.id = "-1"
        self.response.type = "medical_translator_query_result"
        self.response.tool_version = "RTX 0.4"
        self.response.schema_version = "0.5"
        #self.response.datetime = self._now.strftime("%Y-%m-%d %H:%M:%S")
        #self.response.original_question_text = ""  # Eric fills it in
        #self.response.restated_question_text = ""  # Eric fills it in
        self.response.result_code = "OK"
        if self._num_results == 1:
            self.response.message = "%s result found" % self._num_results
        else:
            self.response.message = "%s results found" % self._num_results
Example #3
0
 def createResponse(self):
     #### Create the response object and fill it with attributes about the response
     response = Response()
     response.context = "http://translator.ncats.io"
     response.id = "http://rtx.ncats.io/api/v1/response/0000"
     response.type = "medical_translator_query_response"
     response.tool_version = "RTX 0.4"
     response.schema_version = "0.5"
     response.datetime = datetime.datetime.now().strftime(
         "%Y-%m-%d %H:%M:%S")
     response.result_code = "OK"
     response.message = "1 result found"
     return response
Example #4
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_response = Response()

                for reasoner_id in targets:
                    eprint("Looping with reasoner_id=" + reasoner_id)
                    query["options"] = "foo"
                    url = None
                    if reasoner_id == "RTX":
                        url = "https://rtx.ncats.io/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)
                        response_content = requests.post(
                            url,
                            headers={'accept': 'application/json'},
                            json=query)
                        status_code = response_content.status_code
                        response_dict = response_content.json()
                        response = Response.from_dict(response_dict)
                        if reasoner_id == "RTX":
                            final_response = response
                        if reasoner_id == "Robokop" or reasoner_id == "Indigo":
                            #if reasoner_id == "Robokop":
                            eprint("Merging in " + reasoner_id)
                            response = self.fix_response(
                                query, response, reasoner_id)
                            if response.result_list is not None:
                                final_response = self.merge_response2(
                                    final_response, response)

                return (final_response)
            return (None)
        return (None)
Example #5
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._result_list = []
        self._num_results = 0
        # Create the response object and fill it with attributes about the response
        self.response = Response()
        self.response.type = "medical_translator_query_result"
        self.response.tool_version = RTXConfiguration.version
        self.response.schema_version = "0.5"
        self.response.response_code = "OK"
        if self._num_results == 1:
            self.response.message = "%s result found" % self._num_results
        else:
            self.response.message = "%s results found" % self._num_results
Example #6
0
#### Create an RTX Feedback management object
rtxFeedback = RTXFeedback()

#### Purge and re-create the database if desired
#rtxFeedback.createDatabase()
#rtxFeedback.prepopulateDatabase()

#### Connect to the database
rtxFeedback.connect()

#### Fetch a cached response based on this query if there is one
cachedResponse = rtxFeedback.getCachedResponse(query)
#cachedResponse = None

#### If there was one, then return it
if (cachedResponse is not None):
    apiResponse = Response().from_dict(cachedResponse)

#### Otherwise, send the query to the web service (which creates an entry in the cache)
else:
    httpResponse = requests.post(url, json=query)
    assert (httpResponse.status_code == 200)
    apiResponse = Response.from_dict(httpResponse.json())
    rtxFeedback.addNewResponse(apiResponse, query)

#### Print out the result as JSON
dumpString = json.dumps(ast.literal_eval(repr(apiResponse)),
                        sort_keys=True,
                        indent=2)
print(dumpString[0:1000] + "\n...")
Example #7
0
    def query(self, query):

        #### If there is no known_query_type_id, then return an error
        if "known_query_type_id" not in query:
            response = Response()
            response.result_code = "No_known_query_type_id"
            response.message = "There was no known_query_type_id specified in the query"
            return (response)

        #### If there is no terms, then return an error
        if "terms" not in query:
            response = Response()
            response.result_code = "No_terms"
            response.message = "There was no terms element specified in the query"
            return (response)

        #### Extract the id and the terms from the incoming parameters
        id = query["known_query_type_id"]
        terms = query["terms"]

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

        #### If we can find a cached response for this query and this version of RTX, then return the cached response
        if (cachedResponse is not None):
            apiResponse = Response().from_dict(cachedResponse)
            rtxFeedback.disconnect()
            return apiResponse

        #### Still have special handling for Q0
        if id == 'Q0':
            # call out to QueryMeSH here to satify the query "What is XXXXXX?"
            meshQuery = QueryMeSH()
            response = meshQuery.queryTerm(terms["term"])
            if 'original_question' in query:
                response.original_question_text = query["original_question"]
                response.restated_question_text = query["restated_question"]
            id = response.id
            codeString = response.result_code
            self.logQuery(id, codeString, terms)
            rtxFeedback.addNewResponse(response, query)
            rtxFeedback.disconnect()
            return (response)

        #### Call out to OrangeBoard to answer the other types of queries
        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 response object
            try:
                #data = ast.literal_eval(reformattedText)
                data = json.loads(reformattedText)
                response = Response.from_dict(data)

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

            print(query)
            if 'original_question' in query:
                response.original_question_text = query["original_question"]
                response.restated_question_text = query["restated_question"]

            #### Log the result and return the Response object
            self.logQuery(response.id, response.result_code, terms)
            rtxFeedback.addNewResponse(response, query)
            rtxFeedback.disconnect()
            return (response)

        #### If the query type id is not triggered above, then return an error
        response = Response()
        response.result_code = "UnsupportedQueryTypeID"
        response.message = "The specified query id '" + id + "' is not supported at this time"
        rtxFeedback.disconnect()
        return (response)
Example #8
0
 def createResponse(self):
     #### Create the response object and fill it with attributes about the response
     response = Response()
     response.response_code = "OK"
     response.message = "1 result found"
     return response
Example #9
0
 def processQuery(cls,body):
     response = Response()
     # stupid stub here just to get started, since body JSON 
     # is not going to be the same as Response JSON
     return response.from_dict(body) 
Example #10
0
    def test1(self):

        #### Create the response object and fill it with attributes about the response
        response = Response()
        response.context = "http://translator.ncats.io"
        response.id = "http://rtx.ncats.io/api/v1/response/1234"
        response.type = "medical_translator_query_response"
        response.tool_version = "RTX 0.4"
        response.schema_version = "0.5"
        response.datetime = datetime.datetime.now().strftime(
            "%Y-%m-%d %H:%M:%S")
        response.original_question_text = "what proteins are affected by sickle cell anemia"
        response.restated_question_text = "Which proteins are affected by sickle cell anemia?"
        response.result_code = "OK"
        response.message = "1 result found"

        #### Create a disease node
        node1 = Node()
        node1.id = "http://omim.org/entry/603903"
        node1.type = "disease"
        node1.name = "sickle cell anemia"
        node1.accession = "OMIM:603903"
        node1.description = "A disease characterized by chronic hemolytic anemia..."

        #### Create a protein node
        node2 = Node()
        node2.id = "https://www.uniprot.org/uniprot/P00738"
        node2.type = "protein"
        node2.name = "Haptoglobin"
        node2.symbol = "HP"
        node2.accession = "UNIPROT:P00738"
        node2.description = "Haptoglobin captures, and combines with free plasma hemoglobin..."

        #### Create a node attribute
        node2attribute1 = NodeAttribute()
        node2attribute1.type = "comment"
        node2attribute1.name = "Complex_description"
        node2attribute1.value = "The Hemoglobin/haptoglobin complex is composed of a haptoglobin dimer bound to two hemoglobin alpha-beta dimers"
        node2.node_attributes = [node2attribute1]

        #### Create an edge between these 2 nodes
        edge1 = Edge()
        edge1.type = "is_caused_by_a_defect_in"
        edge1.source_id = node1.id
        edge1.target_id = node2.id
        edge1.confidence = 1.0

        #### Add an origin and property for the edge
        origin1 = Origin()
        origin1.id = "https://api.monarchinitiative.org/api/bioentity/disease/OMIM:603903/genes/"
        origin1.type = "Monarch_BioLink_API_Relationship"

        #### Add an attribute
        attribute1 = EdgeAttribute()
        attribute1.type = "PubMed_article"
        attribute1.name = "Orthopaedic Manifestations of Sickle Cell Disease"
        attribute1.value = None
        attribute1.url = "https://www.ncbi.nlm.nih.gov/pubmed/29309293"
        origin1.attribute_list = [attribute1]
        edge1.origin_list = [origin1]

        #### Create the first result (potential answer)
        result1 = Result()
        result1.id = "http://rtx.ncats.io/api/v1/response/1234/result/2345"
        result1.text = "A free text description of this result"
        result1.confidence = 0.932

        #### Create a ResultGraph object and put the list of nodes and edges into it
        result_graph = ResultGraph()
        result_graph.node_list = [node1, node2]
        result_graph.edge_list = [edge1]

        #### Put the ResultGraph into the first result (potential answer)
        result1.result_graph = result_graph

        #### Put the first result (potential answer) into the response
        result_list = [result1]
        response.result_list = result_list

        print(response)