예제 #1
0
def create_capabilitystatement(meta, canon, publisher, publisher_endpoint, xls):
    cs = CS.CapabilityStatement()
#    cs.id = meta.id
    cs.id = meta.title.lower()
    cs.url = f'{canon}CapabilityStatement/{meta.title.lower()}'
    cs.version = meta.version
    cs.name = f'{kebab_to_pascal(meta.id)}{cs.resource_type}'
#    cs.title = f'{titlecase(meta.id).replace("Us ", "US ")} {cs.resource_type}'
    cs.title = f'{meta.title} {cs.resource_type}'
    cs.status = 'active'

    cs.experimental = False
    cs.date = f_now  # as FHIRDate
    cs.publisher = publisher
    cs.contact = [CD.ContactDetail({"telecom": [publisher_endpoint]})]
    cs.description = meta.description
    cs.jurisdiction = [f_jurisdiction]
    cs.kind = 'requirements'
    cs.fhirVersion = meta.fhirVersion
    cs.acceptUnknown = 'both'
    cs.format = [
        "xml",
        "json"
    ]
    cs.patchFormat = [
        "application/json-patch+json",
    ]
    cs.implementationGuide = meta.ig.split(",") + get_igs(xls)

    return cs
def get_csname_map(file_names):
    csname_map = {}
    for file_name in file_names:
        with open(file_name, 'r') as file_h:
            cap_stmt = CS.CapabilityStatement(json.load(file_h))
            csname_map[cap_stmt.url] = cap_stmt.title
        file_h.close()
    
    return csname_map
def main():
    if (len(sys.argv) < 2):
        print(
            "Error: missing json file - correct usage is:\n\tpython3 R4CapStatement_NarrativeMaker.py [json file] {[Artifacts Folder]}")
        return

    xls = sys.argv[1]

    in_json_file = sys.argv[1]
    artifacts_folder = ""
    
    if len(sys.argv) > 2:
        artifacts_folder = sys.argv[2]
   
    print('....Generating CapabilityStatement Narrative.....')



    with open(in_json_file, 'r') as h:
        pjs = json.load(h)
    capStatement = CS.CapabilityStatement(pjs)
    #print(dumps(capStatement.as_json(), indent=3))    # %% [markdown]

    # CapabilityStatement loaded

    in_path = ''
    in_file = 'R4capabilitystatement-server.j2'

    env = Environment(
        loader=FileSystemLoader(searchpath=in_path),
        autoescape=select_autoescape(['html', 'xml', 'xhtml', 'j2', 'md'])
    )

    env.filters['markdown'] = markdown


    template = env.get_template(in_file)

    pname_map = {}
    igname_map = {}
    csname_map = {}
    # Load name maps
    if artifacts_folder != "":
        print('....Retrieving Artifact Names .....')
        artifacts_folder = os.path.abspath(artifacts_folder)
        struct_def_files = glob.glob(artifacts_folder + "/StructureDefinition-*.json")
        imp_guide_files = glob.glob(artifacts_folder + "/ImplementationGuide-*.json")
        cap_stmt_files = glob.glob(artifacts_folder + "/CapabilityStatement-*.json")
        
        pname_map = get_pname_map(struct_def_files)
        igname_map = get_igname_map(imp_guide_files)
        csname_map = get_csname_map(cap_stmt_files)

    # Check access to hl7.org/fhir
    r = get (fhir_base_url)
    if r.status_code == 200:
        print('....Retrieving Online Artifact Names .....')
        # Loop through all references in the CapabilityStatement and attempt to retried the artifacts to load the names into the map
        

        # Instantiates
        if capStatement.instantiates:
            for url in capStatement.instantiates:
                if url not in csname_map:
                    csname_map[url] = get_url_title(url, "instantiates CapabilityStatement")

        # Imports
        if capStatement.imports:
            for url in capStatement.imports:
                if url not in csname_map:
                    csname_map[url] = get_url_title(url, "imports CapabilityStatement")

        # Implementation Guides
        if capStatement.implementationGuide:
            for url in capStatement.implementationGuide:
                if url not in igname_map:
                    igname_map[url] = get_url_title(url, "ImplementationGuide")

        # Iterate through rest resources
        if capStatement.rest:
            for rest in capStatement.rest:
                if rest.resource:
                    for resource in rest.resource:
                        if resource.profile:
                            url = resource.profile
                            if url not in pname_map:
                                pname_map[url] = get_url_title(url, resource.type + " profile")
                                
                        if resource.supportedProfile:
                            for url in resource.supportedProfile:
                                if url not in pname_map:
                                    pname_map[url] = get_url_title(url, resource.type + " supported profile")

    else:
        print("Unable to connect to " + fhir_base_url + ". Will not attempt to load online artifacts to retrieve artifact names.")




    rendered = template.render(cs=capStatement, path_map='', pname_map=pname_map, purl_map='', sp_map='', 
                            csname_map=csname_map, csurl_map='', sp_url_map='', igname_map=igname_map, igurl_map='')
    
    #template.render(cs=cs, path_map=path_map, pname_map=pname_map, purl_map=purl_map, sp_map=sp_map, 
    #                       csname_map=csname_map, csurl_map=csurl_map, igname_map=igname_map, igurl_map=igurl_map)

    tempPath = Path.cwd() / "test.html"
    tempPath.write_text(rendered)
    #print(rendered)
    

    parser = etree.XMLParser(remove_blank_text=True)
    root = etree.fromstring(rendered, parser=parser)

    div = (etree.tostring(root[1][0], encoding='unicode', method='html'))

    print("\n####################################################\n")
    #print(etree.tostring(root[1][0], encoding='unicode', method='html'))
    print("\n####################################################\n")
    narr = N.Narrative()
    narr.status = 'generated'


    #div = re.sub('https://paciowg.github.io/advance-directives-ig/StructureDefinition-', 'SSSSSSSSSSSSSSSSS', div)
    # replace all of the supported profile urls in link text with just the profile name from inside the cononical url
    #######div = re.sub('">\(https?://.*/StructureDefinition-(.*)\.html\)</a>', '">\\1</a>', div)
    #div = re.sub('">\(https://paciowg.github.io/advance-directives-ig/StructureDefinition-PADI-(PersonalGoal.html)</a>', '\\1', div)
    # For some reason <br /> is being replaced with <br></br>, which is wrong. Convert it back.
    #div = div.replace("<br></br>", "<br />")
    #print(div)
    narr.div = div

    #print(dumps(narr.div, indent=3))    # %% [markdown]
    capStatement.text = narr
    outfile = 'Narrative-' + in_json_file
    path = Path.cwd() / outfile
    tempOut = dumps(capStatement.as_json(), indent=4)
    tempOut = tempOut.replace("<sup>+</sup>", "<sup>&#8224;</sup>")
    #tempOut = tempOut.replace(“<sup>t</sup>”, “<sup>&#8224;</sup>”)
    #print(tempOut)
    path.write_text(tempOut)


    print('.............validating..............')
    r = validate(capStatement)
    if (r.status_code != 200):
        print("Error: Unable to validate - status code {}".format(r.status_code))
    path = Path.cwd() / 'validation.html'
    path.write_text(
        f'<h1>Validation output</h1><h3>Status Code = {r.status_code}</h3> {r.json()["text"]["div"]}')
    print(f"HTML webpage of validation saved to:\n\t {path}")

    # get from package (json) file in local .fhir directory
    # save to file
    print('...........done............')