From eb50660a1bdf5dd848914af8329fb004764e9688 Mon Sep 17 00:00:00 2001 From: soehi <811446351@qq.com> Date: Fri, 4 Dec 2026 14:21:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8B=9B=E8=81=98=E5=85=AC=E5=91=8A=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E6=90=BA=E5=B8=A6=E6=AD=A3=E6=96=87=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements.txt | 4 +- server/recruit.py | 161 +++++++++++++++++++++++++++++++++++++++--- tests/test_recruit.py | 10 ++- 3 files changed, 162 insertions(+), 13 deletions(-) diff --git a/requirements.txt b/requirements.txt index 89f0815..280e3cb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,10 +4,8 @@ SQLAlchemy[asyncio]>=2.0.36,<3 aiosqlite>=0.20,<1 aiosmtplib>=3,<6 pydantic>=2.7,<3 -Pillow>=11,<13 python-docx>=1.1,<2 +Pillow>=10,<13 rapidocr>=3.10,<3.11 onnxruntime>=1.20,<2 -# 仅测试时需要 httpx>=0.27,<1 -python-docx>=1.1,<2 diff --git a/server/recruit.py b/server/recruit.py index db619cf..ccb3f93 100644 --- a/server/recruit.py +++ b/server/recruit.py @@ -3,15 +3,18 @@ from __future__ import annotations import asyncio import io +import re from datetime import datetime from html.parser import HTMLParser from typing import Literal +from urllib.parse import urljoin import httpx from docx import Document -from docx.shared import Pt +from docx.shared import Cm, Pt from fastapi import Depends, HTTPException, Query from fastapi.responses import Response +from PIL import Image from sqlalchemy import func, insert, select from .duty import BEIJING @@ -61,6 +64,118 @@ def html_to_text(content: str) -> str: return parser.text() +def image_url(src: str) -> str: + src = (src or "").strip() + if not src or src.startswith(("data:", "file:")): + return "" + if src.startswith("//"): + return "https:" + src + return urljoin(SOURCE + "/", src) + + +def content_blocks(content: str) -> list[tuple[str, str]]: + """把公告 HTML 拆成按原顺序排列的文字段落和图片。""" + blocks: list[tuple[str, str]] = [] + buffer: list[str] = [] + skip = 0 + + class Parser(HTMLParser): + def flush(self): + text = re.sub(r"[ \t\r\f\v]+", " ", "".join(buffer)).strip() + if text: + blocks.append(("text", text)) + buffer.clear() + + def handle_starttag(self, tag, attrs): + nonlocal skip + if tag in {"script", "style"}: + skip += 1 + if tag == "img": + self.flush() + src = dict(attrs).get("src", "") + source = image_url(src) + if source: + blocks.append(("image", source)) + elif tag in {"p", "div", "section", "br", "tr", "li", "table", "h1", "h2", "h3", "h4"}: + self.flush() + + def handle_endtag(self, tag): + nonlocal skip + if tag in {"script", "style"} and skip: + skip -= 1 + elif tag in {"p", "div", "section", "br", "tr", "li", "table", "h1", "h2", "h3", "h4"}: + self.flush() + + def handle_data(self, data): + if not skip: + buffer.append(data) + + parser = Parser(convert_charrefs=True) + parser.feed(content or "") + parser.close() + parser.flush() + return blocks + + +def is_image_data(body: bytes) -> bool: + return ( + body.startswith(b"\xff\xd8") + or body.startswith(b"\x89PNG\r\n\x1a\n") + or body.startswith((b"GIF87a", b"GIF89a", b"BM", b"II*\x00", b"MM\x00*")) + or (body[:4] == b"RIFF" and body[8:12] == b"WEBP") + ) + + +def normalized_image(body: bytes) -> bytes | None: + try: + with Image.open(io.BytesIO(body)) as image: + if image.format in {"JPEG", "PNG", "GIF", "BMP", "TIFF"}: + return body + image.seek(0) + output = io.BytesIO() + image.convert("RGB").save(output, format="PNG") + return output.getvalue() + except Exception: + return None + + +def add_docx_picture(document, body: bytes) -> bool: + try: + document.add_picture(io.BytesIO(body), width=Cm(15)) + return True + except Exception: + try: + with Image.open(io.BytesIO(body)) as image: + fallback = io.BytesIO() + image.convert("RGB").save(fallback, format="PNG") + document.add_picture(io.BytesIO(fallback.getvalue()), width=Cm(15)) + return True + except Exception: + return False + + +async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None: + headers = [ + {"Referer": SOURCE + "/", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"}, + {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"}, + {"Referer": SOURCE + "/", "User-Agent": "Mozilla/5.0 WorkLog/2.0"}, + ] + for attempt, request_headers in enumerate(headers, 1): + try: + response = await client.get(url, headers=request_headers) + response.raise_for_status() + body = response.content + if is_image_data(body): + normalized = normalized_image(body) + if normalized: + return normalized + except httpx.HTTPError: + pass + if attempt < len(headers): + await asyncio.sleep(0.4 * attempt) + return None + + def public_row(row) -> dict: data = dict(row) data["detail_url"] = data["wailian"] if data["iswailian"] and data["wailian"] else f"{DETAIL_ENDPOINT}/{data['gonggao_id']}" @@ -122,7 +237,27 @@ async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict: return {"fetched": len(rows), "added": added, "updated": updated} -def docx_bytes(rows) -> bytes: +async def docx_bytes(rows, client: httpx.AsyncClient | None = None) -> bytes: + owns_client = client is None + if owns_client: + client = httpx.AsyncClient(timeout=20, follow_redirects=True) + sources = [] + for row in rows: + for kind, value in content_blocks(row["content_html"]): + if kind == "image" and value not in sources: + sources.append(value) + try: + semaphore = asyncio.Semaphore(6) + + async def limited(url): + async with semaphore: + return await fetch_image(client, url) + + results = await asyncio.gather(*(limited(url) for url in sources)) + finally: + if owns_client: + await client.aclose() + images = dict(zip(sources, results)) document = Document() style = document.styles["Normal"] style.font.name = "Microsoft YaHei" @@ -132,8 +267,16 @@ def docx_bytes(rows) -> bytes: meta = " · ".join(value for value in (row["companyname"], row["check_time"][:10], f"截止:{row['valid_time'][:10]}" if row["valid_time"] else "") if value) if meta: document.add_paragraph(meta) - for line in html_to_text(row["content_html"]).splitlines(): - document.add_paragraph(line) + for kind, value in content_blocks(row["content_html"]): + if kind == "text": + document.add_paragraph(value) + else: + body = images.get(value) + if body: + if not add_docx_picture(document, body): + document.add_paragraph("[公告图片格式不受支持]") + else: + document.add_paragraph("[公告图片未能下载]") if index < len(rows): document.add_page_break() output = io.BytesIO() @@ -148,9 +291,11 @@ def markdown_bytes(rows) -> bytes: meta = [value for value in (row["companyname"], row["check_time"], row["valid_time"]) if value] if meta: lines.append(f"- {' / '.join(meta)}") - body = html_to_text(row["content_html"]) - if body: - lines.extend([body, ""]) + for kind, value in content_blocks(row["content_html"]): + if kind == "text": + lines.extend([value, ""]) + else: + lines.extend([f"![公告图片]({value})", ""]) link = row["wailian"] if row["iswailian"] and row["wailian"] else f"{DETAIL_ENDPOINT}/{row['gonggao_id']}" lines.append(f"原文链接:{link}") sections.append("\n".join(lines)) @@ -210,7 +355,7 @@ def install(app, get_db, current_user): raise HTTPException(404, "没有匹配的公告") stamp = datetime.now(BEIJING).strftime("%Y%m%d-%H%M%S") if format == "docx": - body, extension, media_type = docx_bytes(rows), "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + body, extension, media_type = await docx_bytes(rows), "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" else: body, extension, media_type = markdown_bytes(rows), "md", "text/markdown; charset=utf-8" scope = "recruit" if len(rows) > 1 else f"recruit-{rows[0]['gonggao_id']}" diff --git a/tests/test_recruit.py b/tests/test_recruit.py index e6c5dff..0105ec3 100644 --- a/tests/test_recruit.py +++ b/tests/test_recruit.py @@ -3,6 +3,7 @@ from __future__ import annotations import unittest from unittest.mock import patch from unittest.mock import AsyncMock +import base64 from docx import Document from io import BytesIO @@ -14,7 +15,7 @@ from server import recruit RAW = { "gonggaoId": 1, "gonggaoTitle": "测试公告", - "gonggaoContent": "

