Files
doczyai-pipelines/streamlit_multipage/Interface_1.py
T
2024-09-27 15:40:25 +01:00

213 lines
6.9 KiB
Python

import os
import streamlit as st
from streamlit_extras.add_vertical_space import add_vertical_space
import pandas as pd
from datetime import datetime
import time
import constants
if 'uploading' not in st.session_state:
st.session_state.uploading = False
if 'upload_key' not in st.session_state:
st.session_state.upload_key = 0
if 'file_list' not in st.session_state:
st.session_state.file_list = []
if 'show_batchID' not in st.session_state:
st.session_state.show_batchID = False
if 'numFiles' not in st.session_state:
st.session_state.numFiles = 0
st.set_page_config(layout = "wide")
# # # Sidebar contents
with st.sidebar:
st.title("Doczy.AI ™")
st.markdown(
"""
## About
This app extracts data from contracts
"""
)
add_vertical_space(15)
# st.write("Doczy")
# AARETE LOGO
x,y,z = st.columns([15,2,15])
with y:
st.image('aaretelogo.png')
hide_img_fs = '''
<style>
button[title="View fullscreen"]{
visibility: hidden;}
</style>
'''
st.markdown(hide_img_fs, unsafe_allow_html=True)
_,c1= st.columns([5,1])
st.session_state['user_info'] = {'mail': 'piragavarapu@aarete.com', 'displayName': 'Priya Iragavarapu'}
try:
c1.write(f"User: **{st.session_state.user_info['displayName']}**")
user_mail = st.session_state.user_info['mail']
except KeyError as e:
st.write("Session Expired.")
st.stop()
client_row = st.columns([0.1, 0.8])
with client_row[0]:
st.write("**Client Name**")
with client_row[1]:
client = st.selectbox('Client Name',(constants.client_list), label_visibility = "collapsed", index = None)
file_row = st.columns([0.1, 0.8])
with file_row[0]:
st.write("**Upload Files**")
with file_row[1]:
file_list = st.file_uploader("Upload", type=['docx','tiff','pdf'], accept_multiple_files=True, label_visibility = "collapsed", help="Only PDF, TIFF and DOCX file formats are supported.", disabled=st.session_state.uploading, key = st.session_state.upload_key)
add_vertical_space(2)
df = pd.DataFrame(columns=['Contract Name'])
df['Contract Name'] = file_list
file_names = []
buttons = st.columns([0.4, 0.4, 0.2])
def set_uploading_state():
if not client == None and not len(file_list) == 0:
st.session_state.file_list = file_list
st.session_state.upload_key += 1
st.session_state.uploading = True
def save_uploaded_files(uploaded_files, save_path):
try:
if not os.path.exists(save_path):
os.makedirs(save_path)
for uploaded_file in uploaded_files:
with open(os.path.join(save_path, uploaded_file.name), 'wb') as f:
f.write(uploaded_file.getbuffer())
return True
except Exception as e:
st.error(f"Error saving files: {e}")
return False
with buttons[1]:
if st.button("Create Batch", on_click=set_uploading_state):
file_list = st.session_state.file_list
if client == None:
st.error("No Client Name Selected.")
elif len(file_list) == 0:
st.error("No Files Selected.")
else:
with st.spinner('Running...'):
time.sleep(2)
if (save_uploaded_files(file_list, os.path.join(os.getcwd(), f'temp/{client}'))):
st.session_state.numFiles = len(file_list)
st.session_state.uploading = False
st.session_state.show_batchID = True
st.rerun()
else:
st.error("Failed to upload the files.")
if st.session_state.show_batchID:
st.write(f"{st.session_state.numFiles} files uploaded successfully!")
# st.session_state.file_list = []
add_vertical_space(1)
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]:
a = st.checkbox('Unique Key')
with checks[2]:
b = st.checkbox('Pricing Before Carveouts')
with checks[3]:
c = st.checkbox('Contract Related')
with checks[4]:
d = st.checkbox('Provider')
with checks[5]:
e = st.checkbox('Timeline')
with checks[6]:
f = st.checkbox('Carveout Indicator')
with checks[7]:
g = st.checkbox('Carveout Methodology')
add_vertical_space(1)
df = pd.DataFrame(columns=['Contract Name', 'Unique Key','Pricing Before Carveouts'
, 'Contract Related', 'Provider', 'Timeline', 'Carveout Indicator', 'Carveout Methodology'])
df['Contract Name'] = [file.name for file in st.session_state.file_list]
# df['Contract Name'] = st.session_state.file_list
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
dir_path = os.path.dirname(os.path.realpath(__file__))
print(f'DEBUGGING: PWD= {dir_path}')
df.to_csv('temp1.csv', index=False)
add_vertical_space(1)
df2 = pd.read_csv('temp1.csv')
edited_df = st.data_editor(df2)
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")
@st.cache_data
def convert_df(df):
return df.to_csv(index=False).encode('utf-8')
csv = convert_df(edited_df)
additional_info = pd.DataFrame(columns=['CLIENT_NAME', 'REQUEST_USERNAME', 'REQUEST_DATETIME'])
additional_info.loc[0] = [client, st.session_state.user_info['mail'], datetime.now().strftime("%Y-%m-%d %H:%M:%S")]
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 = []
if row['Unique Key']:
group_list.append('A')
allow_run_for_contract = True
if row['Pricing Before Carveouts']:
group_list.append('B')
allow_run_for_contract = True
if row['Contract Related']:
group_list.append('C')
allow_run_for_contract = True
if row['Provider']:
group_list.append('D')
allow_run_for_contract = True
if row['Timeline']:
group_list.append('E')
allow_run_for_contract = True
if row['Carveout Indicator']:
group_list.append('F')
allow_run_for_contract = True
if row['Carveout Methodology']:
group_list.append('G')
allow_run_for_contract = True
if allow_run_for_contract: st.session_state.contract_count += 1
buttons = st.columns([0.8, 0.2])
with buttons[0]:
st.download_button("Download Table", csv, "file.csv", "text/csv", key='download-csv')
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:
with st.spinner('Running...'):
time.sleep(2)
st.write("Success!")
st.write("Current processing time for A & C: 1 min")
st.write("Current processing time for B: 10 mins")