Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Google Play Vitals Monitor & LLM Reporter

Turn Google Play data into decisions — trends, engagement, monetization, and only then stability.

This tool pulls your apps' Play vitals (ANRs, crashes, slow starts, memory, LMK, background wakelocks), your AdMob revenue data, your Play Console install/uninstall/rating/store metrics and the latest user reviews, then uses an LLM (Gemini, DeepSeek, or any OpenAI-compatible/local model) to write a plain-language report with computed trends and concrete recommendations — no dashboard digging required.

The important design choice: the model never does the arithmetic. analysis.py computes the trends (direction, % change, R², spikes, weekly rollups, cross-source correlations) and the LLM only writes prose about numbers that are already correct. That is what stops these reports from being a restatement of a table ("crash rate was 0.00% on Monday, 0.00% on Tuesday...") and what makes weak signals — like a 12% decline in sessions while stability stays perfect — actually visible.

✨ Highlights

  • 📈 Real trend detection, not table narration — every metric gets a direction, a percentage change, an R² and a weekly line, computed deterministically before the LLM sees it.
  • 🧩 Multi-source reports — vitals + AdMob + Play Console engagement + reviews are joined per app and period, so "earnings fell because eCPM fell, not because users left" becomes sayable.
  • 🙈 Zero-metric fatigue handled — metrics that stayed at zero are collapsed into one line instead of a paragraph each, leaving room for engagement and revenue.
  • 🌱 Engagement signals — active users (and the caveat that Play rounds them), launches, launch penetration, install/uninstall trend, ratings, store conversion, install-to-active-user ratio.
  • 💰 AdMob monetization — impressions, clicks, earnings, eCPM, match/show rates, revenue decomposition, plus ad requests as a session-volume proxy (user-OAuth based).
  • 🚦 Polite by default — every LLM call has a timeout, bounded retries with backoff, and pacing between calls, so a slow API cannot freeze your terminal.
  • 🔒 No secrets stored — credentials live in your local .env; nothing is committed.
  • 🧩 Extensible — a new data source only needs to produce daily series; the trend engine and the prompt contract do the rest.

🚀 Quick demo

Once configured (see Setup Guide), a single run gives you everything:

./weekly_report.sh --reviews

That one command fetches 28 days of vitals (a shorter window cannot separate a trend from weekly noise), pulls reviews, attaches any AdMob and Play Console export it finds, and writes one report per app that looks like this:

## TL;DR
- Earnings −31.5% vs the first half of the period, driven by eCPM (−23.7%), not by traffic.
- Ad requests (session proxy) −10.7%, R²=0.53 — the user base is quietly shrinking while
  active-user counts stay flat, because Play rounds them to multiples of 10.
- Stability is not the story: crash/ANR rates stayed at ~0%.

## Engagement & Growth ... ## Monetization ... ## Stability & Performance ...
## What Changed & When ... ## Actions ... ## Data Quality & Caveats

Full sample output: examples/example_report.md · Data structure: examples/example_data.json


Table of Contents


