Spaces:
Runtime error

File size: 6,393 Bytes
a0e8676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e133e72
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
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
from __future__ import annotations

import hashlib
import io
import re
import tempfile
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from typing import Iterable
from urllib.parse import urljoin

import fitz
import httpx
from bs4 import BeautifulSoup
from docx import Document

from .config import REQUEST_TIMEOUT_SECONDS, SITE_BASE_URL


@dataclass(frozen=True)
class NoticeLink:
    category: str
    title: str
    url: str
    publish_date: date | None


@dataclass(frozen=True)
class Attachment:
    name: str
    url: str
    text: str


@dataclass(frozen=True)
class ParsedDocument:
    category: str
    title: str
    url: str
    publish_date: date | None
    content: str
    attachments: list[Attachment]
    content_hash: str


def fetch_text(url: str) -> str:
    headers = {
        "User-Agent": "CampusVerifyBot/0.1 (+public academic affairs sync)",
    }
    with httpx.Client(timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=True, headers=headers) as client:
        response = client.get(url)
        response.raise_for_status()
        response.encoding = "utf-8"
        return response.text


def fetch_bytes(url: str) -> bytes:
    headers = {
        "User-Agent": "CampusVerifyBot/0.1 (+public academic affairs sync)",
    }
    with httpx.Client(timeout=REQUEST_TIMEOUT_SECONDS, follow_redirects=True, headers=headers) as client:
        response = client.get(url)
        response.raise_for_status()
        return response.content


def clean_text(text: str) -> str:
    text = text.replace("\xa0", " ")
    text = re.sub(r"[ \t]+", " ", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def parse_date(value: str) -> date | None:
    match = re.search(r"(20\d{2})[-年/.](\d{1,2})[-月/.](\d{1,2})", value)
    if not match:
        return None
    year, month, day = (int(part) for part in match.groups())
    return date(year, month, day)


def absolute_url(base_url: str, href: str) -> str:
    return urljoin(base_url, href)


def extract_notice_links(category: str, list_url: str) -> list[NoticeLink]:
    soup = BeautifulSoup(fetch_text(list_url), "lxml")
    notices: list[NoticeLink] = []

    for anchor in soup.select(".lists li a[href], .lists a[href]"):
        href = anchor.get("href")
        if not href:
            continue
        url = absolute_url(list_url, href)
        if "/info/" not in url or not url.endswith(".htm"):
            continue

        span = anchor.find("span")
        publish_date = parse_date(span.get_text(" ", strip=True) if span else "")
        if span:
            span.extract()
        title = clean_text(anchor.get_text(" ", strip=True))
        if title:
            notices.append(NoticeLink(category=category, title=title, url=url, publish_date=publish_date))

    seen: set[str] = set()
    unique_notices: list[NoticeLink] = []
    for notice in notices:
        if notice.url not in seen:
            unique_notices.append(notice)
            seen.add(notice.url)
    return unique_notices


def discover_paged_urls(seed_url: str, max_pages: int) -> list[str]:
    urls = [seed_url]
    soup = BeautifulSoup(fetch_text(seed_url), "lxml")
    for anchor in soup.select(".p_pages a[href]"):
        href = anchor.get("href")
        if not href:
            continue
        url = absolute_url(seed_url, href)
        if url not in urls:
            urls.append(url)
        if len(urls) >= max_pages:
            break
    return urls


def extract_docx_text(data: bytes) -> str:
    with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as tmp:
        tmp.write(data)
        tmp_path = Path(tmp.name)
    try:
        document = Document(str(tmp_path))
        return clean_text("\n".join(paragraph.text for paragraph in document.paragraphs))
    finally:
        tmp_path.unlink(missing_ok=True)


def extract_pdf_text(data: bytes) -> str:
    document = fitz.open(stream=data, filetype="pdf")
    return clean_text("\n".join(page.get_text() for page in document))


def extract_attachment_text(name: str, data: bytes) -> str:
    suffix = Path(name).suffix.lower()
    if suffix == ".pdf":
        return extract_pdf_text(data)
    if suffix == ".docx":
        return extract_docx_text(data)
    return ""


def extract_attachments(soup: BeautifulSoup, detail_url: str) -> list[Attachment]:
    attachments: list[Attachment] = []
    for anchor in soup.select('a[href*="download.jsp"], a[href$=".pdf"], a[href$=".docx"]'):
        href = anchor.get("href")
        if not href:
            continue
        url = absolute_url(SITE_BASE_URL, href) if href.startswith("/") else absolute_url(detail_url, href)
        name = clean_text(anchor.get_text(" ", strip=True)) or Path(url).name
        try:
            data = fetch_bytes(url)
            text = extract_attachment_text(name, data)
        except Exception as exc:
            text = f"[附件解析失败: {exc}]"
        attachments.append(Attachment(name=name, url=url, text=text))
    return attachments


def parse_detail(notice: NoticeLink) -> ParsedDocument:
    html = fetch_text(notice.url)
    soup = BeautifulSoup(html, "lxml")

    title_node = soup.select_one(".art-tit h3, .cont-tit h3, h1")
    title = clean_text(title_node.get_text(" ", strip=True)) if title_node else notice.title

    date_node = soup.select_one(".art-tit p, .cont-tit p")
    publish_date = parse_date(date_node.get_text(" ", strip=True)) if date_node else notice.publish_date
    publish_date = publish_date or notice.publish_date

    content_node = soup.select_one(".v_news_content, #vsb_content_6, .art-body")
    content = clean_text(content_node.get_text("\n", strip=True)) if content_node else ""
    attachments = extract_attachments(soup, notice.url)
    hash_source = "\n".join([title, notice.url, content, *(item.text for item in attachments)])
    content_hash = hashlib.sha256(hash_source.encode("utf-8")).hexdigest()

    return ParsedDocument(
        category=notice.category,
        title=title,
        url=notice.url,
        publish_date=publish_date,
        content=content,
        attachments=attachments,
        content_hash=content_hash,
    )


def iter_notices(category: str, seed_url: str, max_pages: int) -> Iterable[NoticeLink]:
    for list_url in discover_paged_urls(seed_url, max_pages):
        yield from extract_notice_links(category, list_url)