adsspy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
adsspy/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """AdsSpy — see what ads your competitors run on Meta (official Ad Library API)."""
2
+
3
+ from .analyzer import (ad_duration_days, is_active, keyword_trends,
4
+ longest_running, summarize, top_advertisers)
5
+ from .client import AdLibraryClient, AdsSpyError, build_url
6
+ from .store import load_ads, save_ads
7
+
8
+ __version__ = "0.1.0"
9
+ __all__ = ["AdLibraryClient", "AdsSpyError", "build_url", "summarize",
10
+ "top_advertisers", "longest_running", "keyword_trends",
11
+ "ad_duration_days", "is_active", "save_ads", "load_ads"]
adsspy/analyzer.py ADDED
@@ -0,0 +1,86 @@
1
+ """AdsSpy analyzer: turn collected ads into competitor intelligence."""
2
+
3
+ import re
4
+ from collections import Counter
5
+ from datetime import date
6
+
7
+ STOPWORDS = {
8
+ "the", "and", "for", "with", "your", "you", "our", "this", "that",
9
+ "from", "are", "get", "now", "all", "can", "has", "have", "more",
10
+ "just", "into", "over", "than", "then", "will", "shop", "buy",
11
+ "click", "learn", "today", "new", "best", "free", "off", "out",
12
+ }
13
+
14
+
15
+ def _parse_date(value):
16
+ """Parse 'YYYY-MM-DD' (or ISO datetime) into a date, or None."""
17
+ if not value:
18
+ return None
19
+ try:
20
+ return date.fromisoformat(str(value)[:10])
21
+ except ValueError:
22
+ return None
23
+
24
+
25
+ def ad_duration_days(ad, today=None):
26
+ """How many days an ad ran (start -> stop, or start -> today). None if unknown."""
27
+ start = _parse_date(ad.get("ad_delivery_start_time"))
28
+ if start is None:
29
+ return None
30
+ end = _parse_date(ad.get("ad_delivery_stop_time")) or (today or date.today())
31
+ return max(0, (end - start).days)
32
+
33
+
34
+ def is_active(ad):
35
+ return not ad.get("ad_delivery_stop_time")
36
+
37
+
38
+ def top_advertisers(ads, n=10):
39
+ """Pages ranked by number of ads collected."""
40
+ counts = Counter(ad.get("page_name", "Unknown") for ad in ads)
41
+ return [{"page_name": name, "ads": count}
42
+ for name, count in counts.most_common(n)]
43
+
44
+
45
+ def longest_running(ads, today=None, n=10):
46
+ """Ads ranked by days running — long-running usually means profitable."""
47
+ ranked = []
48
+ for ad in ads:
49
+ days = ad_duration_days(ad, today=today)
50
+ if days is not None:
51
+ ranked.append({
52
+ "id": ad.get("id", ""),
53
+ "page_name": ad.get("page_name", "Unknown"),
54
+ "days_running": days,
55
+ "active": is_active(ad),
56
+ "ad_snapshot_url": ad.get("ad_snapshot_url", ""),
57
+ })
58
+ ranked.sort(key=lambda item: item["days_running"], reverse=True)
59
+ return ranked[:n]
60
+
61
+
62
+ def keyword_trends(ads, n=15):
63
+ """Most common meaningful words across all ad copy."""
64
+ counter = Counter()
65
+ for ad in ads:
66
+ bodies = ad.get("ad_creative_bodies") or []
67
+ text = " ".join(bodies).lower()
68
+ for word in re.findall(r"[a-z]{3,}", text):
69
+ if word not in STOPWORDS:
70
+ counter[word] += 1
71
+ return [{"keyword": word, "count": count}
72
+ for word, count in counter.most_common(n)]
73
+
74
+
75
+ def summarize(ads, today=None):
76
+ """One-call report: totals, top advertisers, longest-running, keywords."""
77
+ active = [ad for ad in ads if is_active(ad)]
78
+ return {
79
+ "total_ads": len(ads),
80
+ "active_ads": len(active),
81
+ "ended_ads": len(ads) - len(active),
82
+ "advertisers": len({ad.get("page_name", "Unknown") for ad in ads}),
83
+ "top_advertisers": top_advertisers(ads),
84
+ "longest_running": longest_running(ads, today=today),
85
+ "keyword_trends": keyword_trends(ads),
86
+ }
adsspy/client.py ADDED
@@ -0,0 +1,90 @@
1
+ """AdsSpy client for Meta's official Ad Library API (ads_archive).
2
+
3
+ Uses only the public transparency endpoint. Token comes from the
4
+ META_ACCESS_TOKEN environment variable — never hard-code it.
5
+ Pure Python (urllib), no dependencies.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+
14
+ GRAPH_BASE = "https://graph.facebook.com"
15
+ DEFAULT_VERSION = "v21.0"
16
+
17
+ FIELDS = [
18
+ "id", "page_id", "page_name",
19
+ "ad_creative_bodies", "ad_creative_link_titles",
20
+ "ad_snapshot_url", "publisher_platforms",
21
+ "ad_delivery_start_time", "ad_delivery_stop_time",
22
+ "impressions", "spend", "currency",
23
+ ]
24
+
25
+
26
+ class AdsSpyError(Exception):
27
+ """Raised when the Ad Library API returns an error or bad data."""
28
+
29
+
30
+ def build_url(search_terms, countries, version=DEFAULT_VERSION, limit=100,
31
+ ad_type="ALL", active_status="ALL"):
32
+ """Build the ads_archive request URL (token is sent via header, not URL)."""
33
+ if not search_terms:
34
+ raise ValueError("search_terms is required")
35
+ if not countries:
36
+ raise ValueError("at least one country code is required, e.g. ['FR']")
37
+ params = {
38
+ "search_terms": search_terms,
39
+ "ad_reached_countries": json.dumps([c.upper() for c in countries]),
40
+ "ad_type": ad_type,
41
+ "ad_active_status": active_status,
42
+ "fields": ",".join(FIELDS),
43
+ "limit": str(int(limit)),
44
+ }
45
+ query = urllib.parse.urlencode(params)
46
+ return f"{GRAPH_BASE}/{version}/ads_archive?{query}"
47
+
48
+
49
+ class AdLibraryClient:
50
+ """Minimal, polite client for the Meta Ad Library API."""
51
+
52
+ def __init__(self, access_token=None, version=DEFAULT_VERSION, timeout=30):
53
+ self.access_token = access_token or os.environ.get("META_ACCESS_TOKEN", "")
54
+ self.version = version
55
+ self.timeout = timeout
56
+
57
+ def _get(self, url):
58
+ if not self.access_token:
59
+ raise AdsSpyError(
60
+ "No access token. Set META_ACCESS_TOKEN (see docs/SETUP.md).")
61
+ request = urllib.request.Request(
62
+ url, headers={"Authorization": f"Bearer {self.access_token}"})
63
+ try:
64
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
65
+ return json.loads(response.read().decode("utf-8"))
66
+ except urllib.error.HTTPError as exc:
67
+ body = exc.read().decode("utf-8", errors="replace")
68
+ raise AdsSpyError(f"API error {exc.code}: {body[:300]}") from exc
69
+ except urllib.error.URLError as exc:
70
+ raise AdsSpyError(f"Network error: {exc.reason}") from exc
71
+
72
+ def search_ads(self, search_terms, countries, max_pages=3, limit=100):
73
+ """Search the Ad Library. Returns a list of ad dicts.
74
+
75
+ Follows pagination up to max_pages. Respect Meta's rate limits —
76
+ keep max_pages small and cache results with adsspy.store.
77
+ """
78
+ url = build_url(search_terms, countries, version=self.version, limit=limit)
79
+ ads = []
80
+ for _ in range(max(1, int(max_pages))):
81
+ payload = self._get(url)
82
+ if "error" in payload:
83
+ message = payload["error"].get("message", "unknown error")
84
+ raise AdsSpyError(f"API error: {message}")
85
+ ads.extend(payload.get("data", []))
86
+ next_url = (payload.get("paging") or {}).get("next")
87
+ if not next_url:
88
+ break
89
+ url = next_url
90
+ return ads
adsspy/store.py ADDED
@@ -0,0 +1,19 @@
1
+ """AdsSpy storage: save/load collected ads as JSON (history compounds)."""
2
+
3
+ import json
4
+
5
+
6
+ def save_ads(ads, path):
7
+ """Save a list of ad dicts to a JSON file. Returns the count saved."""
8
+ with open(path, "w", encoding="utf-8") as f:
9
+ json.dump(ads, f, indent=2, ensure_ascii=False)
10
+ return len(ads)
11
+
12
+
13
+ def load_ads(path):
14
+ """Load ads previously saved with save_ads (or samples/ads.json)."""
15
+ with open(path, encoding="utf-8") as f:
16
+ data = json.load(f)
17
+ if not isinstance(data, list):
18
+ raise ValueError("ads file must contain a JSON list")
19
+ return data
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: adsspy
3
+ Version: 0.1.0
4
+ Summary: See what ads your competitors run on Meta: official Ad Library API client + competitor analysis in pure Python.
5
+ Author: AdsSpy Contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Brdx47/Ads-Spy
8
+ Project-URL: Repository, https://github.com/Brdx47/Ads-Spy
9
+ Project-URL: Issues, https://github.com/Brdx47/Ads-Spy/issues
10
+ Keywords: meta,facebook-ads,ad-library,competitor-research,ad-intelligence
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: Office/Business
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # AdsSpy — See What Ads Your Competitors Run on Meta
28
+
29
+ **Meta's Ad Library is public. AdsSpy turns it into competitor intelligence.**
30
+
31
+ Every ad on Facebook and Instagram leaves a public trace in Meta's Ad Library. Advertisers who read those traces learn what competitors promote, which messages they repeat, and — most valuable of all — which ads have been running for months (long-running ads are usually profitable ads).
32
+
33
+ AdsSpy collects ads through Meta's **official Ad Library API** and analyzes them:
34
+
35
+ - **Top advertisers** in any niche or keyword
36
+ - **Longest-running ads** — the market's silent vote for what works
37
+ - **Keyword trends** in ad copy (offers, hooks, angles everyone uses)
38
+ - **Active vs. ended** campaigns, with full history you save yourself
39
+
40
+ ```python
41
+ from adsspy import AdLibraryClient, summarize
42
+
43
+ client = AdLibraryClient() # reads META_ACCESS_TOKEN from the environment
44
+ ads = client.search_ads(search_terms="wireless headphones", countries=["FR", "DE"])
45
+ report = summarize(ads)
46
+ print(report["top_advertisers"])
47
+ print(report["longest_running"][:3])
48
+ ```
49
+
50
+ ## Honest coverage limits (read this first)
51
+
52
+ The Ad Library API is a transparency tool, not a universal spy tool:
53
+
54
+ - It returns **ads of any type delivered in the EU/UK** (past year) plus **political and social-issue ads worldwide**. Commercial ads outside EU/UK are generally **not** in the API.
55
+ - It shows creative, dates, platforms, and (for political ads) spend/impression **ranges** — never exact budgets or targeting of commercial ads.
56
+ - Access is **free**, but Meta requires **identity confirmation** for your Facebook account before the API returns data (typically 1–3 business days). See `docs/SETUP.md`.
57
+
58
+ Within those limits, AdsSpy is a real research edge — and the EU/UK market alone is enormous.
59
+
60
+ ## Why AdsSpy?
61
+
62
+ - **Clear money story:** media buyers, agencies, and e-commerce brands already pay monthly for ad-intelligence tools. Per-seat pricing is standard (see `docs/BUSINESS.md`).
63
+ - **Official API only:** no scraping, no ToS roulette. Public transparency data through Meta's own endpoint.
64
+ - **Analysis built in:** collection is easy; insight is the product. Long-running-ad detection and keyword trends ship in v0.1.
65
+ - **Pure Python, zero dependencies:** client, analyzer, and JSON storage run anywhere.
66
+ - **Your history compounds:** save every collection run; trends over time are what competitors can't copy.
67
+
68
+ ## Quick start (no token needed)
69
+
70
+ ```bash
71
+ git clone https://github.com/Brdx47/Ads-Spy.git
72
+ cd Ads-Spy
73
+ python demo.py
74
+ ```
75
+
76
+ The demo analyzes 10 sample ads: top advertisers, longest-running ads, and trending keywords.
77
+
78
+ To collect real ads, follow `docs/SETUP.md` (identity confirmation → developer app → token), then:
79
+
80
+ ```bash
81
+ export META_ACCESS_TOKEN="your-long-lived-token"
82
+ python -c "from adsspy import AdLibraryClient; print(len(AdLibraryClient().search_ads('shoes', ['FR'])))"
83
+ ```
84
+
85
+ ## Business model (open-core)
86
+
87
+ The engine is MIT-licensed and free. Revenue comes from hosted intelligence:
88
+
89
+ - **Hosted collection:** scheduled searches, growing ad history, alerts on new competitor ads
90
+ - **Dashboards:** niche reports, advertiser timelines, creative galleries
91
+ - **AI summaries:** "3 competitors launched 'free shipping' angles this week"
92
+ - **Team features:** saved niches, shared reports, API access
93
+
94
+ See `docs/BUSINESS.md` for customers, pricing, go-to-market, and honest risks. No income is guaranteed.
95
+
96
+ ## Roadmap
97
+
98
+ - [ ] New-ad alerts (watch a page/keyword, get notified)
99
+ - [ ] Creative gallery export (snapshot links + copy, organized)
100
+ - [ ] Spend/impression range tracking for political & social ads
101
+ - [ ] Multi-country niche comparison
102
+ - [ ] Hosted dashboard with history and alerts (open-core)
103
+
104
+ ## Contributing
105
+
106
+ New analyzers, exporters (CSV, Sheets), and niche sample datasets are the most valuable contributions. Read `CONTRIBUTING.md`.
107
+
108
+ ## License
109
+
110
+ MIT — free for personal and commercial use. See `LICENSE`.
111
+
112
+ ---
113
+
114
+ *AdsSpy uses Meta's official Ad Library API and public transparency data only. Follow Meta's Platform Terms and Ad Library API terms. Long-running ads suggest — but do not prove — profitability.*
@@ -0,0 +1,9 @@
1
+ adsspy/__init__.py,sha256=U9zsGUr6gxH_9SBCwK2nRT7d1kTERScC2PXQeoALquY,550
2
+ adsspy/analyzer.py,sha256=K7DlwOK1J_YwfrCb49qawaH6FhNPOoMCGtxls55nwy8,2935
3
+ adsspy/client.py,sha256=cMdG_vv1hV71ZPcSLsmgCcvucupvxKxJ9sqYx-2a8Sw,3428
4
+ adsspy/store.py,sha256=9bk8nQgpyoIyknGeJx-e7-nfiOwboTX95zFXnTd6xpI,595
5
+ adsspy-0.1.0.dist-info/licenses/LICENSE,sha256=N0o-_FlTqOKsBZJus5pg8SpqLjf_78Mjqldw1TzwicE,1076
6
+ adsspy-0.1.0.dist-info/METADATA,sha256=8k_cxYHxwZA0BK5bSrDAsthuoBMisvgC3TbEur2mnEc,5253
7
+ adsspy-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ adsspy-0.1.0.dist-info/top_level.txt,sha256=jX0hG7GPF0UCbqOSaf7upraGoQ5jY9ppzJdVQzycK8Y,7
9
+ adsspy-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AdsSpy Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ adsspy