Spaces:
Runtime error

File size: 4,915 Bytes
a0e8676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
from datetime import datetime, timezone

from .config import DEFAULT_MAX_PAGES_PER_CATEGORY, DEPARTMENT, SEED_URLS, SOURCE_NAME
from .db import db_cursor
from .parser import ParsedDocument, iter_notices, parse_detail


def serialize_document(doc: ParsedDocument) -> dict:
    return {
        "source_name": SOURCE_NAME,
        "source_type": "official_website",
        "category": doc.category,
        "title": doc.title,
        "department": DEPARTMENT,
        "publish_date": doc.publish_date,
        "source_url": doc.url,
        "content": doc.content,
        "content_hash": doc.content_hash,
        "attachments": json.dumps(
            [{"name": item.name, "url": item.url, "text": item.text} for item in doc.attachments],
            ensure_ascii=False,
        ),
    }


def upsert_document(doc: ParsedDocument) -> bool:
    record = serialize_document(doc)
    with db_cursor() as cur:
        cur.execute("select content_hash from campus_documents where source_url = %s", (doc.url,))
        existing = cur.fetchone()
        changed = existing is None or existing["content_hash"] != doc.content_hash
        cur.execute(
            """
            insert into campus_documents (
              source_name, source_type, category, title, department, publish_date,
              source_url, content, content_hash, attachments, last_checked_at
            )
            values (
              %(source_name)s, %(source_type)s, %(category)s, %(title)s, %(department)s,
              %(publish_date)s, %(source_url)s, %(content)s, %(content_hash)s,
              %(attachments)s::jsonb, now()
            )
            on conflict (source_url) do update set
              category = excluded.category,
              title = excluded.title,
              department = excluded.department,
              publish_date = excluded.publish_date,
              content = excluded.content,
              attachments = excluded.attachments,
              content_hash = excluded.content_hash,
              last_checked_at = now(),
              updated_at = case
                when campus_documents.content_hash is distinct from excluded.content_hash then now()
                else campus_documents.updated_at
              end
            """,
            record,
        )
        return changed


def create_sync_run() -> int:
    with db_cursor() as cur:
        cur.execute("insert into sync_runs(status) values ('running') returning id")
        return int(cur.fetchone()["id"])


def finish_sync_run(run_id: int, status: str, scanned: int, upserted: int, error: str | None = None) -> None:
    with db_cursor() as cur:
        cur.execute(
            """
            update sync_runs
            set finished_at = now(), status = %s, scanned_count = %s, upserted_count = %s, error = %s
            where id = %s
            """,
            (status, scanned, upserted, error, run_id),
        )


def run_sync(max_pages_per_category: int = DEFAULT_MAX_PAGES_PER_CATEGORY, limit: int | None = None) -> dict:
    run_id = create_sync_run()
    scanned = 0
    upserted = 0
    errors: list[str] = []

    try:
        seen_urls: set[str] = set()
        for category, seed_url in SEED_URLS:
            for notice in iter_notices(category, seed_url, max_pages_per_category):
                if notice.url in seen_urls:
                    continue
                seen_urls.add(notice.url)
                if limit is not None and scanned >= limit:
                    break
                scanned += 1
                try:
                    document = parse_detail(notice)
                    if upsert_document(document):
                        upserted += 1
                except Exception as exc:
                    errors.append(f"{notice.url}: {exc}")
            if limit is not None and scanned >= limit:
                break

        status = "partial_success" if errors else "success"
        finish_sync_run(run_id, status, scanned, upserted, "\n".join(errors) if errors else None)
        return {
            "run_id": run_id,
            "status": status,
            "scanned_count": scanned,
            "upserted_count": upserted,
            "errors": errors,
            "finished_at": datetime.now(timezone.utc).isoformat(),
        }
    except Exception as exc:
        finish_sync_run(run_id, "failed", scanned, upserted, str(exc))
        raise


def main() -> None:
    parser = argparse.ArgumentParser(description="Sync MYCC academic affairs public notices.")
    parser.add_argument("--max-pages", type=int, default=DEFAULT_MAX_PAGES_PER_CATEGORY)
    parser.add_argument("--limit", type=int, default=None)
    args = parser.parse_args()
    print(json.dumps(run_sync(max_pages_per_category=args.max_pages, limit=args.limit), ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()