招聘公告导出携带正文图片

This commit is contained in:
2026-12-04 14:21:47 +08:00
parent bf9f8dc089
commit eb50660a1b
3 changed files with 162 additions and 13 deletions
+153 -8
View File
@@ -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']}"