Jay-2776 commited on
Commit
4281ddb
Β·
verified Β·
1 Parent(s): e30aeee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -172
app.py CHANGED
@@ -20,103 +20,88 @@ from google.analytics.data_v1beta.types import (
20
 
21
  warnings.filterwarnings("ignore", category=FutureWarning)
22
 
23
- # ==========================================================
24
  # CONFIG
25
- # ==========================================================
26
- SITE_DOMAIN = "rishabhsoft.com" # πŸ”΄ change if needed
27
  GA4_PROPERTY_ID = os.environ["GA4_PROPERTY_ID"]
28
  SERVICE_ACCOUNT_JSON = json.loads(os.environ["SERVICE_ACCOUNT_JSON"])
 
29
 
30
- # ==========================================================
31
- # GA4 CLIENT
32
- # ==========================================================
33
  with open("service_account.json", "w") as f:
34
  json.dump(SERVICE_ACCOUNT_JSON, f)
35
 
36
  creds = service_account.Credentials.from_service_account_file("service_account.json")
37
  ga = BetaAnalyticsDataClient(credentials=creds)
38
 
39
- # ==========================================================
40
  # HELPERS
41
- # ==========================================================
42
- def clean_path(value):
43
- if not value:
44
  return "(unknown)"
45
- parsed = urlparse(value)
46
- path = parsed.path or value
47
- if path == "/":
48
- return "/ (Home)"
49
- return path[:50] + "…" if len(path) > 50 else path
50
 
51
  def classify_source(src):
52
- if not src:
53
  return "External"
54
- if src == "(direct)":
55
- return "External"
56
- if src.startswith("http"):
57
- return "Internal" if SITE_DOMAIN in urlparse(src).netloc else "External"
58
  if src.startswith("/"):
59
  return "Internal"
 
 
60
  return "External"
61
 
62
- # ==========================================================
63
- # FAST PAGE FETCH (CACHED)
64
- # ==========================================================
65
  @lru_cache(maxsize=3)
66
- def fetch_top_page_paths(start, end, limit=300):
67
  req = RunReportRequest(
68
  property=f"properties/{GA4_PROPERTY_ID}",
69
  dimensions=[{"name": "pagePath"}],
70
  metrics=[{"name": "screenPageViews"}],
71
  date_ranges=[{"start_date": start, "end_date": end}],
72
  order_bys=[{"metric": {"metric_name": "screenPageViews"}, "desc": True}],
73
- limit=limit
74
  )
75
  res = ga.run_report(req)
76
- return sorted(
77
- {r.dimension_values[0].value for r in res.rows if r.dimension_values[0].value}
78
- )
79
 
80
- # ==========================================================
81
  # JOURNEY DATA
82
- # ==========================================================
83
- def fetch_journey_paths(start, end, landing_page):
84
  req = RunReportRequest(
85
  property=f"properties/{GA4_PROPERTY_ID}",
86
- dimensions=[{"name": "pagePath"}, {"name": "pageReferrer"}],
87
  metrics=[{"name": "screenPageViews"}],
88
  date_ranges=[{"start_date": start, "end_date": end}],
89
  dimension_filter=FilterExpression(
90
  filter=Filter(
91
  field_name="landingPage",
92
- string_filter={
93
- "match_type": 4,
94
- "value": landing_page,
95
- "case_sensitive": False
96
- }
97
  )
98
  ),
99
  limit=3000
100
  )
101
 
102
- res = ga.run_report(req)
103
  rows = []
104
- for r in res.rows:
105
  rows.append({
106
- "From": r.dimension_values[1].value or "(direct)",
107
- "To": r.dimension_values[0].value,
108
  "Views": int(r.metric_values[0].value)
109
  })
 
110
  return pd.DataFrame(rows)
111
 
112
- # ==========================================================
113
- # FORM SUBMISSIONS (GA4-CORRECT PROXY)
114
- # ==========================================================
115
- def get_form_submissions_for_page(start, end, landing_page):
116
- """
117
- Counts form submissions for users who STARTED on the selected landing page.
118
- This is the most accurate GA4 API approach without BigQuery.
119
- """
120
  req = RunReportRequest(
121
  property=f"properties/{GA4_PROPERTY_ID}",
122
  dimensions=[{"name": "landingPage"}],
@@ -140,133 +125,109 @@ def get_form_submissions_for_page(start, end, landing_page):
140
  FilterExpression(
141
  filter=Filter(
142
  field_name="landingPage",
143
- string_filter={
144
- "match_type": 4,
145
- "value": landing_page,
146
- "case_sensitive": False
147
- }
148
  )
149
  )
150
  ])
