File size: 8,090 Bytes
7e61a73
 
4d2fd83
 
43e0c2d
9b96a20
b91e3df
7e61a73
4d2fd83
 
7e61a73
48407e5
bbf108c
7e61a73
4d2fd83
7e61a73
92fd5a6
 
 
 
 
4d2fd83
92fd5a6
4d2fd83
 
92fd5a6
 
 
4d2fd83
 
92fd5a6
 
4d2fd83
92fd5a6
4d2fd83
 
 
92fd5a6
 
4d2fd83
92fd5a6
4d2fd83
 
92fd5a6
 
4d2fd83
 
92fd5a6
 
fc9f8af
92fd5a6
 
4d2fd83
92fd5a6
4d2fd83
 
 
92fd5a6
 
 
4d2fd83
92fd5a6
 
 
4d2fd83
 
92fd5a6
4d2fd83
92fd5a6
 
4d2fd83
 
 
92fd5a6
4d2fd83
92fd5a6
4d2fd83
 
92fd5a6
4d2fd83
92fd5a6
4d2fd83
 
 
92fd5a6
 
4d2fd83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fbf909
4d2fd83
 
 
4fbf909
 
4d2fd83
 
4fbf909
4d2fd83
 
 
 
 
4fbf909
4d2fd83
4fbf909
4d2fd83
 
 
 
 
 
 
4fbf909
bbf108c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d2fd83
 
 
92fd5a6
4d2fd83
 
 
92fd5a6
 
4d2fd83
bbf108c
 
 
4d2fd83
 
 
 
 
 
 
92fd5a6
 
bbf108c
92fd5a6
 
4d2fd83
 
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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import json
import requests
from datetime import datetime, timezone, timedelta
import matplotlib.pyplot as plt
import gradio as gr
import traceback
import html

from sessions import create_session
from error_handling import display_error

from Data_Fetching_and_Rendering import fetch_posts_and_stats

API_V2_BASE = 'https://api.linkedin.com/v2'
API_REST_BASE = 'https://api.linkedin.com/rest'

def extract_follower_gains(data):
    elements = data.get("elements", [])
    if not elements:
        return []

    results = []
    for item in elements:
        start_timestamp = item.get("timeRange", {}).get("start")
        if not start_timestamp:
            continue

        try:
            date_str = datetime.fromtimestamp(start_timestamp / 1000, tz=timezone.utc).strftime('%Y-%m')
        except Exception:
            continue

        gains = item.get("followerGains", {})
        results.append({
            "date": date_str,
            "organic": gains.get("organicFollowerGain", 0) or 0,
            "paid": gains.get("paidFollowerGain", 0) or 0
        })

    return sorted(results, key=lambda x: x['date'])

def fetch_analytics_data(client_id, token):
    if not token:
        raise ValueError("comm_token is missing.")

    token_dict = token if isinstance(token, dict) else {'access_token': token, 'token_type': 'Bearer'}
    session = create_session(client_id, token=token_dict)

    try:
        org_urn, org_name = "urn:li:organization:19010008", "GRLS"

        count_url = f"{API_V2_BASE}/networkSizes/{org_urn}?edgeType=CompanyFollowedByMember"
        follower_count = session.get(count_url).json().get("firstDegreeSize", 0)

        start = datetime.now(timezone.utc) - timedelta(days=365)
        start = start.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        start_ms = int(start.timestamp() * 1000)

        gains_url = (
            f"{API_REST_BASE}/organizationalEntityFollowerStatistics"
            f"?q=organizationalEntity&organizationalEntity={org_urn}"
            f"&timeIntervals.timeGranularityType=MONTH"
            f"&timeIntervals.timeRange.start={start_ms}"
        )
        gains_data = session.get(gains_url).json()
        gains = extract_follower_gains(gains_data)

        return org_name, follower_count, gains

    except requests.exceptions.RequestException as e:
        status = getattr(e.response, 'status_code', 'N/A')
        msg = f"Failed to fetch LinkedIn analytics (Status: {status})."
        raise ValueError(msg) from e
    except Exception as e:
        raise ValueError("Unexpected error during LinkedIn analytics fetch.") from e

def plot_follower_gains(data):
    plt.style.use('seaborn-v0_8-whitegrid')

    if not data:
        fig, ax = plt.subplots(figsize=(10, 5))
        ax.text(0.5, 0.5, 'No follower gains data.', ha='center', va='center', transform=ax.transAxes)
        ax.set_title('Monthly Follower Gains')
        ax.set_xticks([]); ax.set_yticks([])
        return fig

    dates = [d['date'] for d in data]
    organic = [d['organic'] for d in data]
    paid = [d['paid'] for d in data]

    fig, ax = plt.subplots(figsize=(12, 6))
    ax.plot(dates, organic, label='Organic', marker='o', color='#0073b1')
    ax.plot(dates, paid, label='Paid', marker='x', linestyle='--', color='#d9534f')
    ax.set(title='Monthly Follower Gains', xlabel='Month', ylabel='New Followers')
    ax.tick_params(axis='x', rotation=45)
    ax.legend()
    plt.tight_layout()
    return fig

