Spaces:
Running
Running
fschwartzer
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -3,11 +3,8 @@ import pandas as pd
|
|
3 |
from transformers import BartForConditionalGeneration, TapexTokenizer, T5ForConditionalGeneration, T5Tokenizer
|
4 |
from prophet import Prophet
|
5 |
|
6 |
-
# Caminho para o arquivo CSS, ajuste conforme a estrutura do seu projeto
|
7 |
-
css_file = "style.css"
|
8 |
-
|
9 |
# Abrindo e lendo o arquivo CSS
|
10 |
-
with open(
|
11 |
css_style = css.read()
|
12 |
|
13 |
# Markdown combinado com a importação da fonte e o HTML
|
@@ -18,10 +15,10 @@ html_content = f"""
|
|
18 |
</style>
|
19 |
<div style='display: flex; flex-direction: column; align-items: flex-start;'>
|
20 |
<div style='display: flex; align-items: center;'>
|
21 |
-
<div style='width: 20px; height:
|
22 |
-
<div style='width: 20px; height:
|
23 |
-
<div style='width: 20px; height:
|
24 |
-
<span style='font-size:
|
25 |
</div>
|
26 |
<div style='text-align: left; width: 100%;'>
|
27 |
<span style='font-size: 20px; font-weight: normal; color: #333; font-family: "Kanit", sans-serif'>
|
@@ -68,99 +65,45 @@ def load_data(uploaded_file):
|
|
68 |
return df
|
69 |
|
70 |
def preprocess_data(df):
|
71 |
-
|
72 |
-
|
73 |
-
elif uploaded_file.name.endswith('.xlsx'):
|
74 |
-
df = pd.read_excel(uploaded_file)
|
75 |
-
|
76 |
-
# Data preprocessing for Prophet
|
77 |
-
new_df = df.iloc[2:, 9:-1].fillna(0)
|
78 |
-
new_df.columns = df.iloc[1, 9:-1]
|
79 |
-
new_df.columns = new_df.columns.str.replace(r" \(\d+\)", "", regex=True)
|
80 |
-
|
81 |
-
month_dict = {
|
82 |
-
'Jan': '01', 'Fev': '02', 'Mar': '03', 'Abr': '04',
|
83 |
-
'Mai': '05', 'Jun': '06', 'Jul': '07', 'Ago': '08',
|
84 |
-
'Set': '09', 'Out': '10', 'Nov': '11', 'Dez': '12'
|
85 |
-
}
|
86 |
-
|
87 |
-
def convert_column_name(column_name):
|
88 |
-
if column_name == 'Rótulos de Linha':
|
89 |
-
return column_name
|
90 |
-
parts = column_name.split('/')
|
91 |
-
month = parts[0].strip()
|
92 |
-
year = parts[1].strip()
|
93 |
-
year = ''.join(filter(str.isdigit, year))
|
94 |
-
month_number = month_dict.get(month, '00')
|
95 |
-
return f"{month_number}/{year}"
|
96 |
-
|
97 |
-
new_df.columns = [convert_column_name(col) for col in new_df.columns]
|
98 |
-
new_df.columns = pd.to_datetime(new_df.columns, errors='coerce')
|
99 |
-
new_df.rename(columns={new_df.columns[0]: 'Rotulo'}, inplace=True)
|
100 |
-
df_clean = new_df.copy()
|
101 |
-
return df_clean
|
102 |
|
103 |
def apply_prophet(df_clean):
|
|
|
|
|
|
|
|
|
104 |
# Criar um DataFrame vazio para armazenar todas as anomalias
|
105 |
all_anomalies = pd.DataFrame()
|
106 |
-
|
107 |
# Processar cada linha no DataFrame
|
108 |
for index, row in df_clean.iterrows():
|
109 |
-
|
110 |
-
|
111 |
-
'y': row[[isinstance(col, pd.Timestamp) for col in df_clean.columns]].values
|
112 |
-
})
|
113 |
-
|
114 |
-
data = data[data['y'] > 0].reset_index(drop=True)
|
115 |
-
if data.empty or len(data) < 2:
|
116 |
-
print(f"Pulando grupo {row['Rotulo']} porque há menos de 2 observações não nulas.")
|
117 |
-
continue
|
118 |
-
|
119 |
-
try:
|
120 |
-
model = Prophet(interval_width=0.95)
|
121 |
-
model.fit(data)
|
122 |
-
except ValueError as e:
|
123 |
-
print(f"Pulando grupo {row['Rotulo']} devido a erro: {e}")
|
124 |
-
continue
|
125 |
-
|
126 |
-
future = model.make_future_dataframe(periods=12, freq='M')
|
127 |
-
forecast = model.predict(future)
|
128 |
-
|
129 |
-
num_real = len(data)
|
130 |
-
num_forecast = len(forecast)
|
131 |
-
real_values = list(data['y']) + [None] * (num_forecast - num_real)
|
132 |
-
forecast['real'] = real_values
|
133 |
-
anomalies = forecast[(forecast['real'] < forecast['yhat_lower']) | (forecast['real'] > forecast['yhat_upper'])]
|
134 |
-
|
135 |
-
anomalies['Group'] = row['Rotulo']
|
136 |
-
all_anomalies = pd.concat([all_anomalies, anomalies[['ds', 'real', 'Group']]], ignore_index=True)
|
137 |
|
138 |
# Renomear colunas e aplicar filtros
|
139 |
-
all_anomalies.rename(columns={"ds": "datetime", "real": "monetary value", "Group": "group"}, inplace=True)
|
140 |
-
all_anomalies = all_anomalies[all_anomalies['monetary value'].astype(float) >= 10000000.00]
|
141 |
-
all_anomalies['monetary value'] = all_anomalies['monetary value'].apply(lambda x: f"{x:.2f}")
|
142 |
-
all_anomalies.sort_values(by=['monetary value'], ascending=False, inplace=True)
|
143 |
-
all_anomalies = all_anomalies.fillna('').astype(str)
|
144 |
-
|
145 |
return all_anomalies
|
146 |
|
147 |
# Interface para carregar arquivo
|
148 |
uploaded_file = st.file_uploader("Carregue um arquivo CSV ou XLSX", type=['csv', 'xlsx'])
|
149 |
if uploaded_file:
|
150 |
-
|
151 |
-
|
152 |
-
|
|
|
|
|
153 |
with st.spinner('Aplicando modelo de série temporal...'):
|
154 |
-
all_anomalies = apply_prophet(
|
155 |
st.session_state['all_anomalies'] = all_anomalies
|
156 |
-
st.session_state['all_anomalies'] = all_anomalies
|
157 |
|
158 |
# Interface para perguntas do usuário
|
159 |
user_question = st.text_input("Escreva sua questão aqui:", "")
|
160 |
if user_question:
|
161 |
-
|
162 |
-
|
163 |
-
|
|
|
|
|
|
|
164 |
|
165 |
# Mostrar histórico de conversa
|
166 |
for sender, message in st.session_state['history']:
|
@@ -171,4 +114,4 @@ for sender, message in st.session_state['history']:
|
|
171 |
|
172 |
# Botão para limpar histórico
|
173 |
if st.button("Limpar histórico"):
|
174 |
-
st.session_state['history'] = []
|
|
|
3 |
from transformers import BartForConditionalGeneration, TapexTokenizer, T5ForConditionalGeneration, T5Tokenizer
|
4 |
from prophet import Prophet
|
5 |
|
|
|
|
|
|
|
6 |
# Abrindo e lendo o arquivo CSS
|
7 |
+
with open("style.css", "r") as css:
|
8 |
css_style = css.read()
|
9 |
|
10 |
# Markdown combinado com a importação da fonte e o HTML
|
|
|
15 |
</style>
|
16 |
<div style='display: flex; flex-direction: column; align-items: flex-start;'>
|
17 |
<div style='display: flex; align-items: center;'>
|
18 |
+
<div style='width: 20px; height: 4px; background-color: green; margin-right: 1px;'></div>
|
19 |
+
<div style='width: 20px; height: 4px; background-color: red; margin-right: 1px;'></div>
|
20 |
+
<div style='width: 20px; height: 4px; background-color: yellow; margin-right: 20px;'></div>
|
21 |
+
<span style='font-size: 45px; font-weight: normal; font-family: "Kanit", sans-serif;'>NOSTRADAMUS</span>
|
22 |
</div>
|
23 |
<div style='text-align: left; width: 100%;'>
|
24 |
<span style='font-size: 20px; font-weight: normal; color: #333; font-family: "Kanit", sans-serif'>
|
|
|
65 |
return df
|
66 |
|
67 |
def preprocess_data(df):
|
68 |
+
# Implementar as etapas de pré-processamento aqui
|
69 |
+
return df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
def apply_prophet(df_clean):
|
72 |
+
if df_clean.empty:
|
73 |
+
st.error("DataFrame está vazio após o pré-processamento.")
|
74 |
+
return pd.DataFrame()
|
75 |
+
|
76 |
# Criar um DataFrame vazio para armazenar todas as anomalias
|
77 |
all_anomalies = pd.DataFrame()
|
|
|
78 |
# Processar cada linha no DataFrame
|
79 |
for index, row in df_clean.iterrows():
|
80 |
+
# Implementar o processamento com o modelo Prophet aqui
|
81 |
+
pass # Substituir pass pelo seu código real
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
# Renomear colunas e aplicar filtros
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
return all_anomalies
|
85 |
|
86 |
# Interface para carregar arquivo
|
87 |
uploaded_file = st.file_uploader("Carregue um arquivo CSV ou XLSX", type=['csv', 'xlsx'])
|
88 |
if uploaded_file:
|
89 |
+
df = load_data(uploaded_file)
|
90 |
+
df_clean = preprocess_data(df)
|
91 |
+
if df_clean.empty:
|
92 |
+
st.warning("Não há dados válidos para processar.")
|
93 |
+
else:
|
94 |
with st.spinner('Aplicando modelo de série temporal...'):
|
95 |
+
all_anomalies = apply_prophet(df_clean)
|
96 |
st.session_state['all_anomalies'] = all_anomalies
|
|
|
97 |
|
98 |
# Interface para perguntas do usuário
|
99 |
user_question = st.text_input("Escreva sua questão aqui:", "")
|
100 |
if user_question:
|
101 |
+
if 'all_anomalies' in st.session_state and not st.session_state['all_anomalies'].empty:
|
102 |
+
bot_response = response(user_question, st.session_state['all_anomalies'])
|
103 |
+
st.session_state['history'].append(('👤', user_question))
|
104 |
+
st.session_state['history'].append(('🤖', bot_response))
|
105 |
+
else:
|
106 |
+
st.warning("Ainda não há dados de anomalias para responder a pergunta.")
|
107 |
|
108 |
# Mostrar histórico de conversa
|
109 |
for sender, message in st.session_state['history']:
|
|
|
114 |
|
115 |
# Botão para limpar histórico
|
116 |
if st.button("Limpar histórico"):
|
117 |
+
st.session_state['history'] = []
|