151
- ),
152
- limit=100
153
  )
154
-
155
  res = ga.run_report(req)
156
  return sum(int(r.metric_values[0].value) for r in res.rows)
157
 
158
- # ==========================================================
159
- # MAIN JOURNEY LOGIC
160
- # ==========================================================
161
  def run_journey(start, end, landing_page):
162
- df = fetch_journey_paths(start, end, landing_page)
163
  if df.empty:
164
- return None, pd.DataFrame(), "No journey data found."
165
-
166
- # Reduce noise (top 80% traffic)
167
- df = df.sort_values("Views", ascending=False)
168
- df["cum_pct"] = df["Views"].cumsum() / df["Views"].sum()
169
- df = df[df["cum_pct"] <= 0.80]
170
 
171
  total_users = df["Views"].sum()
172
- form_yes = get_form_submissions_for_page(start, end, landing_page)
173
- form_no = max(total_users - form_yes, 0)
174
 
175
- # ======================================================
176
  # EXIT TABLE
177
- # ======================================================
178
- exit_table = df.groupby("From")["Views"].sum().reset_index()
179
- exit_table.columns = ["Source", "Users Exited"]
180
- exit_table["Users Entered"] = exit_table["Users Exited"]
181
- exit_table["Exit Rate %"] = 100.0
182
- exit_table["Source Type"] = exit_table["Source"].apply(classify_source)
183
- exit_table["Exit Source / Page"] = exit_table["Source"].apply(clean_path)
184
-
185
- def form_flag(src):
186
- return (
187
- "Yes"
188
- if clean_path(src) == clean_path(landing_page) and form_yes > 0
189
- else "No"
190
- )
191
-
192
- exit_table["Form Submitted?"] = exit_table["Source"].apply(form_flag)
193
-
194
- def insight(row):
195
- if row["Form Submitted?"] == "Yes":
196
- return "Converted before exit"
197
- if row["Source Type"] == "External":
198
- return "High exit – landing intent mismatch"
199
- return "Conversion leak – improve CTA"
200
 