def plot_growth_rate(data, total):
    if not data:
        fig, ax = plt.subplots(figsize=(10, 5))
        ax.text(0.5, 0.5, 'No data for growth rate.', ha='center', va='center', transform=ax.transAxes)
        ax.set_title('Growth Rate (%)')
        ax.set_xticks([]); ax.set_yticks([])
        return fig

    dates = [d['date'] for d in data]
    gains = [d['organic'] + d['paid'] for d in data]

    history = []
    current = total
    for g in reversed(gains):
        history.insert(0, current)
        current -= g

    rates = [((history[i] - history[i-1]) / history[i-1] * 100 if history[i-1] else 0) for i in range(1, len(history))]

    fig, ax = plt.subplots(figsize=(12, 6))
    ax.plot(dates[1:], rates, label='Growth Rate (%)', marker='o', color='green')
    ax.set(title='Monthly Growth Rate (%)', xlabel='Month', ylabel='Growth %')
    ax.tick_params(axis='x', rotation=45)
    ax.legend()
    plt.tight_layout()
    return fig

def compute_monthly_avg_engagement_rate(posts):
    from collections import defaultdict
    import statistics

    if not posts:
        return []

    monthly_data = defaultdict(lambda: {"engagement_sum": 0, "post_count": 0, "impression_total": 0})

    for post in posts:
        try:
            month = post["when"][:7]  # Format: YYYY-MM
            likes = post.get("likes", 0)
            comments = post.get("comments", 0)
            shares = post.get("shares", 0)
            clicks = post.get("clicks", 0)
            impressions = post.get("impressions", 0)

            engagement = likes + comments + shares + clicks
            monthly_data[month]["engagement_sum"] += engagement
            monthly_data[month]["post_count"] += 1
            monthly_data[month]["impression_total"] += impressions
        except Exception:
            continue

    results = []
    for month in sorted(monthly_data.keys()):
        data = monthly_data[month]
        if data["post_count"] == 0 or data["impression_total"] == 0:
            rate = 0
        else:
            avg_impressions = data["impression_total"] / data["post_count"]
            rate = (data["engagement_sum"] / (data["post_count"] * avg_impressions)) * 100
        results.append({"month": month, "engagement_rate": round(rate, 2)})

    return results

def plot_avg_engagement_rate(data):
    import matplotlib.pyplot as plt

    if not data:
        fig, ax = plt.subplots(figsize=(10, 5))
        ax.text(0.5, 0.5, 'No engagement data.', ha='center', va='center', transform=ax.transAxes)
        ax.set_title('Average Post Engagement Rate (%)')
        ax.set_xticks([]); ax.set_yticks([])
        return fig

    months = [d["month"] for d in data]
    rates = [d["engagement_rate"] for d in data]

    fig, ax = plt.subplots(figsize=(12, 6))
    ax.plot(months, rates, label="Engagement Rate (%)", marker="s", color="#ff7f0e")
    ax.set(title="Average Post Engagement Rate (%)", xlabel="Month", ylabel="Engagement Rate %")
    ax.tick_params(axis='x', rotation=45)
    ax.legend()
    plt.tight_layout()
    return fig


def fetch_and_render_analytics(client_id, token):
    loading = gr.update(value="<p>Loading follower count...</p>", visible=True)
    hidden = gr.update(value=None, visible=False)

    if not token:
        error = "<p style='color:red;'>❌ Missing token. Please log in.</p>"
        return gr.update(value=error, visible=True), hidden, hidden

    try:
        name, count, gains = fetch_analytics_data(client_id, token)
        posts, org_name, sentiments = fetch_posts_and_stats(client_id, token, count=30)
        engagement_data = compute_monthly_avg_engagement_rate(posts)
 

        count_html = f"""
        <div style='text-align:center; padding:20px; background:#e7f3ff; border:1px solid #bce8f1; border-radius:8px;'>
            <p style='font-size:1.1em; color:#31708f;'>Total Followers for</p>
            <p style='font-size:1.4em; font-weight:bold; color:#005a9e;'>{html.escape(name)}</p>
            <p style='font-size:2.8em; font-weight:bold; color:#0073b1;'>{count:,}</p>
            <p style='font-size:0.9em; color:#777;'>(As of latest data)</p>
        </div>
        """
        return gr.update(value=count_html, visible=True), gr.update(value=plot_follower_gains(gains), visible=True), gr.update(value=plot_growth_rate(gains, count), visible=True), gr.update(value=plot_avg_engagement_rate(engagement_data), visible=True)

    except Exception as e:
        error = display_error("Analytics load failed.", e).get('value', "<p style='color:red;'>Error loading data.</p>")
        return gr.update(value=error, visible=True), hidden, hidden