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