Spaces:
Sleeping
Sleeping
fschwartzer
commited on
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
from transformers import BartForConditionalGeneration, TapexTokenizer, T5ForConditionalGeneration, T5Tokenizer
|
4 |
+
import datetime
|
5 |
+
import sentencepiece as spm
|
6 |
+
|
7 |
+
# File upload interface
|
8 |
+
uploaded_file = st.file_uploader("Upload a CSV or XLSX file", type=['csv', 'xlsx'])
|
9 |
+
|
10 |
+
if uploaded_file:
|
11 |
+
# Load the file into a DataFrame
|
12 |
+
if uploaded_file.name.endswith('.csv'):
|
13 |
+
df = pd.read_csv(uploaded_file, quotechar='"', encoding='utf-8')
|
14 |
+
elif uploaded_file.name.endswith('.xlsx'):
|
15 |
+
df = pd.read_excel(uploaded_file)
|
16 |
+
|
17 |
+
df.rename(columns={"ds": "datetime", "real": "monetary value", "Explicação": "explanation"}, inplace=True)
|
18 |
+
df.sort_values(by=['datetime', 'monetary value'], ascending=False, inplace=True)
|
19 |
+
df = df[df['monetary value'] >= 10000000.]
|
20 |
+
df['monetary value'] = df['monetary value'].apply(lambda x: f"{x:.2f}")
|
21 |
+
df = df.fillna('').astype(str)
|
22 |
+
table_data = df
|
23 |
+
|
24 |
+
# Display the uploaded table
|
25 |
+
st.dataframe(table_data.head())
|
26 |
+
|
27 |
+
# Load translation models
|
28 |
+
pt_en_translator = T5ForConditionalGeneration.from_pretrained("unicamp-dl/translation-pt-en-t5")
|
29 |
+
en_pt_translator = T5ForConditionalGeneration.from_pretrained("unicamp-dl/translation-en-pt-t5")
|
30 |
+
tokenizer = T5Tokenizer.from_pretrained("unicamp-dl/translation-pt-en-t5")
|
31 |
+
|
32 |
+
# Load TAPEX model
|
33 |
+
tapex_model = BartForConditionalGeneration.from_pretrained("microsoft/tapex-large-finetuned-wtq")
|
34 |
+
tapex_tokenizer = TapexTokenizer.from_pretrained("microsoft/tapex-large-finetuned-wtq")
|
35 |
+
|
36 |
+
def translate(text, model, tokenizer, source_lang="pt", target_lang="en"):
|
37 |
+
input_ids = tokenizer.encode(text, return_tensors="pt", add_special_tokens=True)
|
38 |
+
outputs = model.generate(input_ids)
|
39 |
+
translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
40 |
+
return translated_text
|
41 |
+
|
42 |
+
def response(user_question, table_data):
|
43 |
+
# Traduz a pergunta para o inglês
|
44 |
+
question_en = translate(user_question, pt_en_translator, tokenizer, source_lang="pt", target_lang="en")
|
45 |
+
print(question_en)
|
46 |
+
|
47 |
+
# Gera a resposta em inglês
|
48 |
+
encoding = tapex_tokenizer(table=table_data, query=[question_en], padding=True, return_tensors="pt", truncation=True)
|
49 |
+
outputs = tapex_model.generate(**encoding)
|
50 |
+
response_en = tapex_tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
|
51 |
+
print(response_en)
|
52 |
+
|
53 |
+
# Traduz a resposta para o português
|
54 |
+
response_pt = translate(response_en, en_pt_translator, tokenizer, source_lang="en", target_lang="pt")
|
55 |
+
return response_pt
|
56 |
+
|
57 |
+
# Streamlit interface
|
58 |
+
|
59 |
+
st.markdown("""
|
60 |
+
<div style='display: flex; align-items: center;'>
|
61 |
+
<div style='width: 40px; height: 40px; background-color: green; border-radius: 50%; margin-right: 5px;'></div>
|
62 |
+
<div style='width: 40px; height: 40px; background-color: red; border-radius: 50%; margin-right: 5px;'></div>
|
63 |
+
<div style='width: 40px; height: 40px; background-color: yellow; border-radius: 50%; margin-right: 5px;'></div>
|
64 |
+
<span style='font-size: 40px; font-weight: bold;'>Chatbot do Tesouro RS</span>
|
65 |
+
</div>
|
66 |
+
""", unsafe_allow_html=True)
|
67 |
+
|
68 |
+
# Chat history
|
69 |
+
if 'history' not in st.session_state:
|
70 |
+
st.session_state['history'] = []
|
71 |
+
|
72 |
+
# Input box for user question
|
73 |
+
user_question = st.text_input("Escreva sua questão aqui:", "")
|
74 |
+
|
75 |
+
if user_question:
|
76 |
+
# Add human emoji when user asks a question
|
77 |
+
st.session_state['history'].append(('👤', user_question))
|
78 |
+
st.markdown(f"**👤 {user_question}**")
|
79 |
+
|
80 |
+
# Generate the response
|
81 |
+
bot_response = response(user_question, table_data)
|
82 |
+
|
83 |
+
# Add robot emoji when generating response and align to the right
|
84 |
+
st.session_state['history'].append(('🤖', bot_response))
|
85 |
+
st.markdown(f"<div style='text-align: right'>**🤖 {bot_response}**</div>", unsafe_allow_html=True)
|
86 |
+
|
87 |
+
# Clear history button
|
88 |
+
if st.button("Limpar"):
|
89 |
+
st.session_state['history'] = []
|
90 |
+
|
91 |
+
# Display chat history
|
92 |
+
for sender, message in st.session_state['history']:
|
93 |
+
if sender == '👤':
|
94 |
+
st.markdown(f"**👤 {message}**")
|
95 |
+
elif sender == '🤖':
|
96 |
+
st.markdown(f"<div style='text-align: right'>**🤖 {message}**</div>", unsafe_allow_html=True)
|
97 |
+
else:
|
98 |
+
st.warning("Carregue um arquivo CSV ou XLSX para começar.")
|