Spaces:
Runtime error
Runtime error
| import streamlit as st | |
| import pandas as pd | |
| import torch | |
| from transformers import GPT2Tokenizer, GPT2LMHeadModel | |
| # Carregando o modelo e o tokenizador do GPT-2 | |
| tokenizer = GPT2Tokenizer.from_pretrained('gpt2') | |
| model = GPT2LMHeadModel.from_pretrained('gpt2') | |
| # Set the padding token to the end-of-sequence token | |
| if tokenizer.pad_token is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| df = pd.read_csv('anomalies.csv') | |
| # Função para gerar resposta | |
| def response(question): | |
| prompt = f"Considerando os dados: {df.to_string(index=False)}. Pergunta: {question} Resposta:" | |
| inputs = tokenizer(prompt, return_tensors='pt', padding='max_length', truncation=True, max_length=512) | |
| attention_mask = inputs['attention_mask'] | |
| input_ids = inputs['input_ids'] | |
| generated_ids = model.generate( | |
| input_ids, | |
| attention_mask=attention_mask, | |
| max_length=len(input_ids[0]) + 100, # Aumentar o limite de geração | |
| temperature=0.65, # Ajustar a criatividade | |
| top_p=0.9, # Usar nucleus sampling | |
| no_repeat_ngram_size=2 # Evitar repetições desnecessárias | |
| ) | |
| generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) | |
| # Processando para extrair apenas a resposta após "Resposta:" | |
| response_part = generated_text.split("Resposta:")[1] if "Resposta:" in generated_text else "Resposta não encontrada." | |
| final_response = response_part.split(".")[0] + "." # Assumindo que a resposta termina na primeira sentença. | |
| return final_response | |
| # Interface Streamlit | |
| st.markdown(""" | |
| <div style='display: flex; align-items: center;'> | |
| <div style='width: 20px; height: 20px; background-color: green; border-radius: 50%; margin-right: 5px;'></div> | |
| <div style='width: 20px; height: 20px; background-color: red; border-radius: 50%; margin-right: 5px;'></div> | |
| <div style='width: 20px; height: 20px; background-color: yellow; border-radius: 50%; margin-right: 10px;'></div> | |
| <span style='font-size: 24px; font-weight: bold;'>Chatbot do Tesouro RS</span> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Histórico de conversas | |
| if 'history' not in st.session_state: | |
| st.session_state['history'] = [] | |
| # Caixa de entrada para a pergunta | |
| user_question = st.text_input("Escreva sua questão aqui:", "") | |
| if user_question: | |
| # Adiciona emoji de pessoa quando a pergunta está sendo digitada | |
| st.session_state['history'].append(('👤', user_question)) | |
| st.markdown(f"**👤 {user_question}**") | |
| # Gera a resposta | |
| bot_response = response(user_question) | |
| # Adiciona emoji de robô quando a resposta está sendo gerada e alinha à direita | |
| st.session_state['history'].append(('🤖', bot_response)) | |
| st.markdown(f"<div style='text-align: right'>**🤖 {bot_response}**</div>", unsafe_allow_html=True) | |
| # Botão para limpar o histórico | |
| if st.button("Limpar"): | |
| st.session_state['history'] = [] | |
| # Exibe o histórico de conversas | |
| for sender, message in st.session_state['history']: | |
| if sender == '👤': | |
| st.markdown(f"**👤 {message}**") | |
| elif sender == '🤖': | |
| st.markdown(f"<div style='text-align: right'>**🤖 {message}**</div>", unsafe_allow_html=True) | |