Beispiel #1
0
async def preset_cat_filters(
        *,
        db: Session = Depends(get_db),
        case_id: int,
        category: str,
        # txt: Optional[str],
        # start: int = 0,
        # limit: int = 25,
        current_user: DBUser = Depends(get_current_active_user),
        response: Response):
    confirm_case_id_with_biz_id_helper_func(db, case_id, current_user)

    f_pivot = "category,text,confirmed_visit_date,id"

    params = {
        "q": "*:*",
        "fq":
        f"category:\"{category}\" AND business_id:{current_user.business_id} AND case_id:{case_id}",
        "facet.pivot": f_pivot,
        "facet": "true",
        "rows": "0",
        "facet.pivot.mincount": "1",
        "facet.limit": "-1"
    }

    local_session = await get_session()
    resp = await local_session.get(url, params=urllib.parse.urlencode(params))
    res = json.loads(await resp.text())

    if "error" in res:
        logger.info(
            f"Exception occurred for business_id: {current_user.business_id} while fetching file_id: {case_id} "
            f"with below exception. \n {res['error']['trace']}")
        raise HTTPException(
            status_code=res["error"]["code"],
            detail="Invalid details passed.",
        )

    d: PresetCatFiltersSearchResults = PresetCatFiltersSearchResults(
        field=None, value=None, count=None, pivot=None)
    if len(res["facet_counts"]["facet_pivot"][f_pivot]) > 0:
        d = res["facet_counts"]["facet_pivot"][f_pivot][0]
        # response.headers["cache-control"] = f"private, max-age={int(86400)}"
    return d
Beispiel #2
0
def show_me_pdf_search(*,
                       db: Session = Depends(get_db),
                       case_id: int,
                       current_user: DBUser = Depends(get_current_active_user),
                       response: Response):
    # confirm_case_id_with_biz_id = get_by_case_id(db, id=case_id, user_details=current_user)
    #
    # if not confirm_case_id_with_biz_id:
    #     logger.info(f"Invalid case_id of value {case_id} found for business_id {current_user.business_id}")
    #     raise HTTPException(
    #         status_code=400,
    #         detail="Invalid details passed.",
    #     )

    confirm_case_id_with_biz_id_helper_func(db, case_id, current_user)
    results = show_me_pdf_from_db(db, case_id, user_details=current_user)

    # response.headers["cache-control"] = f"private, max-age={int(86400)}"

    return results
Beispiel #3
0
async def get_pdf_cords(
        *,
        db: Session = Depends(get_db),
        case_id: int,
        m_id: int,
        current_user: DBUser = Depends(get_current_active_user),
        response: Response):
    confirm_case_id_with_biz_id_helper_func(db, case_id, current_user)

    params = {
        "q": "*:*",
        "fq":
        f"id:{m_id} AND business_id:{current_user.business_id} AND case_id:{case_id}",
        "fl": "full_text_bbox, page_number"
    }

    local_session = await get_session()
    resp = await local_session.get(url, params=urllib.parse.urlencode(params))
    res = json.loads(await resp.text())

    if "error" in res:
        logger.info(
            f"Exception occurred for business_id: {current_user.business_id} while fetching file_id: {case_id} "
            f"with below exception. \n {res['error']['trace']}")
        raise HTTPException(
            status_code=res["error"]["code"],
            detail="Invalid details passed.",
        )
    obj_to_return = {}
    if len(res["response"]["docs"]) > 0:
        obj_to_return = res["response"]["docs"][0]
    else:
        obj_to_return["full_text_bbox"] = ""
        obj_to_return["page_number"] = 0

    # Cache-Control:public, max-age=31536000
    # response.headers["cache-control"] = f"private, max-age={int(86400)}"
    return obj_to_return
Beispiel #4
0
async def faceted_search(
        *,
        db: Session = Depends(get_db),
        case_id: int,
        current_user: DBUser = Depends(get_current_active_user),
        response: Response):
    # confirm_case_id_with_biz_id = get_by_case_id(db, id=case_id, user_details=current_user)
    #
    # if not confirm_case_id_with_biz_id:
    #     logger.info(f"Invalid case_id of value {case_id} found for business_id {current_user.business_id}")
    #     raise HTTPException(
    #         status_code=400,
    #         detail="Invalid details passed.",
    #     )

    confirm_case_id_with_biz_id_helper_func(db, case_id, current_user)

    params = {
        "q": "%2A:%2A",
        "fq":
        f"business_id:{current_user.business_id}%20AND%20case_id:{case_id}",
        # %20AND%20"
        # f"concept_attributes:%28t037%20OR%20t047%20OR%20t184%20OR%20t190%20OR%20t017%29",
        "facet": "true",
        # "facet.field": "tui",
        "facet.field": "category",
        "rows": "0",
        "facet.mincount": "1"
    }

    local_session = await get_session()
    resp = await local_session.get(url, params=params)
    res = json.loads(await resp.text())

    if "error" in res:
        logger.info(
            f"Exception occurred for business_id: {current_user.business_id} while fetching file_id: {case_id} "
            f"with below exception. \n {res['error']['trace']}")
        raise HTTPException(
            status_code=res["error"]["code"],
            detail="Invalid details passed.",
        )

    result = res["facet_counts"]["facet_fields"]["category"]
    return_list = []
    for i in range(0, len(result), 2):
        # if we were faceting by TUI or CUI then we would need line
        # obj = {str(all_categories[result[i]]): result[i + 1]}

        # but we are faceting by Category for easy viewing for end user

        if str(result[i]) in [
                'Sign Or Symptom', 'Medication', 'Body Site',
                'Medical Procedure', 'Disease Disorder'
        ]:
            obj = {str(result[i]): result[i + 1]}

            return_list.append(obj)

    # response.headers["cache-control"] = f"private, max-age={int(86400)}"
    return return_list
