2024-02-28 18:23:22 +05:30
import json
import boto3
from langchain . prompts import PromptTemplate
from langchain . embeddings . bedrock import BedrockEmbeddings
from langchain . llms . bedrock import Bedrock
from langchain_community . vectorstores import Chroma
2024-05-06 19:28:00 -05:00
from constants import CHROMA_SETTINGS , EMBEDDING_MODEL_NAME , PERSIST_DIRECTORY , MODEL_ID , MODEL_BASENAME , SOURCE_DIRECTORY , USER_LIST
2024-02-28 18:23:22 +05:30
from langchain . chains import RetrievalQA
import streamlit as st
from streamlit_extras . add_vertical_space import add_vertical_space
import os
import pandas as pd
2024-03-13 17:23:20 +05:30
import numpy as np
2024-03-08 17:36:36 +05:30
import util
2024-03-13 17:23:20 +05:30
import anthropic
from pydantic import BaseModel
from typing import List
import re
2024-05-10 15:39:42 -05:00
from sf_conn import get_snowflake_conn
2024-02-28 18:23:22 +05:30
2024-05-22 16:50:47 -05:00
REDIRECT_URI = ' https://doczydev.aarete.com:8502 '
2024-06-05 10:15:14 -05:00
user_list = USER_LIST # RECOMMENDATION - AWS Secrets Manager or Snowflake
2024-02-28 18:23:22 +05:30
2024-03-08 17:36:36 +05:30
st . set_page_config ( layout = " wide " )
2024-02-28 18:23:22 +05:30
# 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")
2024-04-02 14:31:43 +05:30
_ , c1 = st . columns ( [ 5 , 1 ] )
2024-03-13 17:23:20 +05:30
try :
2024-06-05 10:15:14 -05:00
util . setup_page ( REDIRECT_URI ) # RECOMMENDATION - Not secure enough
2024-03-13 17:23:20 +05:30
except :
2024-04-10 20:43:35 +05:30
st . write ( " SSO Failed " )
2024-06-05 10:15:14 -05: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 ' ] } ** " )
user_mail = st . session_state . user_info [ ' mail ' ]
except KeyError as e :
st . write ( " Session Expired. " )
2024-04-09 16:20:29 +05:30
st . stop ( )
2024-03-13 17:23:20 +05:30
2024-05-10 17:46:38 +05:30
# remove below try except statement if comparison with actual vales is not required
2024-03-22 23:59:54 +05:30
try :
2024-05-10 15:39:42 -05:00
conn = get_snowflake_conn ( ' STG ' )
2024-03-22 23:59:54 +05:30
cur = conn . cursor ( )
2024-06-05 10:15:14 -05:00
query = ' select * from " TRAINING_DATA_RAW " ' # RECOMMENDATION - Move all queries to another file like constants
2024-03-22 23:59:54 +05:30
cur . execute ( query )
field_values = pd . DataFrame . from_records ( iter ( cur ) , columns = [ x [ 0 ] for x in cur . description ] )
2024-06-05 10:15:14 -05:00
field_values [ ' Document_Name ' ] = field_values [ ' DOCUMENT_NAME ' ] # RECOMMENDATION - Use String Matching or something less hardcoded
2024-03-22 23:59:54 +05:30
except :
2024-05-10 16:41:41 -05:00
# field_values = pd.read_csv('contract_field_values.csv', encoding='unicode_escape', skipinitialspace=True)
# field_values = field_values.loc[:, ~field_values.columns.str.contains('Unnamed:')]
st . write ( " Conn failed, unable to fetch data from training data table in Snowflake " )
2024-03-22 23:59:54 +05:30
try :
2024-06-05 10:15:14 -05:00
query = ' select * from " PROMPT_CONFIG " ' # RECOMMENDATION - Move query somewhere else
2024-03-22 23:59:54 +05:30
cur . execute ( query )
2024-05-10 16:41:41 -05:00
fields = pd . DataFrame . from_records ( iter ( cur ) , columns = [ x [ 0 ] for x in cur . description ] )
2024-06-05 10:15:14 -05:00
fields . rename ( columns = { ' FIELD_DESC ' : ' Field Name ' } , inplace = True ) # RECOMMENDATION - Package into less hardcoded function or handle in DB
2024-03-22 23:59:54 +05:30
fields . rename ( columns = { ' PROMPT ' : ' Interrogation Question? ' } , inplace = True )
fields . rename ( columns = { ' GROUP_ID ' : ' PRIORITY ' } , inplace = True )
fields . rename ( columns = { ' FIELD_NAME ' : ' SF_DB_COL_NAME ' } , inplace = True )
2024-05-10 16:41:41 -05:00
fields . rename ( columns = { ' FM_MODEL_ID ' : ' llm_selected ' } , inplace = True )
2024-05-10 15:46:51 -05:00
except Exception as e :
2024-05-10 15:45:35 -05:00
st . write ( " Unable to fetch data from Snowflake: " , e )
2024-05-10 15:39:42 -05:00
# fields = pd.read_csv('contract_fields.csv', encoding='unicode_escape', skipinitialspace=True)
# fields = fields[~fields['SF_COL_NAME'].str.endswith('_PG', na=None)]
2024-03-22 23:59:54 +05:30
2024-05-10 17:46:38 +05:30
# change the code below if contract list is fetched from snowflake
2024-03-22 23:59:54 +05:30
s3_client = boto3 . client ( ' s3 ' ,
2024-04-02 19:20:12 +05:30
region_name = " us-east-2 "
2024-03-22 23:59:54 +05:30
)
2024-06-05 16:12:39 -05:00
bucket = ' doczy-dev-infra-textract ' # needs to be dynamic based on Client Name and Batch ID
2024-04-19 17:16:13 +05:30
objects = s3_client . list_objects_v2 ( Bucket = bucket , Prefix = " training-data/ " )
2024-03-22 23:59:54 +05:30
file_list = [ ]
for obj in objects [ ' Contents ' ] :
if not obj [ ' Key ' ] . endswith ( ' / ' ) :
file_list . append ( obj [ ' Key ' ] )
contract_list = sorted ( file_list )
2024-05-28 17:36:41 -05:00
file_row = st . columns ( [ 0.2 , 0.7 , 0.1 ] )
with file_row [ 0 ] :
st . write ( " **Contract Name** " )
with file_row [ 1 ] :
file_name = st . selectbox ( ' Select a file ' , contract_list + [ ' All ' ] , label_visibility = " collapsed " )
field_row = st . columns ( [ 0.2 , 0.7 , 0.1 ] )
with field_row [ 0 ] :
st . write ( " **Field Group** " )
with field_row [ 1 ] :
2024-06-05 10:15:14 -05:00
field_group = st . selectbox ( ' Field Group ' , ( ' Unique Key ' , ' Contract Related ' , ' Pricing Before Carveouts - I ' # RECOMMENDATION - Get from a separate list or snowflake
2024-05-28 17:36:41 -05:00
, ' Pricing Before Carveouts - II ' , ' Carveout Indicator, Code Type and Code #s - I '
, ' Carveout Indicator, Code Type and Code #s - II ' , ' Carveout Indicator, Code Type and Code #s - III '
, ' Optimize Carving Indic. ' , ' Carveout Method - I ' , ' Carveout Method - II ' , ' Provider '
, ' Timeline ' ) , label_visibility = " collapsed " )
2024-06-05 10:15:14 -05:00
if field_group == ' Unique Key ' : # RECOMMENDATION - Use a Dictionary for this mapping
2024-05-28 17:36:41 -05:00
fields = fields [ fields [ ' PRIORITY ' ] == ' A ' ]
elif field_group == ' Contract Related ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' C ' ]
elif field_group == ' Pricing Before Carveouts - I ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' B ' ]
fields = np . array_split ( fields , 2 ) [ 0 ]
elif field_group == ' Pricing Before Carveouts - II ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' B ' ]
fields = np . array_split ( fields , 2 ) [ 1 ]
elif field_group == ' Carveout Indicator, Code Type and Code #s - I ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' F ' ]
fields = np . array_split ( fields , 3 ) [ 0 ]
elif field_group == ' Carveout Indicator, Code Type and Code #s - II ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' F ' ]
fields = np . array_split ( fields , 3 ) [ 1 ]
elif field_group == ' Carveout Indicator, Code Type and Code #s - III ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' F ' ]
fields = np . array_split ( fields , 3 ) [ 2 ]
elif field_group == ' Carveout Methodology - I ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' G ' ]
fields = np . array_split ( fields , 4 ) [ 0 ]
elif field_group == ' Carveout Methodology - II ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' G ' ]
fields = np . array_split ( fields , 4 ) [ 1 ]
elif field_group == ' Carveout Method - III ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' G ' ]
fields = np . array_split ( fields , 4 ) [ 2 ]
elif field_group == ' Carveout Method - IV ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' G ' ]
fields = np . array_split ( fields , 4 ) [ 3 ]
elif field_group == ' Provider ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' D ' ]
elif field_group == ' Timeline ' :
fields = fields [ fields [ ' PRIORITY ' ] == ' E ' ]
if st . button ( " Show Results " ) :
2024-06-05 16:12:39 -05:00
#Might be beneficial to have some error handling here for if query execution isn't successful - Use try and catch to handle error
2024-06-05 14:19:21 -05:00
2024-06-05 16:12:39 -05:00
query = ' select * from " DOCZY_PIPELINE_RAW_OUTPUT " ' # RECOMMENDATION - Move query somewhere else - needs to have batch ID and client name
2024-05-28 17:36:41 -05:00
cur . execute ( query )
df2 = pd . DataFrame . from_records ( iter ( cur ) , columns = [ x [ 0 ] for x in cur . description ] )
# get this dataframe from snowflake table
# df2 = pd.DataFrame(columns=['Contract Name','Field Name', 'SF_DB_COL_NAME', 'Snippet','Page Number'
# , 'Field Extracted Value', 'Actual Value','Imputed Value'])
df2 . to_csv ( ' temp2.csv ' , index = False )
df2 = pd . read_csv ( ' temp2.csv ' )
df2 [ ' Imputed Value ' ] = ' '
edited_df = st . data_editor ( df2 )
2024-06-05 14:19:21 -05:00
2024-05-28 17:36:41 -05:00
@st.cache_data
def convert_df ( df ) :
return df . to_csv ( index = False ) . encode ( ' utf-8 ' )
csv = convert_df ( edited_df )
buttons = st . columns ( 3 )
with buttons [ 0 ] :
# st.button("Save All Imputations")
st . download_button ( " Download Table " , csv , " file.csv " , " text/csv " , key = ' download-csv ' )
with buttons [ 1 ] :
# st.download_button("Download Table", csv, "file.csv", "text/csv", key='download-csv')
st . write ( " " )
with buttons [ 2 ] :
if st . button ( " Kickoff Database Integration " ) :
st . write ( " Stored in DB " )
2024-02-28 18:23:22 +05:30