201
- exit_table["Insight"] = exit_table.apply(insight, axis=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
- exit_table = exit_table[
204
  [
205
  "Exit Source / Page",
206
  "Source Type",
207
  "Users Entered",
208
  "Users Exited",
209
  "Exit Rate %",
210
- "Form Submitted?",
 
211
  "Insight"
212
  ]
213
  ].sort_values("Users Exited", ascending=False)
214
 
215
- # ======================================================
216
  # SANKEY
217
- # ======================================================
218
- NODE_COLORS = {
219
- "entry": "rgba(59,130,246,0.85)",
220
- "page": "rgba(107,114,128,0.75)",
221
- "exit": "rgba(239,68,68,0.9)",
222
- "form": "rgba(34,197,94,0.9)"
223
- }
224
-
225
- labels, node_colors, idx = [], [], {}
226
-
227
- def add_node(name, t):
228
- name = clean_path(name)
229
- if name not in idx:
230
- idx[name] = len(labels)
231
- labels.append(name)
232
- node_colors.append(NODE_COLORS[t])
233
- return idx[name]
234
-
235
- sources, targets, values, colors = [], [], [], []
236
 
237
  for _, r in df.iterrows():
238
- s = add_node(r["From"], "entry")
239
- t = add_node(r["To"], "page")
240
- sources.append(s)
241
- targets.append(t)
242
- values.append(r["Views"])
243
- colors.append("rgba(156,163,175,0.4)")
244
 
245
- page_node = add_node(landing_page, "page")
 
 
 
 
246
 
247
  if form_yes > 0:
248
- f_node = add_node("Form Submitted", "form")
249
- sources.append(page_node)
250
- targets.append(f_node)
251
- values.append(form_yes)
252
- colors.append("rgba(34,197,94,0.6)")
253
-
254
- e_node = add_node("Exit", "exit")
255
- sources.append(page_node)
256
- targets.append(e_node)
257
- values.append(form_no)
258
- colors.append("rgba(239,68,68,0.6)")
259
 
260
  fig = go.Figure(go.Sankey(
261
- arrangement="snap",
262
- node=dict(label=labels, color=node_colors, pad=22, thickness=18),
263
- link=dict(source=sources, target=targets, value=values, color=colors)
264
  ))
265
 
266
  fig.update_layout(
267
- title="Customer Journey Flow<br><sup>Entry β†’ Page β†’ Exit / Form</sup>",
268
- height=650,
269
- font=dict(size=11)
270
  )
271
 
272
  summary = f"""
@@ -274,51 +235,39 @@ def run_journey(start, end, landing_page):
274
  **Start Page:** `{clean_path(landing_page)}`
275
  **Date Range:** {start} β†’ {end}
276
 
277
- - βœ… **Form Submitted:** {form_yes}
278
- - ❌ **No Form Before Exit:** {form_no}
 
279
  """
280
 
281
- return fig, exit_table, summary
282
 
283
- # ==========================================================
284
  # UI
285
- # ==========================================================
286
  with gr.Blocks() as app:
287
- gr.Markdown("## πŸš€ Customer Journey Explorer (GA4)")
288
 
289
  with gr.Row():
290
- sd = gr.Textbox(label="Start Date", value=str(date.today() - timedelta(days=30)))
291
- ed = gr.Textbox(label="End Date", value=str(date.today()))
292
-
293
- page_dd = gr.Dropdown(
294
- label="Starting Page Path",
295
- choices=[],
296
- allow_custom_value=True,
297
- interactive=True
298
- )
299
 
300
  with gr.Row():
301
- load_btn = gr.Button("⚑ Load Top Pages")
302
- run_btn = gr.Button("Analyze Journey", variant="primary")
303
 
304
  chart = gr.Plot()
305
- exit_df = gr.Dataframe()
306
- summary_md = gr.Markdown()
307
 
308
- load_btn.click(
309
- lambda s, e: gr.update(choices=fetch_top_page_paths(s, e)),
310
- inputs=[sd, ed],
311
- outputs=page_dd
312
- )
313
 
314
- run_btn.click(
315
- run_journey,
316
- inputs=[sd, ed, page_dd],
317
- outputs=[chart, exit_df, summary_md]
318
- )
319
 
320
- # ==========================================================
321
- # LAUNCH
322
- # ==========================================================
323
  if __name__ == "__main__":
324
  app.launch()
 
20
 
21
  warnings.filterwarnings("ignore", category=FutureWarning)
22
 
23
+ # =====================================================
24
  # CONFIG
25
+ # =====================================================
 
26
  GA4_PROPERTY_ID = os.environ["GA4_PROPERTY_ID"]
27
  SERVICE_ACCOUNT_JSON = json.loads(os.environ["SERVICE_ACCOUNT_JSON"])
28
+ SITE_DOMAIN = "rishabhsoft.com" # change if required
29
 
30
+ # =====================================================
31
+ # GA CLIENT
32
+ # =====================================================
33
  with open("service_account.json", "w") as f:
34
  json.dump(SERVICE_ACCOUNT_JSON, f)
35
 
36
  creds = service_account.Credentials.from_service_account_file("service_account.json")
37
  ga = BetaAnalyticsDataClient(credentials=creds)
38
 
39
+ # =====================================================
40
  # HELPERS
41
+ # =====================================================
42
+ def clean_path(v):
43
+ if not v:
44
  return "(unknown)"
45
+ p = urlparse(v).path or v
46
+ return "/ (Home)" if p == "/" else p
 
 
 
47
 
48
  def classify_source(src):
49
+ if not src or src == "(direct)":
50
  return "External"
 
 
 
 
51
  if src.startswith("/"):
52
  return "Internal"
53
+ if src.startswith("http"):
54
+ return "Internal" if SITE_DOMAIN in urlparse(src).netloc else "External"
55
  return "External"
56
 
57
+ # =====================================================
58
+ # CACHED TOP PAGES
59
+ # =====================================================
60
  @lru_cache(maxsize=3)
61
+ def fetch_top_pages(start, end):
62
  req = RunReportRequest(
63
  property=f"properties/{GA4_PROPERTY_ID}",
64
  dimensions=[{"name": "pagePath"}],
65
  metrics=[{"name": "screenPageViews"}],
66
  date_ranges=[{"start_date": start, "end_date": end}],
67
  order_bys=[{"metric": {"metric_name": "screenPageViews"}, "desc": True}],
68
+ limit=300
69
  )
70
  res = ga.run_report(req)
71
+ return sorted({r.dimension_values[0].value for r in res.rows})
 
 
72
 
73
+ # =====================================================
74
  # JOURNEY DATA
75
+ # =====================================================
76
+ def fetch_journey(start, end, landing_page):
77
  req = RunReportRequest(
78
  property=f"properties/{GA4_PROPERTY_ID}",
79
+ dimensions=[{"name": "pageReferrer"}, {"name": "pagePath"}],
80
  metrics=[{"name": "screenPageViews"}],
81
  date_ranges=[{"start_date": start, "end_date": end}],
82
  dimension_filter=FilterExpression(
83
  filter=Filter(
84
  field_name="landingPage",
85
+ string_filter={"match_type": 4, "value": landing_page}
 
 
 
 
86
  )
87
  ),
88
  limit=3000
89
  )
90
 
 
91
  rows = []
92
+ for r in ga.run_report(req).rows:
93
  rows.append({
94
+ "From": r.dimension_values[0].value or "(direct)",
95
+ "To": r.dimension_values[1].value,
96
  "Views": int(r.metric_values[0].value)
97
  })
98
+
99
  return pd.DataFrame(rows)
100
 
101
+ # =====================================================
102
+ # FORM SUBMISSIONS (GA4-SAFE PROXY)
103
+ # =====================================================
104
+ def get_form_submissions(start, end, landing_page):
 
 
 
 
105
  req = RunReportRequest(
106
  property=f"properties/{GA4_PROPERTY_ID}",
107
  dimensions=[{"name": "landingPage"}],
 
125
  FilterExpression(
126
  filter=Filter(
127
  field_name="landingPage",
128
+ string_filter={"match_type": 4, "value": landing_page}
 
 
 
 
129
  )
130
  )
131
  ])
