Spaces:
Build error
Build error
File size: 6,939 Bytes
8982d8d 6b5366c 8982d8d 6b5366c 8982d8d 2093efb 62e8857 2093efb 8982d8d 5fb23c1 8982d8d 7feb8bf 8982d8d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | import streamlit as st
import pandas as pd
import requests
import json
import re
import os
#from dotenv import load_dotenv
from datetime import datetime, timedelta, time
import pandas as pd
from io import BytesIO
import streamlit as st
# Load environment variables
#load_dotenv()
st.set_page_config(
page_title="馃崻Extracci贸n Reportes Mondelez",
layout="wide",
initial_sidebar_state="expanded",
)
columns_incidents = [
"Sitio", "Regi贸n", "Tipo de veh铆culo", "Nombre del colaborador", "Edad",
"脕rea", "Puesto", "Antig眉edad en 谩rea", "Antig眉edad en el puesto",
"Fecha y hora del accidente", "Fecha y hora en que se report贸 al supervisor",
"Fecha y hora de notificaci贸n va a servicio m茅dico/HSE", "Lugar del accidente",
"Descripci贸n del accidente", "DX", "TX", "D铆as de incapacidad", "Clasificaci贸n"
]
all_columns = columns_incidents + ["Enviado por", "Fecha envio"]
df = pd.DataFrame(columns=all_columns)
# Configuraci贸n inicial
st.title("Extracci贸n Reportes de Incidentes WhatsApp")
st.sidebar.header("Configuraci贸n de la App")
token = os.getenv("TOKEN_WHATSAPP")
excel_file = os.getenv("EXCEL_FILENAME") # Archivo donde se guardar谩n los datos
group_id = os.getenv("GROUP_ID_WHATSAPP") #st.sidebar.text_input("ID del Grupo")
print(group_id)
print(token)
today = datetime.today()
one_week_ago = today - timedelta(days=7)
hora_inicio = time(0, 0)
hora_fin = today.time()
with st.sidebar:
cols = st.sidebar.columns(2)
with cols[0]:
fecha_inicio = st.date_input("Fecha de Inicio", value=datetime.today(), min_value=one_week_ago, max_value=today, key="start_date")
fecha_fin = st.date_input("Fecha de Fin", value=datetime.today(), min_value=one_week_ago, max_value=today, key="end_date")
with cols[1]:
t_inicio = st.time_input("Hora Inicio", hora_inicio, key="start_time")
t_fin = st.time_input("Hora Fin", hora_fin, key="end_time")
# Funci贸n para obtener mensajes
start_date = datetime.combine(fecha_inicio, t_inicio)
end_date = datetime.combine(fecha_fin, t_fin)
def convert_date_to_timestamp(date):
return int(date.timestamp())
time_from = convert_date_to_timestamp(start_date)
time_to = convert_date_to_timestamp(end_date)
def get_group_messages(group_id, token):
url = f"https://gate.whapi.cloud/messages/list/{group_id}?time_from={time_from}&time_to={time_to}&count=100&sort=desc"
print(url)
headers = {
"accept": "application/json",
"Authorization": f"Bearer {token}"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return json.loads(response.text).get('messages', [])
else:
st.error(f"Error al obtener mensajes del grupo {group_id}. C贸digo: {response.status_code}")
return []
# Funci贸n para extraer informaci贸n del mensaje
def parse_message(message):
pattern = r"[\n][鈥(.*?): (.*)"
matches = re.findall(pattern, message)
return {key.strip(): value.strip() for key, value in matches}
# Funci贸n para verificar duplicados
def check_duplicates(existing_df, new_data):
# Combinar los datos existentes con los nuevos
new_df = pd.DataFrame(new_data)
combined_df = pd.concat([existing_df, new_df], ignore_index=True)
combined_df.drop_duplicates(subset=[
"Sitio", "Regi贸n", "Tipo de veh铆culo", "Nombre del colaborador",
"脕rea", "Puesto"
], inplace=True)
# Filtrar solo los nuevos datos
return combined_df[~combined_df.index.isin(existing_df.index)], combined_df
# Cargar el archivo Excel existente
def load_existing_data(file_path):
try:
return pd.read_excel(file_path)
except FileNotFoundError:
return pd.DataFrame(columns=all_columns)
# Guardar el archivo actualizado
def save_data_to_excel(file_path, df):
with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer:
df.to_excel(writer, index=False, sheet_name='Reportes')
# Obtener grupos
if token:
if group_id:
if st.sidebar.button("Cargar Mensajes Incidentes"):
messages = get_group_messages(group_id, token)
accident_reports = []
for message in messages:
if "text" in message:
if "body" in message['text']:
if "REPORTE DE INCIDENTE" in message['text']['body']:
if any(column not in message['text']['body'] for column in columns_incidents):
print("Mensaje no analizado",message['text']['body'])
continue
else:
accident_reports.append(
{
'mensaje': message['text']['body'],
'fecha': message['timestamp'],
'usuario': message['from_name']
}
)
# Filtrar mensajes relevantes
#accident_reports = [msg['text']['body'] for msg in messages if "REPORTE DE INCIDENTE" in msg['text']['body']]
# Procesar los reportes
report_data = []
for report in accident_reports:
parsed = parse_message(report['mensaje'])
parsed['Fecha envio'] = report['fecha']
parsed['Enviado por'] = report['usuario']
report_data.append(parsed)
# Mostrar datos en la app
if report_data:
# Cargar datos existentes
existing_data = load_existing_data(excel_file)
# Verificar duplicados
new_data, updated_data = check_duplicates(existing_data, report_data)
if not new_data.empty:
st.header("Reportes Extra铆dos")
df = pd.DataFrame(new_data)
df_edited = st.data_editor(df, hide_index=True)
# Guardar datos actualizados
st.download_button(
label = "Guardar Reportes",
data = df_edited.to_csv(index=False),
file_name="reportes_accidentes.csv",
mime="text/csv")
#save_data_to_excel(excel_file, updated_data)
st.success("Datos actualizados en el archivo Excel.")
else:
st.warning("No se encontraron reportes nuevos para agregar.")
else:
st.warning("No se encontraron reportes de accidentes nuevos para agregar.")
else:
st.sidebar.info("Introduce un ID de grupo para comenzar.")
else:
st.sidebar.info("Introduce tu token de API.")
|