Adds current version of files

This commit is contained in:
2026-01-16 17:26:18 -03:00
parent d37d5132eb
commit 9eecd617b3
5 changed files with 265 additions and 89 deletions

View File

@@ -8,8 +8,12 @@ import boto3
from botocore.exceptions import ClientError
import jwt
headers = st.context.headers
# The ID token contains user claims
import streamlit as st
# Using a list of options
options = ["English", "Portugues", "Espanhol",]
language = st.selectbox("Response language:", options)
id_token = headers.get('x-amzn-oidc-data')
decoded = jwt.decode(id_token, options={"verify_signature": False})
@@ -20,6 +24,7 @@ user_id = (
decoded.get("username") or # Username alternativo
decoded.get("user_id") # Campo customizado
)
email=decoded.get("email")
st.header("Assistente Produtos Servicos")
url="https://xexm2wsz07-vpce-05915540d0592b921.execute-api.us-east-1.amazonaws.com/dev"
payload=[]
@@ -47,7 +52,7 @@ if prompt:
st.chat_message("user").write(prompt)
with st.spinner("Generating response.."):
payload=[{"role":"user","content":prompt}]
content={"message":payload,"chat_history":st.session_state["chat_history"],"username":user_id}
content={"message":payload,"chat_history":st.session_state["chat_history"],"username":user_id,"origem":"Front","email":email,"language":language}
headers={"Content-type":"application/json","x-api-key":json.loads(st_auth.get_secret())['api-gateway-api-key']}
generated_response=json.loads(requests.post(url,json=content,headers=headers).text)
if 'chat_history' in generated_response:

View File

@@ -1,82 +1,8 @@
import streamlit_authenticator as stauth
import yaml
from yaml.loader import SafeLoader
import streamlit as st
import boto3
from botocore.exceptions import ClientError
def get_authenticator():
# with open('.streamlit/users.yaml') as file:
# cred_config = yaml.load(file, Loader=SafeLoader)
file_content = read_text_file_from_s3('chatbot-editais-auth', 'config.yaml')
# Parse the YAML content safely
cred_config = yaml.safe_load(file_content)
# Pre-hashing all plain text passwords once
# hash_credentials = stauth.Hasher.hash_passwords(config['credentials'])
authenticator = stauth.Authenticate(
cred_config['credentials'],
cred_config['cookie']['name'],
cred_config['cookie']['key'],
cred_config['cookie']['expiry_days']
)
return authenticator
def st_authenticate(authenticator: stauth.Authenticate):
# authenticator = get_authenticator()
try:
authenticator.login(
location='sidebar',
fields=dict(Username="Usuário",
Password="Senha")
)
except Exception as e:
st.error(e)
authenticator.cookie_controller.delete_cookie()
st.warning('Caso o erro persistir, tente recarregar a página.')
st.stop()
if st.session_state['authentication_status']:
with st.sidebar:
st.write(f'Usuário: {st.session_state["name"]}')
authenticator.logout()
elif st.session_state['authentication_status'] is False:
with st.sidebar:
st.error('Usuário/senha incorreto')
st.stop()
elif st.session_state['authentication_status'] is None:
st.warning('Por favor, informe o seu usuário e senha no painel lateral')
st.stop()
def read_text_file_from_s3(bucket, key):
"""
Read a YAML file from an S3 bucket using provided AWS credentials.
Args:
bucket (str): Name of the S3 bucket
key (str): Path to the YAML file in the bucket
aws_access_key_id (str): AWS Access Key ID
aws_secret_access_key (str): AWS Secret Access Key
Returns:
dict: Parsed YAML content
"""
try:
# Create an S3 client
s3_client = boto3.client('s3')
# Download the file from S3
response = s3_client.get_object(Bucket=bucket, Key=key)
# Read the file content
file_content = response['Body'].read().decode('utf-8')
return file_content
except Exception as e:
st.error(f"Error reading file from S3: {e}")
return None
def get_secret():
secret_name = "assistente-produtos-servicos"