File size: 4,649 Bytes
6d9ee7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import csv
import time
import json
import random
import sys
import html as html_lib
from urllib.request import Request, urlopen
from urllib.parse import urlparse, parse_qs

# Configuration
BASE_URL = "https://tnc-platform.web.app"
SITEMAP_URL = f"{BASE_URL}/sitemap.xml"
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
# Firestore API Config
FIRESTORE_API_KEY = "AIzaSyA5AUOLUfpZ9VE0zWhi8-hF7t48_5wnT0s"
FIRESTORE_BASE_URL = "https://firestore.googleapis.com/v1/projects/tnc-platform/databases/(default)/documents/archive"

CSV_FILE = "tnc_seminars.csv"
JSONL_FILE = "tnc_seminars.jsonl"

def fetch_url(url):
    """Fetches URL content with a custom User-Agent."""
    try:
        req = Request(url, headers={"User-Agent": USER_AGENT})
        with urlopen(req, timeout=15) as response:
            return response.read().decode("utf-8", errors="replace")
    except Exception as e:
        print(f"Error fetching {url}: {e}", file=sys.stderr)
        return ""

def get_full_description(course_id):
    """Fetches the full description directly from Firestore REST API."""
    api_url = f"{FIRESTORE_BASE_URL}/{course_id}?key={FIRESTORE_API_KEY}"
    raw_json = fetch_url(api_url)
    if not raw_json:
        return ""
    
    try:
        data = json.loads(raw_json)
        # Firestore structure: fields -> description -> stringValue
        desc = data.get("fields", {}).get("description", {}).get("stringValue", "")
        
        # Cleanup: Remove "DESCRIPTION:" prefix if present
        if desc.upper().startswith("DESCRIPTION:"):
            desc = desc[len("DESCRIPTION:"):].strip()
        
        # Unescape HTML entities (like \u003cem\u003e or &)
        desc = html_lib.unescape(desc)
        # Optional: Remove HTML tags if they exist (like <em>)
        desc = re.sub(r'<[^>]+>', '', desc)
        
        return desc.strip()
    except Exception as e:
        print(f"Error parsing Firestore data for {course_id}: {e}", file=sys.stderr)
        return ""

def clean_title(title):
    """Removes the branding suffix from the title."""
    for sep in [" — ", " – ", " - "]:
        if sep in title:
            title = title.split(sep)[0]
    return html_lib.unescape(title.strip())

def main():
    print("Discovering seminars from sitemap...", file=sys.stderr)
    sitemap_xml = fetch_url(SITEMAP_URL)
    
    # Identify all course URLs
    # Pattern: https://tnc-platform.web.app/archive/course.html?id=13106
    course_urls = re.findall(r'<loc>(https://tnc-platform.web.app/archive/course.html\?id=(\d+))</loc>', sitemap_xml)
    
    # Deduplicate and sort
    seen_ids = set()
    unique_courses = []
    for url, cid in course_urls:
        if cid not in seen_ids:
            seen_ids.add(cid)
            unique_courses.append((url, cid))
    
    unique_courses.sort(key=lambda x: x[1], reverse=True) # Newest first
    print(f"Discovered {len(unique_courses)} seminars.", file=sys.stderr)

    if not unique_courses:
        print("No seminar URLs found in sitemap.", file=sys.stderr)
        return

    # Open both files for incremental writing
    with open(CSV_FILE, "w", encoding="utf-8", newline="") as f_csv, \
         open(JSONL_FILE, "w", encoding="utf-8") as f_jsonl:
        
        writer = csv.writer(f_csv)
        writer.writerow(["Seminar Title", "Seminar Description"])

        for i, (url, cid) in enumerate(unique_courses, 1):
            print(f"[{i}/{len(unique_courses)}] Scraping: {cid}", file=sys.stderr)
            
            # 1. Get Title from HTML (still easiest)
            html_text = fetch_url(url)
            title = "Unknown"
            if html_text:
                title_match = re.search(r"<title>(.*?)</title>", html_text, re.S | re.I)
                title = clean_title(title_match.group(1)) if title_match else "Unknown"

            # 2. Get FULL Description from Firestore API
            desc = get_full_description(cid)

            if title or desc:
                # Write to CSV
                writer.writerow([title, desc])
                f_csv.flush()
                
                # Write to JSONL
                json_row = json.dumps({"title": title, "description": desc}, ensure_ascii=False)
                f_jsonl.write(json_row + "\n")
                f_jsonl.flush()

            # Polite delay
            time.sleep(random.uniform(0.1, 0.3))

    print(f"\nSuccess! Full dataset saved to:", file=sys.stderr)
    print(f" - {CSV_FILE}", file=sys.stderr)
    print(f" - {JSONL_FILE}", file=sys.stderr)

if __name__ == "__main__":
    main()