Files
doczyai-pipelines/archive/streamlit/interface_1.py
T

337 lines
12 KiB
Python
Raw Normal View History

2024-02-28 18:05:03 +05:30
import streamlit as st
2024-06-13 13:34:25 -05:00
import security
2024-02-28 18:05:03 +05:30
from streamlit_extras.add_vertical_space import add_vertical_space
import os
import streamlit as st
import pandas as pd
from io import StringIO
from datetime import datetime
2024-03-07 18:48:53 +05:30
import boto3
2024-03-08 17:36:36 +05:30
import util
2024-03-18 13:22:38 +05:30
import requests
import time
2024-04-10 12:10:14 +05:30
from sf_conn import get_client_names, get_secret, save_to_sf
from constants import USER_LIST
from util import logger
2024-03-18 13:22:38 +05:30
(REDIRECT_URI, create_batch_url, doczy_pipeline) = util.load_page_details(1)
2024-02-28 18:05:03 +05:30
2024-05-06 19:28:00 -05:00
user_list = USER_LIST
2024-09-30 12:21:29 +01:00
st.set_page_config(layout="wide")
2024-06-18 20:56:09 -05:00
# Sidebar contents
with st.sidebar:
st.title("Doczy.AI ™")
st.markdown(
"""
## About
This app extracts data from contracts
2024-02-28 18:05:03 +05:30
2024-06-18 20:56:09 -05:00
"""
)
add_vertical_space(15)
# st.write("Doczy")
2024-02-28 18:05:03 +05:30
2024-06-13 13:40:50 -05:00
# AARETE LOGO
2024-09-30 12:21:29 +01:00
x, y, z = st.columns([15, 2, 15])
2024-06-13 13:40:50 -05:00
with y:
2024-09-30 12:21:29 +01:00
st.image("aaretelogo.png")
2024-06-13 13:40:50 -05:00
2024-09-30 12:21:29 +01:00
hide_img_fs = """
2024-06-13 13:40:50 -05:00
<style>
button[title="View fullscreen"]{
visibility: hidden;}
</style>
2024-09-30 12:21:29 +01:00
"""
2024-06-13 13:40:50 -05:00
st.markdown(hide_img_fs, unsafe_allow_html=True)
2024-02-28 18:05:03 +05:30
2024-09-30 12:21:29 +01:00
_, c1 = st.columns([5, 1])
2024-03-13 17:23:20 +05:30
try:
2024-04-02 17:17:21 +05:30
util.setup_page(REDIRECT_URI)
2024-03-13 17:23:20 +05:30
except:
2024-04-10 20:43:35 +05:30
st.write("SSO Failed")
2024-09-30 12:21:29 +01:00
st.session_state["user_info"] = {
"mail": "maamseek@aarete.com",
"displayName": "Mayank Aamseek",
} # RECOMMENDATION - Remove after dev phase
2024-04-05 12:15:54 +05:30
try:
c1.write(f"User: **{st.session_state.user_info['displayName']}**")
2024-09-30 12:21:29 +01:00
user_mail = st.session_state.user_info["mail"]
2024-04-05 12:15:54 +05:30
except KeyError as e:
2024-09-30 12:21:29 +01:00
# Do we add a link to get to the login page here?
2024-04-05 12:15:54 +05:30
st.write("Session Expired.")
2024-06-13 13:34:25 -05:00
# st.write("Please sign-in to use this app.")
auth_url = security.get_auth_url(REDIRECT_URI)
2024-09-30 12:21:29 +01:00
st.markdown(
f"<a href='{auth_url}' target='_self'>Sign In</a>", unsafe_allow_html=True
)
st.stop()
2024-03-13 17:23:20 +05:30
2024-02-28 18:05:03 +05:30
2024-09-30 12:21:29 +01:00
s3_client = boto3.client(
"s3",
2024-05-28 17:36:41 -05:00
region_name="us-east-2",
)
# # to be replaced with snowflake data
# client_list = ['doczy-ai-client-1', 'Delaware First Health, Inc.', 'Community Health Choice, Inc','CareSource Network Partners LLC',
# 'HealthNet of Cali', 'Oklahoma Complete Health, Inc', 'HealthFirst', 'Molina Healthcare of TX', 'AvMed', 'Arizona Care1st',
# 'WellCare New Jersey']
client_list, s3_paths = get_client_names()
client_s3_paths = dict(zip(client_list, s3_paths))
client_row = st.columns([0.1, 0.8])
with client_row[0]:
st.write("**Client Name**")
with client_row[1]:
2024-09-30 12:21:29 +01:00
client = st.selectbox(
"Client Name", (client_list), label_visibility="collapsed", index=None
)
2024-05-28 17:36:41 -05:00
2024-06-20 17:28:03 -05:00
if client:
client_bucket = client_s3_paths.get(client)
# to be deleted when buckets for different clients are ready; below line is added only for testing the corresponding DAG
# client_bucket = 'doczyai-use2-d-cn1-s3-textract-processing-001'
2024-09-30 12:21:29 +01:00
batch_objects = s3_client.list_objects_v2(
Bucket=client_bucket, Prefix="contracts-landing-zone/", Delimiter="/"
)
2024-06-20 17:28:03 -05:00
batch_list = []
2024-09-30 12:21:29 +01:00
for prefix in batch_objects["CommonPrefixes"]:
batch_name = prefix["Prefix"][:-1].split("/")[-1]
batch_objects2 = s3_client.list_objects_v2(
Bucket=client_bucket,
Prefix="contracts-landing-zone/" + batch_name + "/",
Delimiter="/",
)
if "Contents" in batch_objects2 and len(batch_objects2["Contents"]) > 0:
batch_list.append(prefix["Prefix"][:-1].split("/")[-1])
2024-06-20 17:28:03 -05:00
# Hardcoded batch_list for testing purposes
2024-09-30 12:21:29 +01:00
# batch_list = ['batch_020524103737', 'batch_090524131433', 'batch_090524131607', 'batch_100524123000', 'batch_130524064322',
2024-06-20 17:28:03 -05:00
# 'batch_160524071331', 'batch_200524213550', 'batch_250424112237', 'batch_280524120530', 'batch_280524121721', 'batch_280524144222',
# 'batch_290524123926', 'batch_290524164044', 'batch_310524102029', 'batch_310524124050', 'batch_310524162346', 'batch_310524162631']
2024-09-30 12:21:29 +01:00
# Select Box for Applying Different Sort for the Batch List
2024-06-20 17:28:03 -05:00
2024-07-01 10:03:11 -05:00
# if 'sorted_list' not in st.session_state:
# st.session_state.sorted_list = batch_list
2024-06-20 17:28:03 -05:00
2024-07-01 10:03:11 -05:00
# def sort_list(ex_list, sort_by, order):
# if sort_by == 'Alphabetical':
# ex_list = sorted(ex_list, reverse=(order == 'Descending'))
# elif sort_by == 'Create Date':
# ex_list = ex_list if order == 'Ascending' else list(reversed(ex_list))
2024-06-20 17:28:03 -05:00
2024-07-01 10:03:11 -05:00
# return ex_list
2024-06-20 17:28:03 -05:00
2024-07-01 10:03:11 -05:00
# col1, col2, col3, col4 = st.columns([0.5, 0.5, 0.5, 0.5])
2024-06-20 17:28:03 -05:00
2024-09-30 12:21:29 +01:00
# with col1:
2024-07-01 10:03:11 -05:00
# sort_by = st.radio("**Sort Batch_IDs**", ('Alphabetical', 'Create Date'))
# with col2:
# order = st.radio('', ('Ascending','Descending'))
2024-09-30 12:21:29 +01:00
# with col3:
2024-07-01 10:03:11 -05:00
# add_vertical_space(2)
# if st.button('Apply'):
# st.session_state.sorted_list = sort_list(batch_list, sort_by, order)
2024-06-20 17:28:03 -05:00
path_row = st.columns([0.1, 0.8])
with path_row[0]:
st.write("**Batch ID**")
with path_row[1]:
2024-09-30 12:21:29 +01:00
batch_id = st.selectbox(
"**Batch ID**",
reversed(batch_list),
label_visibility="collapsed",
index=None,
)
2024-06-20 17:28:03 -05:00
if not batch_id:
batch_id = "None"
checks = st.columns([0.1, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12])
with checks[0]:
st.write("**Group No.**")
with checks[1]:
2024-09-30 12:21:29 +01:00
a = st.checkbox("Unique Key", key=str(1), args="Unique")
2024-06-20 17:28:03 -05:00
with checks[2]:
2024-09-30 12:21:29 +01:00
b = st.checkbox("Pricing Before Carveouts", key=str(2))
2024-06-20 17:28:03 -05:00
with checks[3]:
2024-09-30 12:21:29 +01:00
c = st.checkbox("Contract Related", key=str(3))
2024-06-20 17:28:03 -05:00
with checks[4]:
2024-09-30 12:21:29 +01:00
d = st.checkbox("Provider", key=str(4))
2024-06-20 17:28:03 -05:00
with checks[5]:
2024-09-30 12:21:29 +01:00
e = st.checkbox("Timeline", key=str(5))
2024-06-20 17:28:03 -05:00
with checks[6]:
2024-09-30 12:21:29 +01:00
f = st.checkbox("Carveout Indicator", key=str(6))
2024-06-20 17:28:03 -05:00
with checks[7]:
2024-09-30 12:21:29 +01:00
g = st.checkbox("Carveout Methodology", key=str(7))
2024-06-20 17:28:03 -05:00
add_vertical_space(1)
2024-09-30 12:21:29 +01:00
df = pd.DataFrame(
columns=[
"Contract Name",
"Unique Key",
"Pricing Before Carveouts",
"Contract Related",
"Provider",
"Timeline",
"Carveout Indicator",
"Carveout Methodology",
]
)
2024-06-20 17:28:03 -05:00
file_list = []
2024-09-30 12:21:29 +01:00
file_objects = s3_client.list_objects_v2(
Bucket=client_bucket,
Prefix="contracts-landing-zone/" + batch_id + "/",
Delimiter="/",
)
2024-06-20 17:28:03 -05:00
# Hardcoded file_list for testing purposes
2024-09-30 12:21:29 +01:00
# file_list = ['Boilerplate_TX Amendment Mission Health Network effective_040114 MU.pdf', 'Custom_TX - MP AMENDMENT - MISSION HEALTH NETWORK - MU.pdf',
2024-06-20 17:28:03 -05:00
# 'Delaware First Health_First State Homecare Agency_212260_7 MU.pdf', 'Molina Healthcare of Texas, Inc. Amendment 4 - HIX ACA__EFF 01012016_MU.pdf']
if st.button("Read the contracts from Path"):
2024-09-30 12:21:29 +01:00
for obj in file_objects.get("Contents", []):
if not obj["Key"].endswith("/"):
file_list.append(obj["Key"].split("/")[-1])
df["Contract Name"] = file_list
2024-06-20 17:28:03 -05:00
# df['Request ID'] = range(len(file_list))
# df['Contract ID'] = file_list
2024-09-30 12:21:29 +01:00
df["Unique Key"] = a
df["Pricing Before Carveouts"] = b
df["Contract Related"] = c
df["Provider"] = d
df["Timeline"] = e
df["Carveout Indicator"] = f
df["Carveout Methodology"] = g
2024-06-20 17:28:03 -05:00
dir_path = os.path.dirname(os.path.realpath(__file__))
2024-09-30 12:21:29 +01:00
print(f"DEBUGGING: PWD= {dir_path}")
df.to_csv("temp1.csv", index=False)
2024-06-20 17:28:03 -05:00
add_vertical_space(1)
2024-09-30 12:21:29 +01:00
df2 = pd.read_csv("temp1.csv")
2024-06-20 17:28:03 -05:00
edited_df = st.data_editor(df2)
2024-09-30 12:21:29 +01:00
edited_df["REQUEST_USER"] = user_mail
edited_df["LATEST_FLAG BOOLEAN"] = True
edited_df["PIPELINE_KICKOFF_DATETIME"] = datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
)
edited_df["REQUEST_DATETIME"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
2024-06-20 17:28:03 -05:00
2024-09-30 12:21:29 +01:00
@st.cache_data
2024-06-20 17:28:03 -05:00
def convert_df(df):
2024-09-30 12:21:29 +01:00
return df.to_csv(index=False).encode("utf-8")
2024-06-20 17:28:03 -05:00
csv = convert_df(edited_df)
# edited_df = edited_df.reset_index() # make sure indexes pair with number of rows
# additional_info = pd.DataFrame(columns=['REQUEST_ID','T_DRIVE_PATH','CLIENT_NAME'
# , 'GROUP_NAME', 'REQUEST_USERNAME', 'REQUEST_DATETIME'])
2024-09-30 12:21:29 +01:00
additional_info = pd.DataFrame(
columns=["CLIENT_NAME", "BATCH_ID", "REQUEST_USERNAME", "REQUEST_DATETIME"]
)
additional_info.loc[0] = [
client,
batch_id,
st.session_state.user_info["mail"],
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
]
2024-06-20 17:28:03 -05:00
st.write(additional_info)
st.session_state.contract_count = 0
contract_list = []
for index, row in edited_df.iterrows():
allow_run_for_contract = False
group_list = []
2024-09-30 12:21:29 +01:00
if row["Unique Key"]:
group_list.append("A")
2024-06-20 17:28:03 -05:00
allow_run_for_contract = True
2024-09-30 12:21:29 +01:00
if row["Pricing Before Carveouts"]:
group_list.append("B")
2024-06-20 17:28:03 -05:00
allow_run_for_contract = True
2024-09-30 12:21:29 +01:00
if row["Contract Related"]:
group_list.append("C")
2024-06-20 17:28:03 -05:00
allow_run_for_contract = True
2024-09-30 12:21:29 +01:00
if row["Provider"]:
group_list.append("D")
2024-06-20 17:28:03 -05:00
allow_run_for_contract = True
2024-09-30 12:21:29 +01:00
if row["Timeline"]:
group_list.append("E")
2024-06-20 17:28:03 -05:00
allow_run_for_contract = True
2024-09-30 12:21:29 +01:00
if row["Carveout Indicator"]:
group_list.append("F")
2024-06-20 17:28:03 -05:00
allow_run_for_contract = True
2024-09-30 12:21:29 +01:00
if row["Carveout Methodology"]:
group_list.append("G")
2024-06-20 17:28:03 -05:00
allow_run_for_contract = True
2024-09-30 12:21:29 +01:00
if allow_run_for_contract:
st.session_state.contract_count += 1
2024-06-20 17:28:03 -05:00
entry_dict = {
2024-09-30 12:21:29 +01:00
"contract_name": row["Contract Name"],
2024-06-20 17:28:03 -05:00
"groups": group_list,
2024-09-30 12:21:29 +01:00
"contract_source_path": "contracts-landing-zone/"
+ batch_id
+ "/"
+ row["Contract Name"],
2024-06-20 17:28:03 -05:00
}
contract_list.append(entry_dict)
myobj = {
"s3_bucket": client_bucket,
"batch_id": batch_id,
"client_name": client,
"username": user_mail,
2024-09-30 12:21:29 +01:00
"contract_list": contract_list,
2024-05-28 17:36:41 -05:00
}
2024-06-20 17:28:03 -05:00
buttons = st.columns([0.8, 0.2])
with buttons[0]:
2024-09-30 12:21:29 +01:00
st.download_button(
"Download Table", csv, "file.csv", "text/csv", key="download-csv"
)
2024-06-20 17:28:03 -05:00
with buttons[1]:
if st.button("Run Doczy.AI Pipeline"):
if not st.session_state.contract_count == len(edited_df):
st.error("Select at least one Group No. for every Contract")
else:
2024-09-30 12:21:29 +01:00
with st.spinner("Running..."):
2024-06-20 17:28:03 -05:00
# csv_buf = StringIO()
# additional_info.to_csv(csv_buf, header=True, index=False)
# csv_buf.seek(0)
# s3_client.put_object(Bucket='doczy-dev-infra-raw-data-ingestion', Body=csv_buf.getvalue(), Key='training_interface/request_submission.csv')
# csv_buf = StringIO()
# edited_df.to_csv(csv_buf, header=True, index=False)
# csv_buf.seek(0)
2024-09-30 12:21:29 +01:00
# s3_client.put_object(Bucket='doczy-dev-infra-raw-data-ingestion', Body=csv_buf.getvalue(), Key='training_interface/contract_config.csv')
2024-06-20 17:28:03 -05:00
# try:
# save_to_sf('load_request_and_contract_submissions', request_submission_file_name = "request_submission.csv", contract_config_file_name = "contract_config.csv")
# except Exception as e:
# st.write(e)
2024-09-30 12:21:29 +01:00
response = requests.post(doczy_pipeline, json=myobj)
2024-06-20 17:28:03 -05:00
if response.status_code >= 200 and response.status_code < 300:
success_message = """
<div style="text-align: center; font-size: 24px; color: green;">
Pipeline Success
</div>
"""
st.markdown(success_message, unsafe_allow_html=True)
2024-06-20 17:28:03 -05:00
# st.write(myobj)
else:
failure_message = """
<div style="text-align: center; font-size: 24px; color: red;">
Pipeline Failed
</div>
"""
st.markdown(failure_message, unsafe_allow_html=True)
2024-06-20 17:28:03 -05:00
# st.write(response.text)