File size: 15,953 Bytes
b02a1b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dcf3a7
 
 
 
 
 
 
 
 
 
 
 
b02a1b6
8dcf3a7
b02a1b6
 
 
8dcf3a7
 
 
 
 
 
b02a1b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dcf3a7
b02a1b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""
ENA Chatbot โ€” Scraper v4.0 (API-Based)
ูŠุณุชุฎุฏู… WordPress REST API + RSS Feed + Sitemap ุจุฏู„ ุงู„ู€ scraping ุงู„ุชู‚ู„ูŠุฏูŠ
Run: python scraper_api.py
"""
from __future__ import annotations

import json
import re
import time
import xml.etree.ElementTree as ET
from urllib.parse import urlparse, unquote
from html import unescape

import requests
from bs4 import BeautifulSoup

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# โš™๏ธ CONFIG
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

BASE = "https://www.ena.tn"

API_ENDPOINTS = {
    "posts_ar": f"{BASE}/wp-json/wp/v2/posts?per_page=100&lang=ar",
    "posts_fr": f"{BASE}/wp-json/wp/v2/posts?per_page=100&lang=fr",
    "posts_all": f"{BASE}/wp-json/wp/v2/posts?per_page=100",
    "pages_ar": f"{BASE}/wp-json/wp/v2/pages?per_page=100&lang=ar",
    "pages_fr": f"{BASE}/wp-json/wp/v2/pages?per_page=100&lang=fr",
    "pages_all": f"{BASE}/wp-json/wp/v2/pages?per_page=100",
}

RSS_FEEDS = [
    f"{BASE}/feed/",
    f"{BASE}/ar/feed/",
    f"{BASE}/fr/feed/",
]

SITEMAPS = [
    f"{BASE}/ar/wp-sitemap-posts-post-1.xml",
    f"{BASE}/ar/wp-sitemap-posts-page-1.xml",
    f"{BASE}/fr/wp-sitemap-posts-post-1.xml",
    f"{BASE}/fr/wp-sitemap-posts-page-1.xml",
]

# ุตูุญุงุช ู…ู‡ู…ุฉ ู†ุฌูŠุจู‡ุง ู…ุจุงุดุฑุฉ ุจุงู„ู€ scraping (ู…ุง ุชุธู‡ุฑุด ููŠ ุงู„ู€ API)
PRIORITY_PAGES = [
    f"{BASE}/ar/concours-ar/cycle-superieur-arr/concours-entree-cycle-superieur-ar/",
    f"{BASE}/ar/concours-ar/informations-generales-ar/",
    f"{BASE}/ar/concours-ar/cycle-moyen-ar/entree-au-cycle-de-formation-des-cadres-moyens-ar/",
    f"{BASE}/ar/concours-ar/agents-categorie-a3-ar/",
    f"{BASE}/ar/preparation-au-concours-ar/",
    f"{BASE}/fr/concours/cycle-superieur/le-concours-dentree-au-cycle-superieur/",
    f"{BASE}/fr/concours/informations-generales/",
    f"{BASE}/fr/concours/cycle-moyen/concours-dentree-au-cycle-de-formation-des-cadres-moyens-de-la-sous-categorie-a2-2/",
    f"{BASE}/fr/concours/agents-de-la-sous-categorie-a3/",
    f"{BASE}/ar/formation-continue-ar/formation-continue-a-distance-et-presentielle-ar/",
    f"{BASE}/fr/formation-continue/formation-continue-a-distance-et-presentielle/",
    f"{BASE}/ar/inscription2026/",
    f"{BASE}/ar/ouverturefad2026/",
    f"{BASE}/ar/fad2026/",
]

HEADERS = {
    "User-Agent": "Mozilla/5.0 (compatible; ENA-Chatbot/4.0; +https://www.ena.tn)",
    "Accept": "application/json, text/html",
}

CATS = {
    "/concours/":          "concours_fr",
    "/concours-ar":        "concours_ar",
    "/ar/concours":        "concours_ar",
    "/formation/":         "formation_fr",
    "/ar/formation":       "formation_ar",
    "/formation-continue": "formation_continue",
    "/gouvernance/":       "gouvernance",
    "/actualites/":        "news_fr",
    "/actualites-ar/":     "news_ar",
    "/leadership":         "leadership",
    "/inscription":        "inscription",
    "/fad":                "fad",
}

SKIP_SLUGS = [
    "page-dexemple", "sample-page", "politique-de-confidentialite",
    "shop", "cart", "checkout", "my-account", "woocommerce",
    "default-kit", "elementor", "log-file",
]

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ› ๏ธ HELPERS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

CONTENT_CATS = {
    "concours_ar": ["ู…ู†ุงุธุฑุฉ", "ุชุฑุดุญ", "ุดุฑูˆุท ุงู„ุฏุฎูˆู„", "ุจู‚ุงุน", "ุงุฎุชุจุงุฑ", "ู…ุฑุญู„ุฉ ุนู„ูŠุง", "ู…ุฑุญู„ุฉ ู…ุชูˆุณุทุฉ", "ุฃุนูˆุงู†"],
    "concours_fr": ["concours", "candidature", "cycle supรฉrieur", "cycle moyen", "รฉpreuve", "places"],
    "formation_continue": ["ุชูƒูˆูŠู† ู…ุณุชู…ุฑ", "formation continue", "fad", "ุชูƒูˆูŠู† ุนู† ุจุนุฏ"],
    "formation_ar": ["ุชูƒูˆูŠู†", "ุจุฑู†ุงู…ุฌ", "ุชุฃู‡ูŠู„", "cycle de formation"],
    "news_ar": ["ุฅุนู„ุงู†", "ุจู„ุงุบ", "ุฃุฎุจุงุฑ", "ู…ุณุชุฌุฏุงุช", "ุฅุนู„ุงู…"],
    "news_fr": ["actualitรฉ", "communiquรฉ", "annonce", "information"],
    "inscription": ["ุชุณุฌูŠู„", "inscription", "2026"],
    "fad": ["fad", "ุชุนู„ูŠู… ุนู† ุจุนุฏ", "formation ร  distance"],
}

def get_category(url: str, text: str = "") -> str:
    ul = url.lower()
    # First try URL-based matching (most reliable)
    for p, c in CATS.items():
        if p in ul:
            return c
    # Then try content-based matching for API pages
    if text:
        tl = text.lower()
        for cat, keywords in CONTENT_CATS.items():
            if any(kw in tl for kw in keywords):
                return cat
    return "other"

def get_lang(url: str) -> str:
    path = urlparse(url.lower()).path
    if "/ar/" in path or path.startswith("/ar"):
        return "ar"
    return "fr"

def clean_html(html_text: str) -> str:
    """ุฅุฒุงู„ุฉ HTML tags ูˆุชู†ุธูŠู ุงู„ู†ุต"""
    if not html_text:
        return ""
    soup = BeautifulSoup(html_text, "html.parser")
    text = soup.get_text(" ", strip=True)
    text = unescape(text)
    text = re.sub(r"\s{3,}", "  ", text)
    return text.strip()

def should_skip(slug: str, title: str) -> bool:
    slug_lower = slug.lower()
    title_lower = title.lower()
    return any(s in slug_lower or s in title_lower for s in SKIP_SLUGS)

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ“ก 1. WordPress REST API
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def fetch_api(endpoint: str) -> list[dict]:
    """ูŠุฌูŠุจ ุงู„ุจูŠุงู†ุงุช ู…ู† WordPress API"""
    all_items = []
    page = 1

    while True:
        url = f"{endpoint}&page={page}"
        try:
            r = requests.get(url, headers=HEADERS, timeout=20)
            if r.status_code == 400:  # No more pages
                break
            r.raise_for_status()
            items = r.json()
            if not items:
                break
            all_items.extend(items)
            # ุฅุฐุง ุฃู‚ู„ ู…ู† 100 โ†’ ุขุฎุฑ ุตูุญุฉ
            if len(items) < 100:
                break
            page += 1
            time.sleep(0.5)  # respectful delay
        except Exception as e:
            print(f"  API error {url[:60]}: {e}")
            break

    return all_items

def process_api_items(items: list[dict], content_type: str) -> list[dict]:
    """ุชุญูˆูŠู„ API items ู„ุตูŠุบุฉ ู…ูˆุญู‘ุฏุฉ"""
    results = []
    for item in items:
        slug = item.get("slug", "")
        title_raw = item.get("title", {}).get("rendered", "")
        title = clean_html(title_raw)
        content_raw = item.get("content", {}).get("rendered", "")
        excerpt_raw = item.get("excerpt", {}).get("rendered", "")
        link = item.get("link", "")
        date = item.get("date", "")[:10]  # YYYY-MM-DD

        if should_skip(slug, title):
            continue

        # ู†ุฌู…ุน ุงู„ู…ุญุชูˆู‰ ุงู„ูƒุงู…ู„
        content = clean_html(content_raw)
        if not content or len(content) < 50:
            content = clean_html(excerpt_raw)
        if not content or len(content) < 50:
            continue

        # ู†ุถูŠู ุงู„ุนู†ูˆุงู† ููŠ ุจุฏุงูŠุฉ ุงู„ู…ุญุชูˆู‰
        full_content = f"{title}\n\n{content}" if title else content

        results.append({
            "page_name": unquote(slug),
            "url": link,
            "source": "ena.tn-api",
            "langue": get_lang(link),
            "category": get_category(link, full_content),
            "content_type": content_type,
            "date": date,
            "content": full_content,
            "chars": len(full_content),
        })

    return results

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ“ฐ 2. RSS Feed
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def fetch_rss(feed_url: str) -> list[dict]:
    """ูŠุฌูŠุจ ุขุฎุฑ ุงู„ุฃุฎุจุงุฑ ู…ู† RSS"""
    results = []
    try:
        r = requests.get(feed_url, headers=HEADERS, timeout=15)
        r.raise_for_status()
        # Clean potential weird characters at start
        content = r.content.strip()
        root = ET.fromstring(content)

        # RSS namespace
        ns = {"content": "http://purl.org/rss/1.0/modules/content/"}

        for item in root.findall(".//item"):
            title = item.findtext("title", "").strip()
            link  = item.findtext("link", "").strip()
            desc  = item.findtext("description", "")
            date  = item.findtext("pubDate", "")[:16]

            # ู…ุญุชูˆู‰ ูƒุงู…ู„ ุฅุฐุง ู…ุชูˆูุฑ
            content_encoded = item.find("content:encoded", ns)
            if content_encoded is not None and content_encoded.text:
                content = clean_html(content_encoded.text)
            else:
                content = clean_html(desc)

            if not content or len(content) < 50:
                continue

            full_content = f"{title}\n\n{content}" if title else content
            slug = urlparse(link).path.strip("/").split("/")[-1]

            results.append({
                "page_name": unquote(slug),
                "url": link,
                "source": "ena.tn-rss",
                "langue": get_lang(link),
                "category": "news_ar" if "/ar/" in link else "news_fr",
                "content_type": "news",
                "date": date,
                "content": full_content,
                "chars": len(full_content),
            })

    except Exception as e:
        print(f"  RSS error {feed_url}: {e}")

    return results

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ—บ๏ธ 3. Sitemap โ†’ Scrape important pages
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def fetch_sitemap_urls(sitemap_url: str) -> list[str]:
    """ูŠุฌูŠุจ ูƒู„ URLs ู…ู† ุงู„ู€ sitemap"""
    urls = []
    try:
        r = requests.get(sitemap_url, headers=HEADERS, timeout=15)
        r.raise_for_status()
        root = ET.fromstring(r.content)
        ns = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
        for loc in root.findall(".//sm:loc", ns):
            if loc.text:
                urls.append(loc.text.strip())
    except Exception as e:
        print(f"  Sitemap error {sitemap_url}: {e}")
    return urls

def scrape_page(url: str) -> dict | None:
    """ูŠุฌูŠุจ ู…ุญุชูˆู‰ ุตูุญุฉ ูˆุงุญุฏุฉ ุจุงู„ู€ scraping"""
    try:
        r = requests.get(url, headers=HEADERS, timeout=20, allow_redirects=True)
        r.raise_for_status()
        soup = BeautifulSoup(r.text, "html.parser")

        # ุฅุฒุงู„ุฉ ุงู„ุนู†ุงุตุฑ ุบูŠุฑ ุงู„ู…ููŠุฏุฉ
        for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
            tag.decompose()
        for tag in soup.find_all(class_=re.compile(r"breadcrumb|menu|sidebar|widget", re.I)):
            tag.decompose()

        text = soup.get_text(" ", strip=True)
        text = re.sub(r"\s{3,}", "  ", text)

        if len(text) < 100:
            return None

        slug = urlparse(url).path.strip("/").split("/")[-1]
        return {
            "page_name": unquote(slug),
            "url": url,
            "source": "ena.tn-scrape",
            "langue": get_lang(url),
            "category": get_category(url),
            "content_type": "page",
            "date": "",
            "content": text,
            "chars": len(text),
        }
    except Exception as e:
        print(f"  skip {url[:60]}: {e}")
        return None

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿš€ MAIN
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

if __name__ == "__main__":
    print("=" * 60)
    print("Step: ENA Scraper v4.0 -- API + RSS + Sitemap")
    print("=" * 60)

    all_data: list[dict] = []
    seen_urls: set[str] = set()
    seen_texts: set[str] = set()

    def add_unique(items: list[dict]):
        for item in items:
            url = item.get("url", "")
            text = item.get("content", "")
            if url not in seen_urls and text not in seen_texts and len(text) > 50:
                all_data.append(item)
                seen_urls.add(url)
                seen_texts.add(text)

    # โ”€โ”€ 1. WordPress API โ”€โ”€
    print("\nStep 1: WordPress REST API...")
    for name, endpoint in API_ENDPOINTS.items():
        print(f"  Fetching {name}...")
        items = fetch_api(endpoint)
        processed = process_api_items(items, "post" if "posts" in name else "page")
        add_unique(processed)
        print(f"  OK: {len(processed)} items from {name}")

    # โ”€โ”€ 2. RSS Feed โ”€โ”€
    print("\nStep 2: RSS Feeds...")
    for feed_url in RSS_FEEDS:
        print(f"  Fetching {feed_url}...")
        items = fetch_rss(feed_url)
        add_unique(items)
        print(f"  OK: {len(items)} items from RSS")

    # โ”€โ”€ 3. Sitemap URLs โ”€โ”€
    print("\nStep 3: Sitemap pages...")
    sitemap_urls = []
    for sm in SITEMAPS:
        urls = fetch_sitemap_urls(sm)
        sitemap_urls.extend(urls)
        print(f"  Found {len(urls)} URLs in {sm.split('/')[-1]}")

    # Scrape sitemap pages not already fetched
    new_urls = [u for u in sitemap_urls if u not in seen_urls]
    print(f"  Scraping {len(new_urls)} new pages from sitemap...")
    for i, url in enumerate(new_urls):
        page = scrape_page(url)
        if page:
            add_unique([page])
        if (i + 1) % 20 == 0:
            print(f"  {i + 1}/{len(new_urls)} scraped...")
        time.sleep(0.3)

    # โ”€โ”€ 4. Priority Pages โ”€โ”€
    print("\nStep 4: Priority pages (concours, conditions)...")
    priority_new = [u for u in PRIORITY_PAGES if u not in seen_urls]
    for url in priority_new:
        page = scrape_page(url)
        if page:
            add_unique([page])
            print(f"  OK: {page['page_name']}")
        time.sleep(0.3)

    # โ”€โ”€ Stats โ”€โ”€
    print("\n" + "=" * 60)
    print(f"OK. Total pages: {len(all_data)}")
    print(f"Total characters: {sum(p['chars'] for p in all_data):,}")

    from collections import Counter
    cats  = Counter(p["category"] for p in all_data)
    langs = Counter(p["langue"] for p in all_data)
    srcs  = Counter(p["source"] for p in all_data)

    print("\nBy category:")
    for cat, count in cats.most_common():
        print(f"   {cat}: {count}")
    print("\nBy language:")
    for lang, count in langs.items():
        print(f"   {lang}: {count}")
    print("\nBy source:")
    for src, count in srcs.items():
        print(f"   {src}: {count}")

    # โ”€โ”€ Save โ”€โ”€
    with open("ena_full_data.json", "w", encoding="utf-8") as f:
        json.dump(all_data, f, ensure_ascii=False, indent=2)

    print("\nSaved to ena_full_data.json")
    print("=" * 60)
    print("Done! Now run: python build_chroma.py")