132
+ )
 
133
  )
 
134
  res = ga.run_report(req)
135
  return sum(int(r.metric_values[0].value) for r in res.rows)
136
 
137
+ # =====================================================
138
+ # MAIN LOGIC
139
+ # =====================================================
140
  def run_journey(start, end, landing_page):
141
+ df = fetch_journey(start, end, landing_page)
142
  if df.empty:
143
+ return None, pd.DataFrame(), "No data found."
 
 
 
 
 
144
 
145
  total_users = df["Views"].sum()
146
+ form_yes = get_form_submissions(start, end, landing_page)
147
+ journey_converted = "Yes" if form_yes > 0 else "No"
148
 
149
+ # ===========================
150
  # EXIT TABLE
151
+ # ===========================
152
+ exit_df = (
153
+ df.groupby("From")["Views"]
154
+ .sum()
155
+ .reset_index()
156
+ .rename(columns={"From": "Exit Source / Page", "Views": "Users Exited"})
157
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
+ exit_df["Users Entered"] = exit_df["Users Exited"]
160
+ exit_df["Exit Rate %"] = 100
161
+ exit_df["Source Type"] = exit_df["Exit Source / Page"].apply(classify_source)
162
+ exit_df["Exit Source / Page"] = exit_df["Exit Source / Page"].apply(clean_path)
163
+
164
+ # πŸ”‘ Option C logic
165
+ exit_df["Journey Converted?"] = journey_converted
166
+ exit_df["Form Submitted Before Exit?"] = "No"
167
+
168
+ exit_df["Insight"] = exit_df.apply(
169
+ lambda r:
170
+ "Converted journey – exit after intent met"
171
+ if r["Journey Converted?"] == "Yes"
172
+ else (
173
+ "High exit – landing intent mismatch"
174
+ if r["Source Type"] == "External"
175
+ else "Conversion leak – improve CTA"
176
+ ),
177
+ axis=1
178
+ )
179
 
180
+ exit_df = exit_df[
181
  [
182
  "Exit Source / Page",
183
  "Source Type",
184
  "Users Entered",
185
  "Users Exited",
186
  "Exit Rate %",
187
+ "Journey Converted?",
188
+ "Form Submitted Before Exit?",
189
  "Insight"
190
  ]
191
  ].sort_values("Users Exited", ascending=False)
192
 
193
+ # ===========================
194
  # SANKEY
195
+ # ===========================
196
+ labels, idx = [], {}
197
+
198
+ def add(n):
199
+ if n not in idx:
200
+ idx[n] = len(labels)
201
+ labels.append(n)
202
+ return idx[n]
203
+
204
+ s, t, v = [], [], []
 
 
 
 
 
 
 
 
 
205
 
206
  for _, r in df.iterrows():
207
+ s.append(add(clean_path(r["From"])))
208
+ t.append(add(clean_path(r["To"])))
209
+ v.append(r["Views"])
 
 
 
210
 
211
+ p = add(clean_path(landing_page))
212
+ e = add("Exit")
213
+ s.append(p)
214
+ t.append(e)
215
+ v.append(total_users - form_yes)
216
 
217
  if form_yes > 0:
218
+ f = add("Form Submitted")
219
+ s.append(p)
220
+ t.append(f)
221
+ v.append(form_yes)
 
 
 
 
 
 
 
222
 
223
  fig = go.Figure(go.Sankey(
224
+ node=dict(label=labels, pad=22, thickness=18),
225
+ link=dict(source=s, target=t, value=v)
 
226
  ))
227
 
228
  fig.update_layout(
229
+ title="Customer Journey Flow (Entry β†’ Exit / Conversion)",
230
+ height=650
 
231
  )
232
 
233
  summary = f"""
 
235
  **Start Page:** `{clean_path(landing_page)}`
236
  **Date Range:** {start} β†’ {end}
237
 
238
+ - **Journey Converted:** {journey_converted}
239
+ - **Form Submissions:** {form_yes}
240
+ - **Exited Without Form:** {total_users - form_yes}
241
  """
242
 
243
+ return fig, exit_df, summary
244
 
245
+ # =====================================================
246
  # UI
247
+ # =====================================================
248
  with gr.Blocks() as app:
249
+ gr.Markdown("## πŸš€ Customer Journey Explorer (GA4 – Business View)")
250
 
251
  with gr.Row():
252
+ sd = gr.Textbox(value=str(date.today() - timedelta(days=30)), label="Start Date")
253
+ ed = gr.Textbox(value=str(date.today()), label="End Date")
254
+
255
+ page_dd = gr.Dropdown(label="Starting Page", allow_custom_value=True)
 
 
 
 
 
256
 
257
  with gr.Row():
258
+ load = gr.Button("⚑ Load Top Pages")
259
+ run = gr.Button("Analyze Journey", variant="primary")
260
 
261
  chart = gr.Plot()
262
+ table = gr.Dataframe()
263
+ summary = gr.Markdown()
264
 
265
+ load.click(lambda s, e: gr.update(choices=fetch_top_pages(s, e)),
266
+ [sd, ed], page_dd)
 
 
 
267
 
268
+ run.click(run_journey,
269
+ [sd, ed, page_dd],
270
+ [chart, table, summary])
 
 
271
 
 
 
 
272
  if __name__ == "__main__":
273
  app.launch()