Spaces:
Build error
Build error
| 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.") | |