Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
| 1 |
-
# slack_reporter/app.py –
|
| 2 |
import os
|
| 3 |
import time
|
| 4 |
import schedule
|
| 5 |
import pandas as pd
|
| 6 |
-
import matplotlib.pyplot as plt
|
| 7 |
import requests
|
| 8 |
import logging
|
| 9 |
import re
|
|
@@ -23,77 +22,6 @@ REPO_ID = "ChargeNodeEurope/logfiles"
|
|
| 23 |
LOG_FILENAME = "logs/conversation_log.txt"
|
| 24 |
WEBHOOK_URL = os.environ.get("SLACK_WEBHOOK_URL")
|
| 25 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 26 |
-
IMGUR_CLIENT_ID = os.environ.get("IMGUR_CLIENT_ID") # Du måste lägga till denna i dina Secrets
|
| 27 |
-
|
| 28 |
-
# --- Funktion: Skapa grafer ---
|
| 29 |
-
def generate_graphs(df):
|
| 30 |
-
if df.empty:
|
| 31 |
-
logging.warning("DataFrame är tom – inga loggar att analysera.")
|
| 32 |
-
return None, None
|
| 33 |
-
|
| 34 |
-
now = datetime.now()
|
| 35 |
-
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
| 36 |
-
|
| 37 |
-
# 1. Unika användare per dag (14 dagar)
|
| 38 |
-
daily_users = df.groupby(df['timestamp'].dt.date)['user_id'].nunique()
|
| 39 |
-
daily_users.index = pd.to_datetime(daily_users.index)
|
| 40 |
-
daily_users = daily_users.last("14D")
|
| 41 |
-
plt.figure(figsize=(8, 4))
|
| 42 |
-
daily_users.plot(kind='bar', title="Unika användare per dag (14 dagar)")
|
| 43 |
-
plt.ylabel("Antal användare")
|
| 44 |
-
plt.tight_layout()
|
| 45 |
-
user_graph_path = "daily_users.png"
|
| 46 |
-
plt.savefig(user_graph_path)
|
| 47 |
-
plt.close()
|
| 48 |
-
logging.info(f"Graf sparad: {user_graph_path}")
|
| 49 |
-
|
| 50 |
-
# 2. Meddelanden per timme (72h)
|
| 51 |
-
cutoff = now - timedelta(hours=72)
|
| 52 |
-
df_recent = df[df['timestamp'] >= cutoff]
|
| 53 |
-
hourly = df_recent.groupby(df_recent['timestamp'].dt.floor('H')).size()
|
| 54 |
-
plt.figure(figsize=(10, 4))
|
| 55 |
-
hourly.plot(title="Meddelanden per timme (senaste 72h)")
|
| 56 |
-
plt.ylabel("Antal meddelanden")
|
| 57 |
-
plt.xticks(rotation=45)
|
| 58 |
-
plt.tight_layout()
|
| 59 |
-
hourly_graph_path = "hourly_msgs.png"
|
| 60 |
-
plt.savefig(hourly_graph_path)
|
| 61 |
-
plt.close()
|
| 62 |
-
logging.info(f"Graf sparad: {hourly_graph_path}")
|
| 63 |
-
|
| 64 |
-
return user_graph_path, hourly_graph_path
|
| 65 |
-
|
| 66 |
-
# --- Funktion: Ladda upp bilder till Imgur ---
|
| 67 |
-
def upload_to_imgur(image_path):
|
| 68 |
-
headers = {"Authorization": f"Client-ID {IMGUR_CLIENT_ID}"}
|
| 69 |
-
with open(image_path, 'rb') as img:
|
| 70 |
-
response = requests.post("https://api.imgur.com/3/image", headers=headers, files={"image": img})
|
| 71 |
-
if response.status_code == 200:
|
| 72 |
-
link = response.json()["data"]["link"]
|
| 73 |
-
logging.info(f"Imgur upload success: {link}")
|
| 74 |
-
return link
|
| 75 |
-
else:
|
| 76 |
-
logging.error(f"Imgur upload failed: {response.text}")
|
| 77 |
-
return None
|
| 78 |
-
|
| 79 |
-
# --- Funktion: Skicka Slack-meddelande ---
|
| 80 |
-
def send_to_slack(user_url, hourly_url):
|
| 81 |
-
payload = {
|
| 82 |
-
"text": "📊 Dagliga grafer",
|
| 83 |
-
"attachments": [
|
| 84 |
-
{"title": "Unika användare (14 dagar)", "image_url": user_url},
|
| 85 |
-
{"title": "Meddelanden per timme (72h)", "image_url": hourly_url}
|
| 86 |
-
]
|
| 87 |
-
}
|
| 88 |
-
try:
|
| 89 |
-
response = requests.post(WEBHOOK_URL, json=payload)
|
| 90 |
-
logging.info(f"Slack response status: {response.status_code}")
|
| 91 |
-
logging.info(f"Slack response text: {response.text}")
|
| 92 |
-
response.raise_for_status()
|
| 93 |
-
logging.info("Slack-meddelande postat.")
|
| 94 |
-
except Exception as e:
|
| 95 |
-
logging.error(f"Fel vid Slack-post: {e}", exc_info=True)
|
| 96 |
-
raise
|
| 97 |
|
| 98 |
# --- Konvertera gammal loggtext till DataFrame ---
|
| 99 |
def parse_legacy_log(log_path):
|
|
@@ -123,6 +51,38 @@ def parse_legacy_log(log_path):
|
|
| 123 |
df["platform"] = "legacy"
|
| 124 |
return df
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
# --- Huvudfunktion ---
|
| 127 |
def run_report():
|
| 128 |
try:
|
|
@@ -145,19 +105,9 @@ def run_report():
|
|
| 145 |
logging.warning("Inga loggrader hittades – avbryter.")
|
| 146 |
return "⚠️ Inga loggar att rapportera."
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
return "⚠️ Inga data att rapportera."
|
| 152 |
-
|
| 153 |
-
user_url = upload_to_imgur(user_graph)
|
| 154 |
-
hourly_url = upload_to_imgur(hourly_graph)
|
| 155 |
-
|
| 156 |
-
if user_url and hourly_url:
|
| 157 |
-
send_to_slack(user_url, hourly_url)
|
| 158 |
-
return "✅ Slack-meddelande skickat med grafer."
|
| 159 |
-
else:
|
| 160 |
-
return "⚠️ Kunde inte ladda upp grafer till Imgur."
|
| 161 |
|
| 162 |
except Exception as e:
|
| 163 |
logging.error(f"Fel vid körning: {e}", exc_info=True)
|
|
@@ -174,20 +124,12 @@ def run_schedule():
|
|
| 174 |
import threading
|
| 175 |
threading.Thread(target=run_schedule, daemon=True).start()
|
| 176 |
|
| 177 |
-
# --- Gradio
|
| 178 |
with gr.Blocks() as app:
|
| 179 |
-
gr.Markdown("# Slack Reporter
|
| 180 |
-
gr.
|
| 181 |
-
btn = gr.Button("Skicka nu")
|
| 182 |
output = gr.Textbox()
|
| 183 |
-
|
| 184 |
-
image2 = gr.Image(label="Meddelanden per timme (72h)")
|
| 185 |
-
|
| 186 |
-
def manual_run():
|
| 187 |
-
result = run_report()
|
| 188 |
-
return result, "daily_users.png", "hourly_msgs.png"
|
| 189 |
-
|
| 190 |
-
btn.click(fn=manual_run, outputs=[output, image1, image2])
|
| 191 |
|
| 192 |
if __name__ == "__main__":
|
| 193 |
app.launch()
|
|
|
|
| 1 |
+
# slack_reporter/app.py – fokuserar på nyckeltal utan grafer
|
| 2 |
import os
|
| 3 |
import time
|
| 4 |
import schedule
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
import requests
|
| 7 |
import logging
|
| 8 |
import re
|
|
|
|
| 22 |
LOG_FILENAME = "logs/conversation_log.txt"
|
| 23 |
WEBHOOK_URL = os.environ.get("SLACK_WEBHOOK_URL")
|
| 24 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# --- Konvertera gammal loggtext till DataFrame ---
|
| 27 |
def parse_legacy_log(log_path):
|
|
|
|
| 51 |
df["platform"] = "legacy"
|
| 52 |
return df
|
| 53 |
|
| 54 |
+
# --- Funktion: Skicka Slack-meddelande med nyckeltal ---
|
| 55 |
+
def send_summary_to_slack(summary_text):
|
| 56 |
+
payload = {"text": f"📊 Daglig sammanställning:\n{summary_text}"}
|
| 57 |
+
try:
|
| 58 |
+
response = requests.post(WEBHOOK_URL, json=payload)
|
| 59 |
+
logging.info(f"Slack response status: {response.status_code}")
|
| 60 |
+
logging.info(f"Slack response text: {response.text}")
|
| 61 |
+
response.raise_for_status()
|
| 62 |
+
logging.info("Slack-meddelande postat.")
|
| 63 |
+
except Exception as e:
|
| 64 |
+
logging.error(f"Fel vid Slack-post: {e}", exc_info=True)
|
| 65 |
+
raise
|
| 66 |
+
|
| 67 |
+
# --- Funktion: Bygg nyckeltalstext ---
|
| 68 |
+
def generate_summary(df):
|
| 69 |
+
now = datetime.now()
|
| 70 |
+
yesterday = now - timedelta(days=1)
|
| 71 |
+
last_14 = now - timedelta(days=14)
|
| 72 |
+
|
| 73 |
+
df["timestamp"] = pd.to_datetime(df["timestamp"])
|
| 74 |
+
df_day = df[df["timestamp"] >= yesterday.replace(hour=0, minute=0, second=0)]
|
| 75 |
+
df_14 = df[df["timestamp"] >= last_14]
|
| 76 |
+
|
| 77 |
+
summary = []
|
| 78 |
+
summary.append(f"📅 Datum: {now.strftime('%Y-%m-%d')}")
|
| 79 |
+
summary.append(f"🗨️ Antal meddelanden senaste 24h: {len(df_day)}")
|
| 80 |
+
summary.append(f"👥 Unika sessioner senaste 24h: {df_day['session_id'].nunique()}")
|
| 81 |
+
summary.append(f"🕒 Snittsvarstid senaste 24h: {round(df_day['response_time'].mean(), 2)} sekunder")
|
| 82 |
+
summary.append(f"📊 Antal meddelanden (14 dagar): {len(df_14)}")
|
| 83 |
+
summary.append(f"📈 Unika användare (14 dagar): {df_14['user_id'].nunique()}")
|
| 84 |
+
return "\n".join(summary)
|
| 85 |
+
|
| 86 |
# --- Huvudfunktion ---
|
| 87 |
def run_report():
|
| 88 |
try:
|
|
|
|
| 105 |
logging.warning("Inga loggrader hittades – avbryter.")
|
| 106 |
return "⚠️ Inga loggar att rapportera."
|
| 107 |
|
| 108 |
+
summary = generate_summary(df)
|
| 109 |
+
send_summary_to_slack(summary)
|
| 110 |
+
return "✅ Slack-meddelande skickat."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
except Exception as e:
|
| 113 |
logging.error(f"Fel vid körning: {e}", exc_info=True)
|
|
|
|
| 124 |
import threading
|
| 125 |
threading.Thread(target=run_schedule, daemon=True).start()
|
| 126 |
|
| 127 |
+
# --- Gradio-knapp ---
|
| 128 |
with gr.Blocks() as app:
|
| 129 |
+
gr.Markdown("# Slack Reporter – Nyckeltal")
|
| 130 |
+
btn = gr.Button("Skicka rapport nu")
|
|
|
|
| 131 |
output = gr.Textbox()
|
| 132 |
+
btn.click(fn=run_report, outputs=output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
if __name__ == "__main__":
|
| 135 |
app.launch()
|