Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,120 +1,136 @@
|
|
| 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 |
-
|
| 9 |
-
from
|
| 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 |
-
plt.
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
api
|
| 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 |
app.launch()
|
|
|
|
| 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 |
+
from datetime import datetime, timedelta
|
| 10 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
# --- Loggning ---
|
| 14 |
+
logging.basicConfig(
|
| 15 |
+
filename="slack_reporter.log",
|
| 16 |
+
level=logging.INFO,
|
| 17 |
+
format="%(asctime)s %(levelname)s %(message)s"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
# --- Konfiguration ---
|
| 21 |
+
REPO_ID = "ChargeNodeEurope/logfiles"
|
| 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 |
+
# --- Funktion: Skapa grafer ---
|
| 27 |
+
def generate_graphs(df):
|
| 28 |
+
now = datetime.now()
|
| 29 |
+
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
| 30 |
+
|
| 31 |
+
# 1. Unika användare per dag (14 dagar)
|
| 32 |
+
daily_users = df.groupby(df['timestamp'].dt.date)['user_id'].nunique()
|
| 33 |
+
daily_users = daily_users.last("14D")
|
| 34 |
+
plt.figure(figsize=(8,4))
|
| 35 |
+
daily_users.plot(kind='bar', title="Unika användare per dag (14 dagar)")
|
| 36 |
+
plt.ylabel("Antal användare")
|
| 37 |
+
plt.tight_layout()
|
| 38 |
+
user_graph_path = "daily_users.png"
|
| 39 |
+
plt.savefig(user_graph_path)
|
| 40 |
+
plt.close()
|
| 41 |
+
|
| 42 |
+
# 2. Meddelanden per timme (72h)
|
| 43 |
+
cutoff = now - timedelta(hours=72)
|
| 44 |
+
df_recent = df[df['timestamp'] >= cutoff]
|
| 45 |
+
hourly = df_recent.groupby(df_recent['timestamp'].dt.floor('H')).size()
|
| 46 |
+
plt.figure(figsize=(10,4))
|
| 47 |
+
hourly.plot(title="Meddelanden per timme (senaste 72h)")
|
| 48 |
+
plt.ylabel("Antal meddelanden")
|
| 49 |
+
plt.xticks(rotation=45)
|
| 50 |
+
plt.tight_layout()
|
| 51 |
+
hourly_graph_path = "hourly_msgs.png"
|
| 52 |
+
plt.savefig(hourly_graph_path)
|
| 53 |
+
plt.close()
|
| 54 |
+
|
| 55 |
+
return user_graph_path, hourly_graph_path
|
| 56 |
+
|
| 57 |
+
# --- Funktion: Ladda upp grafer till Hugging Face Hub ---
|
| 58 |
+
def upload_graphs_to_hub(user_graph_path, hourly_graph_path):
|
| 59 |
+
api = HfApi()
|
| 60 |
+
api.upload_file(
|
| 61 |
+
path_or_fileobj=user_graph_path,
|
| 62 |
+
path_in_repo="graphs/daily_users.png",
|
| 63 |
+
repo_id=REPO_ID,
|
| 64 |
+
repo_type="dataset",
|
| 65 |
+
token=HF_TOKEN
|
| 66 |
+
)
|
| 67 |
+
api.upload_file(
|
| 68 |
+
path_or_fileobj=hourly_graph_path,
|
| 69 |
+
path_in_repo="graphs/hourly_msgs.png",
|
| 70 |
+
repo_id=REPO_ID,
|
| 71 |
+
repo_type="dataset",
|
| 72 |
+
token=HF_TOKEN
|
| 73 |
+
)
|
| 74 |
+
return (
|
| 75 |
+
f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/graphs/daily_users.png",
|
| 76 |
+
f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/graphs/hourly_msgs.png"
|
| 77 |
+
)
|
| 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 |
+
response.raise_for_status()
|
| 91 |
+
logging.info("Slack-meddelande postat.")
|
| 92 |
+
except Exception as e:
|
| 93 |
+
logging.error(f"Fel vid Slack-post: {e}", exc_info=True)
|
| 94 |
+
raise
|
| 95 |
+
|
| 96 |
+
# --- Huvudfunktion ---
|
| 97 |
+
def run_report():
|
| 98 |
+
try:
|
| 99 |
+
logging.info("Startar rapportgenerering...")
|
| 100 |
+
log_path = hf_hub_download(
|
| 101 |
+
repo_id=REPO_ID,
|
| 102 |
+
filename=LOG_FILENAME,
|
| 103 |
+
repo_type="dataset",
|
| 104 |
+
token=HF_TOKEN
|
| 105 |
+
)
|
| 106 |
+
df = pd.read_json(log_path, lines=True)
|
| 107 |
+
user_graph, hourly_graph = generate_graphs(df)
|
| 108 |
+
user_url, hourly_url = upload_graphs_to_hub(user_graph, hourly_graph)
|
| 109 |
+
send_to_slack(user_url, hourly_url)
|
| 110 |
+
logging.info("Rapport skickad till Slack.")
|
| 111 |
+
return "✅ Slack-meddelande skickat med grafer."
|
| 112 |
+
except Exception as e:
|
| 113 |
+
logging.error(f"Fel vid körning: {e}", exc_info=True)
|
| 114 |
+
return f"❌ Fel vid körning: {e}"
|
| 115 |
+
|
| 116 |
+
# --- Schemaläggning ---
|
| 117 |
+
schedule.every().day.at("08:20").do(run_report)
|
| 118 |
+
|
| 119 |
+
def run_schedule():
|
| 120 |
+
while True:
|
| 121 |
+
schedule.run_pending()
|
| 122 |
+
time.sleep(60)
|
| 123 |
+
|
| 124 |
+
import threading
|
| 125 |
+
threading.Thread(target=run_schedule, daemon=True).start()
|
| 126 |
+
|
| 127 |
+
# --- Gradio-knapp för manuell körning ---
|
| 128 |
+
with gr.Blocks() as app:
|
| 129 |
+
gr.Markdown("# Slack Reporter - ChargeNode")
|
| 130 |
+
gr.Markdown("Tryck på knappen för att generera dagens rapport och posta till Slack.")
|
| 131 |
+
btn = gr.Button("Skicka nu")
|
| 132 |
+
output = gr.Textbox()
|
| 133 |
+
btn.click(fn=run_report, outputs=output)
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
app.launch()
|