Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -68,20 +68,92 @@ def load_data(uploaded_file):
|
|
68 |
return df
|
69 |
|
70 |
def preprocess_data(df):
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
-
def apply_prophet(df):
|
75 |
-
# Implementar o modelo Prophet aqui
|
76 |
-
return df
|
77 |
-
|
78 |
# Interface para carregar arquivo
|
79 |
uploaded_file = st.file_uploader("Carregue um arquivo CSV ou XLSX", type=['csv', 'xlsx'])
|
80 |
-
if uploaded_file
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
85 |
|
86 |
# Interface para perguntas do usuário
|
87 |
user_question = st.text_input("Escreva sua questão aqui:", "")
|
|
|
68 |
return df
|
69 |
|
70 |
def preprocess_data(df):
|
71 |
+
if uploaded_file.name.endswith('.csv'):
|
72 |
+
df = pd.read_csv(uploaded_file, quotechar='"', encoding='utf-8')
|
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 |
+
data = pd.DataFrame({
|
110 |
+
'ds': [col for col in df_clean.columns if isinstance(col, pd.Timestamp)],
|
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 |
+
if 'all_anomalies' not in st.session_state:
|
151 |
+
df = load_data(uploaded_file)
|
152 |
+
df = preprocess_data(df)
|
153 |
+
with st.spinner('Aplicando modelo de série temporal...'):
|
154 |
+
all_anomalies = apply_prophet(df)
|
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:", "")
|