How It Works

   Play Developer Reporting API ─┐
   AdMob API (user OAuth) ───────┤     ┌───────────────┐   ┌─────────────┐   ┌────────────────────┐
   Play Console GCS exports ─────┼────▶│  fetch_*.py   │──▶│ analysis.py │──▶│ generate_report.py │
   Android Publisher (reviews) ──┘     │ data/*.json   │   │ facts+trends│   │  (LLM prose only)  │
                                       └───────────────┘   └─────────────┘   └─────────┬──────────┘
                                                                                       ▼
                                                                          data/*_<app>.md per app
  1. fetch_data.py — Play vitals per app: ANR/crash/slow-start/LMK/wakelock/wakeup rates, userPerceived* variants, rolling 7d/28d user-weighted rates, distinctUsers per cohort, Google's own anomaly flags, grouped error issues (cause + affected users + version) and a release timeline derived from the versionCode dimension.
  2. fetch_admob.py — AdMob network report. Any range: it chunks into ≤31-day API requests.
  3. fetch_play_console.py — installs, uninstalls, ratings and store-listing metrics from the Play Console bulk exports (Cloud Storage bucket or a local folder of CSVs).
  4. analysis.py — turns all of the above into a compact block of computed facts.
  5. generate_report.py — attaches every source it can match to the app + period and asks the LLM for a report, not a summary: TL;DR, Engagement & Growth, Monetization, Stability, What Changed & When, Actions, Data Quality & Caveats.

Trend Detection & Report Contract

The trend engine (analysis.py) is deliberately boring and deterministic. For every metric it computes: mean/median/min/max, 2nd-half vs 1st-half change, a least-squares slope with R², weekly means (partial weeks dropped), weekday profile, robust spike detection (MAD z-score) and, when several sources exist, cross-source correlations.

It then labels each series:

Label Meaning
flat at zero 0 on every day — collapsed into a single line in the report
insufficient data fewer than 7 days — no direction is claimed
isolated events non-zero on only a handful of days (e.g. 3 crashes in 6 weeks) — "events, not a trend"
emerging zero in the first half, non-zero now
rising / declining R² ≥ 0.50 and ≥ 10% change
weak rise / weak decline 0.20 ≤ R² < 0.50 and ≥ 10% change
no clear trend noise — the report is explicitly told not to describe a trend

Every fact handed to the model carries a status tag, which is the only thing that authorises a trend statement:

Tag The model may…
[UP], [DOWN] call it rising/declining and cite the % change and R²
[WEAK-UP], [WEAK-DOWN] call it a weak/suggestive trend, with its numbers
[FLAT-NOISE] say it is flat/noisy — no direction, no %
[EVENTS] list the individual events — no trend
[FLAT-ZERO] one sentence total for all such metrics
[NO-DATA], [NEW] say it is unavailable / just appeared

This exists because small models cheerfully turn "the halves differ by 8% but R²=0.03" into "active users are declining". With tags, the failure mode flips from a confident wrong claim to a missing one.

Three consequences worth knowing:

  • Use ≥ 14 days, ideally 28–42. A 7-day window yields insufficient data by design instead of a fake trend. ./weekly_report.sh defaults to 42 days for that reason.
  • Small apps get honesty, not filler. Play rounds user counts to 1–2 significant figures, so the facts block states the rounding granularity and the report is told to treat sub-rounding movements as noise. When vitals have nothing to say, the report says so in one line.
  • The prompt is a contract, not a wish. The output sections are fixed, zeroed metrics get one sentence total, and every action must quote the number that motivates it.

Numeric grounding check

After the report is written, generate_report.py extracts every percentage and every R² from it and checks whether the value was actually computed (it also accepts the ratio/percent spellings of the same number). If something cannot be traced back, the model gets one corrective rewrite that lists the offending numbers, and any leftovers are printed as a warning:

Warning: these numbers in the report are not traceable to the data: 47.3%, R²=0.94

Disable it with --no-verify (it costs one extra call only when the check fails).


Prerequisites

Before using this tool you need:

  • A Google Play Developer account with at least one published app.
  • A Google Cloud project with the Play Developer Reporting API enabled.
  • A service account (JSON key) with access to your Play Console data.
  • Python 3.9+ installed.
  • An LLM API key — Gemini (free tier), DeepSeek, OpenAI, OpenRouter, Groq… — or a local model via Ollama/LM Studio. See Choosing the LLM backend.

Setup Guide

1. Google Cloud Project & Service Account

This is the most important step. Follow it carefully.

1.1 Create or select a Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Click the project dropdown at the top and select New Project (or choose an existing one).
  3. Give it a name (e.g., play-vitals-monitor) and click Create.

1.2 Enable the Play Developer Reporting API

  1. In your project, go to APIs & Services > Library.
  2. Search for Google Play Developer Reporting API.
  3. Click Enable.

1.3 Create a Service Account

  1. Go to APIs & Services > Credentials.
  2. Click + Create Credentials > Service Account.
  3. Give it a name (e.g., play-vitals-reader).
  4. Click Done (skip granting roles for now — access is granted in Play Console).

1.4 Generate a JSON Key

  1. In the Service Accounts list, click on the account you just created.
  2. Go to the Keys tab.
  3. Click Add Key > Create New Key.
  4. Choose JSON and click Create.
  5. A .json file will be downloaded automatically — keep this file safe.

Where to place the file: Place the downloaded JSON key file in the root of this project directory:

<project_root>/service_account.json

The default .env.example expects the file to be named service_account.json in the project root. You can use a different path by updating GOOGLE_APPLICATION_CREDENTIALS in .env.

2. Grant Play Console Access

The service account must be granted access to your apps inside the Google Play Console.

  1. Go to the Google Play Console.
  2. Navigate to Users and permissions (under Settings).
  3. Click Invite new user.
  4. Enter the service account email (it looks like [email protected]).
  5. Under App permissions, select all apps you want to monitor.
  6. Under Account permissions, grant at least:
    • View app data (read-only) — this allows reading vitals data.
  7. Click Invite.

It may take a few minutes for the permissions to propagate.

3. Environment Variables

Copy the example configuration and edit it:

cp .env.example .env

Edit .env with your values:

# Path to your service account JSON key file
GOOGLE_APPLICATION_CREDENTIALS=service_account.json

# Your LLM API key (Gemini; see "Choosing the LLM backend" for DeepSeek/OpenAI-compatible)
GEMINI_API_KEY=AIzaSyYourActualKeyHere

# Comma-separated list of package names to monitor (find these in Play Console)
PACKAGE_NAMES=com.example.app1,com.example.app2,com.example.app3

# Optional: Local LLM command (if not using Gemini)
# LOCAL_LLM_COMMAND="ollama run llama3"

Where to find your package names:

  • Open the Google Play Console.
  • Go to All apps — each app's package name is listed under its icon (e.g., com.example.transit).
  • You can also find it in the URL when viewing an app: https://play.google.com/console/developers/.../app/com.example.transit/...

Where to get a Gemini API key:

  1. Go to Google AI Studio.
  2. Click Get API Key.
  3. Create a new API key (free tier includes generous limits).
  4. Copy the key into GEMINI_API_KEY in your .env file.

4. Install Dependencies

pip install -r requirements.txt

It's recommended to use a virtual environment:

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

google-cloud-storage is only needed by fetch_play_console.py (engagement data); everything else works without it.


Usage

Quick Start — one command, everything

./weekly_report.sh                        # the whole pipeline
./weekly_report.sh --reviews              # + user reviews

It runs, in order:

  1. AdMob auth preflight — verifies the refresh token; if Google rejects it, the OAuth flow starts, you confirm in your browser, and the new token is written into .env automatically. If that cannot happen, AdMob is skipped with a warning and the run continues.
  2. Play vitals (--days 42 = 6 weeks by default, optional --reviews).
  3. Play Console engagement exports (installs, installed base, ratings, store) if PLAY_CONSOLE_BUCKET is set.
  4. AdMob (--admob-days 56 = 8 weeks by default, fetched in ≤31-day chunks).
  5. One report per app, joining every source that covers the period.

Weekly cadence, multi-week window

Run it once a week, but fetch more than a week. A 7-day window has no trend to detect — every metric comes back as insufficient data, which is exactly the failure mode this tool used to have.

Default Why
--days 42 (vitals + engagement) 6 weeks ≈ 6 week-over-week points: enough for R² to mean something
--admob-days 56 (AdMob) AdMob numbers are exact (no rounding), so 8 weeks give a much cleaner eCPM/requests fit. Costs 2 API calls instead of 1.

Each run overwrites nothing: it writes a new timestamped JSON + reports. Move old files to data/archive/ whenever you like (a tidy data/ also keeps source auto-detection unambiguous).

Custom Time Ranges

./weekly_report.sh --days 14              # 2 weeks  — minimum for a directional read
./weekly_report.sh --days 28              # 4 weeks
./weekly_report.sh                        # 6 weeks (default)
./weekly_report.sh --days 90              # 3 months — release-over-release comparison
./weekly_report.sh --days 42 --admob-days 31   # shorter AdMob window

Component helpers, if you only want one part:

./vitals_report.sh --days 42 [--reviews]  # Play vitals + engagement only (what used to be run_reports.sh)
./admob_report.sh --days 56 [--reauth]    # AdMob only, self-healing auth (what used to be run_admob.sh)

run_reports.sh and run_admob.sh still work as deprecated aliases that forward to those two.

Including User Reviews

./weekly_report.sh --reviews                     # reviews over the same window as vitals
./weekly_report.sh --reviews-count 20            # 20 latest reviews per app, no time filter
./weekly_report.sh --days 42 --reviews-days 60   # 6-week vitals + 60-day reviews

When --reviews is used with vitals, reviews default to the same timeframe as vitals. Use --reviews-days for an independent window; --reviews-days 0 fetches the latest N without filtering.

Reviews Only (skip vitals entirely)

./vitals_report.sh --reviews-only                   # latest 50 reviews, no time filter
./vitals_report.sh --reviews-only --reviews-days 7  # reviews from the last 7 days only

# Or directly, with more control:
python3 fetch_data.py --reviews-only --reviews-count 30 --reviews-days 14
python3 generate_report.py

In --reviews-only mode only the Android Publisher API is queried. The data file is named reviews_TIMESTAMP.json, and the report gets a dedicated User Reviews Summary section.

Combining Sources & Retrying One App

generate_report.py auto-detects the AdMob (data/admob_*.json) and Play Console engagement (data/engagement_*.json) files whose period best overlaps the vitals file — one report per app, all sources joined. Override or disable that when you need to:

python3 generate_report.py --no-admob                  # vitals (+engagement) only
python3 generate_report.py --admob-file data/admob_<timestamp>.json
python3 generate_report.py --engagement-file data/engagement_<timestamp>.json
python3 generate_report.py --only org.example.app      # (re)generate a single app
python3 generate_report.py --skip org.example.app1,org.example.app2
python3 generate_report.py --prompt-only               # dump the prompt, no API call
python3 generate_report.py --full-daily                # also send the raw daily table
python3 generate_report.py --no-verify                 # skip the numeric grounding check
python3 generate_report.py --model deepseek-v4-pro     # override the model
python3 generate_report.py --provider gemini           # force a backend for this run

--prompt-only is the cheapest way to inspect what the model sees when a report feels off.

Choosing the LLM backend

Nothing in the code is Gemini-specific: llm.py resolves a provider from .env and every script goes through it. Pick one of the options below.

# (a) Google Gemini
GEMINI_API_KEY=...
GEMINI_MODEL=gemini-3.1-flash-lite

# (b) DeepSeek (OpenAI-compatible API)
DEEPSEEK_API_KEY=...
DEEPSEEK_MODEL=deepseek-flash        # DeepSeek-V4.1-Flash; deepseek-v4-pro is the stronger one
LLM_REASONING_EFFORT=low             # low | high | max (reasoning models: keep it low for reports)

# (c) ANY OpenAI-compatible endpoint — OpenAI, OpenRouter, Groq, Mistral, Together,
#     vLLM, llama.cpp server, LM Studio, or Ollama's OpenAI-compatible API
LLM_PROVIDER=openai
LLM_BASE_URL=https://api.openai.com/v1
LLM_API_KEY=sk-...
LLM_MODEL=gpt-4o-mini

# (d) A local CLI (original behaviour)
LOCAL_LLM_COMMAND="ollama run llama3"

Auto-detection order when LLM_PROVIDER is unset: DEEPSEEK_API_KEY → GEMINI_API_KEY → LLM_BASE_URL → LOCAL_LLM_COMMAND. Override per run with --provider gemini|deepseek|openai|local, per model with --model, and see what would be used with:

python3 -c "import llm; print(llm.describe())"     # e.g. "deepseek / deepseek-flash"
python3 -c "import llm; print(llm.list_models())"  # valid model names from the provider

Practical notes:

  • Reasoning models (DeepSeek V4.x, o-series, R1) can burn the whole output budget thinking and return the monologue instead of the report. llm.py detects that and retries once with double the budget, but LLM_REASONING_EFFORT=low is the reliable setting for report writing.
  • Any provider that fails with 429/5xx/timeout is retried with exponential backoff (LLM_MAX_RETRIES, LLM_RETRY_DELAY), and LLM_CALL_DELAY spaces out the per-app calls.
  • With --local the report is produced by LOCAL_LLM_COMMAND instead of the HTTP provider.

Manual Invocation

python3 fetch_data.py --days 28        # vitals (add --fast to skip optional metric sets)
python3 fetch_data.py --refresh-discovery  # live API description (enables memory metric sets)
python3 generate_report.py             # latest data file
python3 generate_report.py --file data/vitals_<timestamp>.json


Examples

Sanitized example outputs are provided in the examples/ directory to help you understand what the tool produces:

File Description
examples/example_report.md A sample AI-generated report (vitals + user reviews) with app names and user identities redacted. Recorded before the multi-source format; current reports add Engagement & Growth, Monetization, What Changed & When and computed trend labels.
examples/example_data.json A synthetic sample of the JSON data structure produced by fetch_data.py, with fictional values
examples/example_admob_report.md A sample AI-generated AdMob monetization report, with IDs and figures fictionalized
examples/example_admob_data.json A synthetic sample of the JSON produced by fetch_admob.py, with fictional values

Privacy note: The examples are sanitized — app package names, user names, and metrics are fictional or redacted. Your real reports are stored locally in data/, which is gitignored and never committed.


User Reviews Feature (Optional)

This tool can optionally fetch the latest user reviews from Google Play and include them in the AI report for a richer analysis that correlates user sentiment with app vitals.

How it works

When --reviews is passed, fetch_data.py calls the Google Play Android Publisher API (reviews.list) to retrieve the most recent user reviews for each app.

The reviews are stored alongside vitals in the same JSON file under a "reviews" key. When generate_report.py runs, the LLM prompt is extended to ask the AI to:

  • Provide a dedicated ## User Reviews Summary section in the report with key themes and notable quotes
  • Identify common praises and complaints
  • Note sentiment trends (positive, negative, mixed)
  • Correlate user feedback with vitals spikes where possible
  • Suggest specific improvements based on actual user comments

The dedicated section ensures reviews are always visible in the output, even when the AI also integrates them into other parts of the report.

Reviews-only mode

Use --reviews-only to fetch and analyze reviews without querying vitals at all. This is useful for quick check-ins or when you only care about user sentiment.

python3 fetch_data.py --reviews-only --reviews-count 30
python3 generate_report.py

The output file is named reviews_TIMESTAMP.json to distinguish it from combined data files.

Usage

# Full pipeline with reviews (default 50 latest)
./weekly_report.sh --reviews

# Fetch vitals + latest 20 reviews
python3 fetch_data.py --days 7 --reviews --reviews-count 20

Required Permissions

The service account needs the androidpublisher API scope. This is covered by the "View app data (read-only)" permission already granted in the Play Console (step 2 of Setup). No additional API enablement is required beyond what's already done for vitals.

Notes

  • Max --reviews-count is 100 (API limit per page).
  • If --reviews is not passed, the report is generated from vitals only.
  • The reviews API requires the service account to have the androidpublisher scope, which is separate from the playdeveloperreporting scope used for vitals.

AdMob Monitoring (Optional)

A standalone script, fetch_admob.py, monitors your ad monetization: impressions, clicks, earnings, eCPM, match rate and more — per app and per ad unit — and generates an AI-written monetization report with actionable recommendations (e.g., low fill rates, underperforming ad units, placement suggestions).

It is fully independent from the vitals/reviews scripts (no shared code, no shared config beyond the same .env file).

Why AdMob needs its own auth (important)

AdMob does NOT support service accounts. Unlike the Play Developer Reporting and Android Publisher APIs (which work with your service_account.json), the AdMob API requires user-based OAuth 2.0: a real Google Account with access to your AdMob account must authorize the tool once, generating a long-lived refresh token that the script reuses automatically.

AdMob OAuth Setup

Follow these steps once. They are fiddly — read all of them before starting.

1. Enable the AdMob API

  1. In Google Cloud Console, select your project.
  2. Go to APIs & Services > Library and enable the Google AdMob API (admob.googleapis.com).

2. Create the OAuth consent screen (first time only)

This is the step most people trip on. You must configure a consent screen even though this is a personal tool.

  1. Go to APIs & Services > OAuth consent screen.
  2. Choose External user type (required for any app using OAuth with a personal Google account; Internal is only available for Google Workspace organizations).
  3. Fill in the required fields: app name, support email, and developer contact email.
  4. Add yourself as a test user — see the caveat below.
  5. Save.

The tester caveat (critical):

  • Unless your project is submitted for Google verification (which requires logos, privacy policy, review, and is meant for public apps), the consent screen is in "Testing" mode. In testing mode, only accounts you explicitly list as test users can authorize.
  • You are the owner of the AdMob account, the Cloud project, and the Google account — but that is not enough. You must manually add your own email address to the test users list in the OAuth consent screen, or the authorization will fail with an access_denied / "app not verified" error.
  • Add your email under Audience > Test users > Add users, then save.

3. Create an OAuth client ID

  1. Go to APIs & Services > Credentials > Create Credentials > OAuth client ID.
  2. Choose Desktop app as the application type (simplest for a local script — no redirect URIs needed).
  3. Click Create, then Download JSON. Save it somewhere you can reference (e.g., admob_oauth_client.json in the project root).

4. Invite your Google account in AdMob

  1. Go to apps.admob.com > Settings > Users.
  2. Click Add user and enter the email of the Google account you will authorize with (the same one you added as a test user).
  3. Choose a role (e.g., "Read only" — this tool only reads).
  4. Accept the invite from that email account.

5. Generate the refresh token (once)

python3 admob_oauth_setup.py --client-json admob_oauth_client.json
# afterwards you only need:
python3 admob_oauth_setup.py          # renew at any time, same command

Log in with the invited Google account, accept the read-only scope, and the script:

  1. prints the authorization URL and opens it in your normal browser;
  2. verifies the new token with a real AdMob API call;
  3. writes ADMOB_REFRESH_TOKEN (plus ADMOB_CLIENT_ID/ADMOB_CLIENT_SECRET) into .env itself, keeping a .env.bak backup — no copy-paste, no manual editing.

Flags that matter:

Flag When you need it
--no-browser Print the URL only and wait — for WSL/SSH/remote sessions where the auto-open is unreliable
--console Fully manual (paste URL, then paste the code back) for headless servers
--no-write-env Just print the token (e.g. you manage .env from a secret store)
--timeout 600 Longer wait for the browser redirect (default OAUTH_TIMEOUT=300, 0 = forever)
--no-verify Skip the post-issue API check

Browser launching, and why it used to open a text browser. The OAuth library calls webbrowser.get(...).open(url), so on WSL it picked whatever Python resolved — often lynx/w3m. This script now intercepts that call and only tries trusted openers: $BROWSER if set, then on WSL cmd.exe /c start (the real Windows default browser) and PowerShell Start-Process, on macOS open, on Linux xdg-open/gio open. Text browsers and wslview are deliberately never used. If none of them succeed, the URL stays on screen and the script keeps listening for the redirect, so copying it into any browser works.

Why the token seems to die almost every week. If the OAuth consent screen is still in Testing mode, Google expires refresh tokens after 7 days (and revokes them whenever the test-user list changes). Publish it — Cloud Console → APIs & Services → OAuth consent screen → Publishing status → Publish app — and tokens become long-lived. Until then you do not need to touch .env: ./weekly_report.sh detects the rejected token, re-runs this flow, and updates .env itself.

AdMob Usage

# Quick start: auto-discover apps & ad units, 7-day report + LLM summary
./admob_report.sh --days 56

# Fetch only (no LLM)
python3 fetch_admob.py --days 7 --discover --fetch-only

# LLM report from an existing JSON file
python3 fetch_admob.py --file data/admob_<timestamp>.json

# Restrict to specific apps
python3 fetch_admob.py --days 7 --discover --packages com.example.app1,com.example.app2

# Use a local LLM instead of the HTTP provider
python3 fetch_admob.py --days 7 --discover --local

Automatic re-authorisation (the weekly-expiry problem)

./weekly_report.sh handles an expired token by itself — no second run, no manual flag:

Step 1/4 · Checking AdMob credentials
    ! The AdMob refresh token was rejected (expired or revoked).
    ! Starting the OAuth flow now: a browser window will open — sign in ...
      [ you confirm in the browser ]
    ✓ New token written to .env
    ✓ AdMob ready
Step 2/4 · Fetching Play vitals ...

Flow: preflight (fetch_admob.py --check-auth, exit 0/3/4) → on 3 the OAuth flow is launched, the new token is verified and written into .env, and the same run continues. Only if that fails (cancelled, no account visible, no browser and no paste) does it skip AdMob for that run with a warning — the vitals/engagement half still completes.

Related flags:

./weekly_report.sh --auth-only            # just renew/verify the AdMob token, then stop
./weekly_report.sh --no-browser           # print the OAuth URL instead of opening a browser
./weekly_report.sh --oauth-timeout 600    # wait longer for the browser redirect (default 300)
./admob_report.sh --reauth                # force a renewal before an AdMob-only run

Non-interactive use (cron, CI, stdin not a TTY): the consent cannot be confirmed, so the run warns and skips AdMob instead of hanging. Renew once from a terminal with --auth-only.

Notes:

  • The script auto-discovers all linked apps and ad units via the API (--discover), so you don't need to declare them.
  • The AdMob API allows ≤ 31 days per request; longer ranges (e.g. --days 56) are fetched in chunks automatically, so multi-week trends are available from AdMob too.
  • Money is reported in USD by default (--currency or ADMOB_CURRENCY to change). Ratios (CTR, match rate) are 0–1 (1.0 = 100%).

AdMob Ad Units Configuration

Auto-discovery covers most cases. If you prefer to declare ad units explicitly (or restrict the report to specific units), create a JSON file like admob_ad_units.example.json:

{
  "com.example.app": [
    "ca-app-pub-1234567890123456/1234567890"
  ]
}

Then run:

python3 fetch_admob.py --days 7 --ad-units-config admob_ad_units.json

Declared ad unit IDs are validated against the API — a typo raises a clear error listing the available units.

AdMob Metrics captured

Per day, per ad unit: AD_REQUESTS, MATCHED_REQUESTS, IMPRESSIONS, CLICKS, ESTIMATED_EARNINGS, IMPRESSION_CTR, IMPRESSION_RPM (eCPM), MATCH_RATE, SHOW_RATE, plus per-ad-unit and per-app totals (CTR, eCPM, match rate).


Engagement Data: Installs, Uninstalls, Ratings, Store (Optional)

Fixes the "my stability is perfect, so what is actually happening?" problem: gives the report install, uninstall, rating and store-conversion trends instead of only vitals.

One-time setup (2 minutes)

  1. Play Console → Download reports → Statistics → Copy Cloud Storage URI. It looks like gs://pubsite_prod_rev_1234567890123456789.

    ⚠️ The number in that URI is the developer bucket id, and it is usually NOT the same as PLAY_DEVELOPER_ACCOUNT_ID (the id used by the reporting API). There is no way to derive one from the other — copy it from the Play Console. All your apps share the one bucket; the package name is inside each file name.

  2. Cloud Storage → that bucket → Permissions → Add principal → your service account email ([email protected]) → role Storage Legacy Bucket Reader.

  3. Add the bucket name to .env:

    PLAY_CONSOLE_BUCKET=pubsite_prod_rev_1234567890123456789

There is no REST endpoint for these statistics — the Cloud Storage bucket is Google's programmatic interface for them (confirmed in the official docs), which is why this is a separate script using the read-only storage scope.

Usage

python3 fetch_play_console.py --days 42                       # from Cloud Storage
python3 fetch_play_console.py --days 42 --local-dir ~/Downloads/play_reports   # from downloaded CSVs

It writes data/engagement_<timestamp>.json, and generate_report.py picks it up automatically for every app whose period overlaps. The report then gains: install/uninstall trend, net user growth, rating trend, store visitors → acquirers conversion, and two honest retention proxies:

  • install-to-active-user ratio — how fast the daily base is replaced (high = churn-driven);
  • engagement rate = active users / installed base — the closest thing to a whole-product retention number without the Play Console UI. A 2% rate means ~98% of devices with the app installed did not open it on a typical day.

Files read

File What it gives
stats/installs/installs_<pkg>_<YYYYMM>_overview.csv daily installs, uninstalls (device + user), upgrades, install/update/uninstall events, Active Device Installs = installed base
stats/ratings/ratings_<pkg>_<YYYYMM>_overview.csv daily average rating (0.0 = no ratings that day, treated as missing) and cumulative average rating
stats/store_performance/store_performance_<pkg>_<YYYYMM>_traffic_source.csv store listing visitors/acquirers (fallback: _country); rows are summed per day and the conversion rate is recomputed

The reviews/ prefix in the same bucket holds full review history as CSV; this tool does not read it because the Android Publisher API (used by --reviews) already returns the latest reviews.

Notes

  • Exports are UTF-16 encoded with a BOM and are monthly files that land a few days after month end, so the current month is usually partial. The fetcher prints the exact days it found.
  • Column names have changed over the years (and some files are dimension-partitioned), so the parser normalises headers, drops unrecognised columns, sums dimension rows and recomputes rates.
  • Without this step nothing breaks: the report simply says engagement data is missing and explains that ad-request volume is being used as the session proxy instead.

Output

All output goes to the data/ directory.

File Pattern Contents
data/vitals_YYYYMMDD_HHMMSS.json Raw Play API data per app: vitals metric sets, anomalies, grouped error issues, release timeline
data/vitals_YYYYMMDD_HHMMSS_<pkg>.md AI-generated report for one app (all attached sources)
data/reviews_YYYYMMDD_HHMMSS.json User reviews data (from --reviews-only mode)
data/admob_YYYYMMDD_HHMMSS.json AdMob monetization data per app / ad unit (fetch_admob.py)
data/admob_YYYYMMDD_HHMMSS_<pkg>.md Standalone AdMob report (if you run fetch_admob.py with reporting on)
data/engagement_YYYYMMDD_HHMMSS.json Play Console exports: installs, uninstalls, ratings, store listing (fetch_play_console.py)
data/*_<pkg>.prompt.txt The exact prompt sent to the LLM (with --prompt-only) — useful for debugging a bad report

JSON data structure

{
  "com.example.app1": {
    "package_name": "com.example.app1",
    "metrics": {
      "anrRate": {
        "rows": [
          {
            "startTime": {"year": 2026, "month": 5, "day": 5},
            "metrics": [
              {"decimalValue": {"value": "0.0023"}},
              {"integerValue": {"value": "1500"}}
            ]
          }
        ]
      },
      "crashRate": { ... },
      "slowStartRate": {
        "rows": [
          {
            "startTime": {"year": 2026, "month": 5, "day": 5},
            "dimensions": [{"dimension": "startType", "stringValue": "COLD"}],
            "metrics": [...]
          }
        ]
      },
      "stuckBackgroundWakelockRate": { ... },
      "excessiveWakeupRate": { ... },
      "errorCounts": { ... }
    },
    "period": {
      "start": "2026-05-03T00:00:00",
      "end": "2026-05-06T00:00:00"
    }
  }
}

Metrics collected

Vitals (Play Developer Reporting API). Rates are user-weighted percentages; userPerceived* counts only crashes/ANRs/LMKs the user actually saw; the 7d/28d variants are Google's own rolling averages and are the best "stable picture" numbers.

Metric set What it measures
anrRate ANR rate + userPerceivedAnrRate + 7d/28d user-weighted
crashRate Crash rate + userPerceivedCrashRate + 7d/28d user-weighted
slowStartRate Slow start rate by COLD/WARM/HOT start type
lmkRate User-perceived low-memory kills
stuckBackgroundWakelockRate Wakelocks held in the background too long
excessiveWakeupRate Excessive wakeups (alarms, etc.)
slowRenderingRate Jank (games only — skipped automatically elsewhere)
bitmapMemoryUsage, anonRssAndSwapMemoryUsage Memory percentiles (P50/P90/P99)
errorCounts Absolute crash/ANR report counts by reportType
anomalies Regressions Google's own detectors flagged
errorIssues Grouped crash/ANR clusters: cause, reports, affected users, first/last version, issueUri

Every metric set also returns distinctUsers — the number of users that metric was normalised against. It is the only user-count signal in the Play reporting API, it is rounded to 1–2 significant figures, and it is what the report uses as the active-user proxy (with that caveat stated).

AdMob: AD_REQUESTS, MATCHED_REQUESTS, IMPRESSIONS, CLICKS, ESTIMATED_EARNINGS, IMPRESSION_CTR, IMPRESSION_RPM (eCPM), MATCH_RATE, SHOW_RATE — per day, per ad unit.

Play Console engagement: daily installs, uninstalls, upgrades, current/total user installs, average rating, store-listing visitors, acquirers and conversion rate.


Why installs/retention are not in the vitals API

This is the single biggest limitation of Play's reporting API, and the reason fetch_play_console.py exists: the API exposes stability and a rounded user count, and nothing else. There is no installs, uninstalls, ratings, store-listing or retention endpoint. Those live only in:

  1. the Play Console UI, and
  2. the bulk exports Google publishes to a Cloud Storage bucket (stats/installs, stats/ratings, stats/store_performance).

True 1/7/28-day retention cohorts are not part of the exports either — but with exports + vitals you can compute the honest proxies: install trend, uninstall/install ratio, net user growth, install-to-active-user ratio (a solid turnover/retention proxy) and store conversion trend.


Architecture & Extending

Current Structure

.
├── analysis.py           # Trend engine: series parsing, stats, labels, facts builders (no I/O, no LLM)
├── llm.py                # LLM layer: provider selection (Gemini/DeepSeek/OpenAI-compatible/local), timeouts, retries, pacing
├── fetch_data.py         # Play fetcher: vitals, anomalies, error issues, releases, reviews → JSON
├── fetch_admob.py        # AdMob fetcher + optional standalone monetization report (user OAuth)
├── fetch_play_console.py # Play Console bulk exports: installs, uninstalls, ratings, store → JSON
├── generate_report.py    # Multi-source LLM reporter: one .md per app
├── admob_oauth_setup.py  # One-time helper to generate an AdMob refresh token
├── admob_ad_units.example.json  # Template for declaring ad units per app
├── weekly_report.sh      # ONE command: AdMob auth + all sources + all reports (run weekly)
├── vitals_report.sh      # component: Play vitals + engagement only
├── admob_report.sh       # component: AdMob only, self-healing auth
├── run_reports.sh        # deprecated alias -> vitals_report.sh
├── run_admob.sh          # deprecated alias -> admob_report.sh
├── examples/             # Sanitized sample outputs (reports + JSON structures)
├── .env                  # Your credentials and configuration (gitignored)
├── .env.example          # Template for .env
├── service_account.json  # Google service account key (gitignored)
├── admob_oauth_client.json  # OAuth client JSON for AdMob (gitignored, optional)
├── requirements.txt      # Python dependencies
├── data/                 # All output files (gitignored)
└── README.md             # This file

Adding a New Data Source

Because all analysis happens on {date: value} series, a new source only has to:

  1. write data/<source>_<timestamp>.json with {"period": {...}, "apps": {"<pkg>": {...}}},
  2. expose a build_facts(app_data, ...) function in analysis.py that returns (facts, notes, tables) — one-line facts, data-quality caveats, and ready markdown tables,
  3. add the file pattern to the discovery helpers in generate_report.py so it is auto-attached.

Nothing else changes: the trend engine, the prompt contract and the output sections stay the same.

Planned Refactoring for New Data Sources

The current design is intentionally flat and single-purpose, focused on Google Play Vitals. As new data sources are added (e.g., user reviews, ratings, in-app review data, subscription insights), the architecture will be refactored into a more modular structure:

monitor/
  core/
    auth.py           # Authenticate to any Google API
    freshness.py      # Shared freshness retry logic
    storage.py        # JSON file management
    reporter.py       # Generic LLM prompt builder
  fetchers/
    base.py           # Abstract fetcher interface
    vitals.py         # Current vitals logic (extracted from fetch_data.py)
    reviews.py        # Future: user reviews / comments
    ratings.py        # Future: star ratings
  config.py           # Env + CLI handling

Key design principles for the refactored version:

  • Each fetcher is independent — it registers itself, declares its own API scope, and produces its own output shape.
  • The reporter is source-agnostic — each data source provides its own prompt builder, and the reporter only orchestrates the LLM call.
  • Shared utilities are extracted — authentication, freshness retry, and file management are reused across all fetchers.
  • main.py discovers fetchers — no manual wiring when adding a new source.

If you're interested in contributing, the current fetch_data.py is the best place to study the patterns before the refactoring.


Troubleshooting

Google Play Developer Reporting API has not been used

You need to enable the API in your Google Cloud project. See the Setup Guide above, step 1.2.

After enabling, it may take a few minutes to propagate.

'timeline_spec.end_date' field should be at most the current freshness

The API has a processing delay (typically 3–5 days). The script handles this automatically by parsing the error and retrying with the correct date. This is normal — you'll see a log message like:

Adjusting end_date to freshness: 2026-05-07

AttributeError: 'Resource' object has no attribute '...' (e.g. memory metric sets)

google-api-python-client ships a cached API description that lags behind the live API, so brand new metric sets (memory usage) are unknown to it. Either update the library, or let the tool fetch the live description:

pip install --upgrade google-api-python-client
python3 fetch_data.py --refresh-discovery --days 28

Unknown-but-optional metric sets are skipped with a log line instead of aborting the run; --fast skips all optional sets deliberately.

A report only says "everything is 0%"

That is what the data said, but it is no longer the whole report: with the current version you get Engagement & Growth, Monetization and What Changed & When in the same document, and stability is collapsed to a single line. If engagement sections are empty too:

  • too short a window — use --days 28 or more (7 days is insufficient data by design);
  • no AdMob and no Play Console data attached — run fetch_admob.py and/or fetch_play_console.py (see Engagement Data);
  • check data/*_<pkg>.prompt.txt (via --prompt-only) to see exactly what facts were available.

The run appears to hang / the terminal freezes

Fixed in the current version: LLM calls now have a per-request timeout, bounded retries with exponential backoff and a pause between calls. Tune them in .env:

LLM_TIMEOUT=120
LLM_MAX_RETRIES=3
LLM_RETRY_DELAY=5
LLM_CALL_DELAY=2

If you are on an old checkout and a call stalls, Ctrl-C is safe: data files are written before the LLM step, and python3 generate_report.py --only <pkg> regenerates just the missing report.

429 / rate-limit errors from Gemini

Lower the pressure: LLM_CALL_DELAY=10 python3 generate_report.py --only <pkg>, or use a local model with --local. Reports are written per app, so partial progress is never lost.

No data returned for an app

  • Make sure the service account has been granted access in the Play Console (see step 2).
  • Verify the package name is correct.
  • The app must have some user traffic — apps with no users will have no data, and several metric sets (slow start, wakelocks, memory) simply return no rows below a traffic threshold. The report states which ones were missing.
  • The Play reporting API lags a few days; the freshness retry handles that automatically.

GEMINI_API_KEY not found

Set GEMINI_API_KEY in your .env file. See section 3.2.

Play Console engagement data is empty

  • The bucket name must be the Play Console one (pubsite_prod_rev_...), not a bucket you created.
  • The service account needs Storage Legacy Bucket Reader on that bucket (Cloud Storage → Permissions), separate from Play Console app permissions.
  • Exports are monthly and lag a few days; a fresh project may have no files yet. Use --local-dir with manually downloaded CSVs to verify the parser works.

License

Released under the Apache License 2.0.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages