File size: 2,010 Bytes
3802c42
 
 
 
 
 
27a5561
3802c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27a5561
 
 
 
 
3802c42
 
27a5561
3802c42
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt
import json
from io import BytesIO
from datetime import datetime
from PIL import Image, ImageDraw

def load_usage_data():
    """load usage_log.json file to be DataFrame"""
    try:
        with open("usage_log.json", "r") as f:
            data = json.load(f)
        if not data.get("runs"):
            return None

        df = pd.DataFrame(data["runs"])
        df["timestamp"] = pd.to_datetime(df["timestamp"], errors='coerce')
        df.dropna(subset=["timestamp"], inplace=True)
        df["date"] = df["timestamp"].dt.date
        return df
    except Exception as e:
        print(f"Error loading usage data: {e}")
        return None

def plot_daily_usage(df):
    try:
        counts = df.groupby("date").size()
        fig, ax = plt.subplots(figsize=(8, 4))
        counts.plot(kind="bar", ax=ax, color="#4A90E2")
        ax.set_title("Daily Usage of PawMatch AI")
        ax.set_xlabel("Date")
        ax.set_ylabel("Runs")
        ax.grid(axis='y', linestyle='--', alpha=0.7)
        plt.xticks(rotation=45)
        plt.tight_layout()

        buf = BytesIO()
        plt.savefig(buf, format="png")
        plt.close(fig)
        buf.seek(0)
        return buf
    except Exception as e:
        return f"Error generating plot: {e}"

def create_analytics_tab():
    def generate_plot():
        df = load_usage_data()
        if df is None or df.empty:
            img = Image.new("RGB", (600, 200), color=(255, 255, 255))
            draw = ImageDraw.Draw(img)
            draw.text((20, 80), "No usage data available.", fill=(0, 0, 0))
            return img
    
        return plot_daily_usage(df)


    with gr.Tab("\ud83d\udcca Usage Analytics"):
        gr.Markdown("### Daily Usage Trend of PawMatch AI")
        with gr.Row():
            img = gr.Image(type="pil", label="Daily Usage", show_label=True)
        plot_btn = gr.Button("\ud83d\udd04 Refresh")

        plot_btn.click(fn=generate_plot, outputs=[img])