Beispiel #5
0
def return_all(*,
               db: Session = Depends(get_db),
               case_id: int,
               search_term: Optional[str] = None,
               file_id: Optional[int] = None,
               file_state_id: Optional[int] = None,
               current_user: DBUser = Depends(get_current_active_user)):
    # Variables:
    index = 0
    skip_first_VD_results = False

    # confirm_case_id_with_biz_id = get_by_case_id(db, id=case_id, user_details=current_user)
    confirm_case_id_with_biz_id_helper_func(db, case_id, current_user)

    # ---- All Visit Dates by individual files
    cvd = get_all_confirmed_visit_dates(db,
                                        case_id,
                                        search_term=search_term,
                                        user_details=current_user)
    results = []
    for i, c in enumerate(cvd):
        parsed_date = c["confirmed_visit_date"]
        if parsed_date:
            parsed_date = parsed_date.replace("o", "0").replace("O", "0")
            try:
                parsed_date = parse(parsed_date)
            except Exception as e:
                traceback.print_exc(file=sys.stdout)

        visit_date_obj = VisitDates(
            string_to_date=parsed_date,
            parsed_date_to_string=f"{parsed_date.date()}",
            confirmed_visit_date=c["confirmed_visit_date"],
            file_id=c["file_id"],
            file_state_id=c["id"],
            last_modified_instant=c["last_modified_instant"],
            name=c["name"])

        # this is what the search came in for....do the search here for the specific file id
        # for EVERYTHING search, it happens at the bottom
        if file_id == c["file_id"] and file_state_id == c["id"]:
            resp = get_all_terms(db,
                                 visit_date=visit_date_obj,
                                 case_id=case_id,
                                 search_term=search_term,
                                 user_details=current_user)
            visit_date_obj.all_terms = resp
            skip_first_VD_results = True

        results.append(visit_date_obj)

    # sorting so the visit date becomes a timeline
    results = sorted(results, key=lambda x: x.string_to_date)

    # ---- All Terms for the very first visit date
    if len(results) > 0 and not skip_first_VD_results:
        resp = get_all_terms(db,
                             visit_date=results[index],
                             case_id=case_id,
                             search_term=search_term,
                             user_details=current_user)
        results[index].all_terms = resp

    return results
Beispiel #6
0
def download_file(
    *,
    db: Session = Depends(get_db),
    case_id: int,
    current_user: DBUser = Depends(get_current_active_user),
    response: Response,
    file_id: Optional[int] = None,
    file_state_id: Optional[int] = None,
    fd: Optional[str] = None,
):
    """

    :param response: adds expiration from what we got back from S3's STS
    :param db:
    :param file_id:
    :param file_state_id:
    :param case_id:
    :param fd: This is S3 File destination
    :param current_user:
    :return:
    """
    confirm_case_id_with_biz_id_helper_func(db, case_id, current_user)

    s3_file: str = None

    if file_id:
        res = get_bucket_location_by_file_and_file_state_id(
            db,
            file_id=file_id,
            file_state_id=file_state_id,
            user_details=current_user)

        s3_file = res.s3_file_dest

    if fd:
        # browser sent us a full S3 file destination. Let's verify that its actually belongs to this user/business
        fd1 = fd.split("/")
        provided_business_id = int(fd1[0])

        # if provided biz id is not the same as user's business id then reject it
        if provided_business_id != current_user.business_id:
            raise HTTPException(
                status_code=400,
                detail="Invalid details passed.",
            )
        provided_case_name = fd1[1]
        provided_split_file_id = str(fd1[2]).split("_")[0]

        res = crud.file.get_filestate_files(db,
                                            ids=[provided_split_file_id],
                                            user_details=current_user)

        for r in res:
            if r.new_file_name == fd:
                s3_file = r.new_file_name
                break

    if s3_file:
        cred = prepare_download_file(db, s3_file, user_details=current_user)

        # set expiration on client side to 2 minutes less than S3's credentials expiration date
        response.headers["cache-control"] = f"private, max-age={int(80)}"

        return DownloadFileS3Dest(response=cred,
                                  loc=s3_file,
                                  bucket=AWS_UPLOAD_BUCKET)
    else:
        return DownloadFileS3Dest(response={}, loc="", bucket="")