第一段

第二段
", + "gonggaoContent": '

第一段

第二段
', "companyname": "测试单位", "createTime": "2026-11-01 10:00:00", "checkTime": "2026-11-02 10:00:00", @@ -25,6 +26,8 @@ RAW = { "url": "", } +PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=") + class RecruitTests(ApiTestCase): async def test_sync_list_detail_and_exports(self): @@ -41,12 +44,15 @@ class RecruitTests(ApiTestCase): self.assertTrue(rows['items'][0]['detail_url'].endswith('/1')) detail = (await self.client.get('/api/recruit/announcements/1', headers=auth(owner['token']))).json() self.assertEqual(detail['title'], '测试公告') - response = await self.client.get('/api/recruit/export', params={'ids': '1', 'format': 'docx'}, headers=auth(owner['token'])) + with patch.object(recruit, 'fetch_image', new=AsyncMock(return_value=PNG)): + response = await self.client.get('/api/recruit/export', params={'ids': '1', 'format': 'docx'}, headers=auth(owner['token'])) self.assertEqual(response.status_code, 200) document = Document(BytesIO(response.content)) self.assertIn('第一段', '\n'.join(p.text for p in document.paragraphs)) + self.assertEqual(len(document.inline_shapes), 1) response = await self.client.get('/api/recruit/export', params={'ids': '1', 'format': 'markdown'}, headers=auth(owner['token'])) self.assertIn('第一段', response.text) + self.assertIn('![公告图片](https://example.com/a.png)', response.text) self.assertIn('原文链接', response.text) response = await self.client.get('/api/recruit/export', headers=auth(owner['token'])) self.assertEqual(response.status_code, 422)