mainspacy.py 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608
  1. # -*- coding: utf-8 -*-
  2. """Grammar highlighter powered by spaCy + benepar constituency parsing."""
  3. import asyncio
  4. import html
  5. import json
  6. import re
  7. from collections import Counter
  8. from dataclasses import dataclass, field
  9. from html.parser import HTMLParser
  10. from string import Template
  11. from typing import Any, Dict, List, Optional, Tuple
  12. from urllib import error as urllib_error, request as urllib_request
  13. from urllib.parse import urlparse, urlunparse
  14. import benepar
  15. import httpx
  16. import spacy
  17. from fastapi import FastAPI, HTTPException
  18. from fastapi.middleware.cors import CORSMiddleware
  19. from fastapi.responses import HTMLResponse
  20. from pydantic import BaseModel, Field
  21. from spacy.cli import download as spacy_download
  22. from spacy.language import Language
  23. from spacy.tokens import Span as SpacySpan, Token as SpacyToken
  24. from style_config import STYLE_BLOCK
  25. BENE_PAR_WARNING: Optional[str] = None
  26. HAS_BENEPAR: bool = False # new: track whether benepar was successfully attached
  27. def _ensure_benepar_warning(message: str) -> None:
  28. """Record a warning once when benepar annotations are unavailable."""
  29. global BENE_PAR_WARNING
  30. if not BENE_PAR_WARNING:
  31. BENE_PAR_WARNING = message
  32. def _load_spacy_pipeline(
  33. model_name: str = "en_core_web_sm", benepar_model: str = "benepar_en3"
  34. ) -> Language:
  35. global BENE_PAR_WARNING, HAS_BENEPAR
  36. BENE_PAR_WARNING = None
  37. HAS_BENEPAR = False
  38. try:
  39. nlp = spacy.load(model_name)
  40. except OSError:
  41. try:
  42. spacy_download(model_name)
  43. nlp = spacy.load(model_name)
  44. except Exception as exc: # pragma: no cover - install helper
  45. raise RuntimeError(
  46. f"spaCy model '{model_name}' is required. Install via `python -m spacy download {model_name}`."
  47. ) from exc
  48. # Ensure we have sentence segmentation available
  49. pipe_names = set(nlp.pipe_names)
  50. if not ({"parser", "senter", "sentencizer"} & pipe_names):
  51. try:
  52. nlp.add_pipe("sentencizer")
  53. except Exception:
  54. pass # if already present or unavailable, ignore
  55. # Try to add benepar
  56. if "benepar" not in nlp.pipe_names:
  57. try:
  58. nlp.add_pipe("benepar", config={"model": benepar_model}, last=True)
  59. HAS_BENEPAR = True
  60. except ValueError:
  61. try:
  62. benepar.download(benepar_model)
  63. nlp.add_pipe("benepar", config={"model": benepar_model}, last=True)
  64. HAS_BENEPAR = True
  65. except Exception as exc: # pragma: no cover - install helper
  66. HAS_BENEPAR = False
  67. BENE_PAR_WARNING = (
  68. "Benepar model '{model}' unavailable ({err}). Falling back to dependency-based spans."
  69. ).format(model=benepar_model, err=exc)
  70. except Exception as exc:
  71. HAS_BENEPAR = False
  72. BENE_PAR_WARNING = (
  73. "Failed to attach benepar parser to spaCy pipeline. Falling back to dependency-based spans ({err})."
  74. ).format(err=exc)
  75. else:
  76. HAS_BENEPAR = True
  77. return nlp
  78. try:
  79. NLP: Optional[Language] = _load_spacy_pipeline()
  80. NLP_LOAD_ERROR: Optional[Exception] = None
  81. except Exception as exc: # pragma: no cover - import-time diagnostics
  82. NLP = None
  83. NLP_LOAD_ERROR = exc
  84. class AnalyzeRequest(BaseModel):
  85. text: str = Field(..., description="Raw English text to highlight")
  86. class AnalyzeResponse(BaseModel):
  87. highlighted_html: str
  88. @dataclass
  89. class Token:
  90. text: str
  91. start: int
  92. end: int
  93. kind: str # 'word' | 'space' | 'punct'
  94. @dataclass
  95. class Span:
  96. start_token: int
  97. end_token: int
  98. cls: str
  99. attrs: Optional[Dict[str, str]] = None
  100. @dataclass
  101. class SentenceSummary:
  102. subjects: List[str] = field(default_factory=list)
  103. predicates: List[str] = field(default_factory=list)
  104. objects: List[str] = field(default_factory=list)
  105. complements: List[str] = field(default_factory=list)
  106. clauses: List[str] = field(default_factory=list)
  107. clause_functions: List[str] = field(default_factory=list)
  108. connectors: List[str] = field(default_factory=list)
  109. residual_roles: List[str] = field(default_factory=list)
  110. sentence_length: int = 0
  111. TOKEN_REGEX = re.compile(
  112. r"""
  113. (?:\s+)
  114. |(?:\d+(?:[\.,]\d+)*)
  115. |(?:\w+(?:[-']\w+)*)
  116. |(?:.)
  117. """,
  118. re.VERBOSE | re.UNICODE,
  119. )
  120. WORD_LIKE_RE = re.compile(r"\w+(?:[-']\w+)*\Z", re.UNICODE)
  121. NUMBER_RE = re.compile(r"\d+(?:[\.,]\d+)*\Z", re.UNICODE)
  122. PARAGRAPH_BREAK_RE = re.compile(r"(?:\r?\n[ \t]*){2,}")
  123. SUBJECT_DEPS = {"nsubj", "nsubjpass", "csubj", "csubjpass"}
  124. DIRECT_OBJECT_DEPS = {"dobj", "obj"}
  125. INDIRECT_OBJECT_DEPS = {"iobj", "dative"}
  126. COMPLEMENT_DEPS = {"attr", "oprd", "acomp", "ccomp", "xcomp"}
  127. ADVERBIAL_DEPS = {"advmod", "npadvmod", "advcl", "obl", "prep", "pcomp"}
  128. RELATIVE_PRONOUNS = {"which", "that", "who", "whom", "whose", "where", "when"}
  129. SUBORDINATORS_TO_FUNCTION = {
  130. "when": "TIME",
  131. "while": "TIME",
  132. "after": "TIME",
  133. "before": "TIME",
  134. "until": "TIME",
  135. "as": "TIME",
  136. "once": "TIME",
  137. "since": "TIME",
  138. "because": "REASON",
  139. "now that": "REASON",
  140. "if": "CONDITION",
  141. "unless": "CONDITION",
  142. "provided": "CONDITION",
  143. "provided that": "CONDITION",
  144. "although": "CONCESSION",
  145. "though": "CONCESSION",
  146. "even though": "CONCESSION",
  147. "whereas": "CONCESSION",
  148. "so that": "RESULT",
  149. "so": "RESULT",
  150. "lest": "PURPOSE",
  151. "in order that": "PURPOSE",
  152. }
  153. FINITE_VERB_TAGS = {"VBD", "VBP", "VBZ"}
  154. NONFINITE_VERB_TAGS = {"VBG", "VBN"}
  155. FIXED_MULTIWORD_PHRASES: Tuple[Tuple[re.Pattern, str], ...] = tuple(
  156. (
  157. re.compile(pattern, re.IGNORECASE),
  158. label,
  159. )
  160. for pattern, label in [
  161. (r"\bas well as\b", "as well as"),
  162. (r"\brather than\b", "rather than"),
  163. (r"\bin addition to\b", "in addition to"),
  164. (r"\bin spite of\b", "in spite of"),
  165. (r"\baccording to\b", "according to"),
  166. (r"\bas soon as\b", "as soon as"),
  167. ]
  168. )
  169. CLAUSE_FUNCTION_LABELS = {
  170. "TIME": "时间",
  171. "REASON": "原因",
  172. "CONDITION": "条件",
  173. "CONCESSION": "让步",
  174. "RESULT": "结果",
  175. "PURPOSE": "目的",
  176. }
  177. RESIDUAL_DEP_LABELS = {
  178. "det": "限定词",
  179. "prep": "介词",
  180. "case": "介词标记",
  181. "cc": "并列连词",
  182. "mark": "从属连词",
  183. "poss": "所有格标记",
  184. "nummod": "数量修饰语",
  185. "aux": "助动词",
  186. "prt": "小品词",
  187. }
  188. RESIDUAL_POS_LABELS = {
  189. "ADJ": "形容词修饰语",
  190. "ADV": "副词",
  191. "NUM": "数词",
  192. "PRON": "代词",
  193. }
  194. def _classify_segment(seg: str) -> str:
  195. if not seg:
  196. return "punct"
  197. if seg.isspace():
  198. return "space"
  199. if NUMBER_RE.fullmatch(seg) or WORD_LIKE_RE.fullmatch(seg):
  200. return "word"
  201. return "punct"
  202. def _append_fallback_tokens(text: str, start: int, end: int, tokens: List[Token]) -> None:
  203. for idx in range(start, end):
  204. ch = text[idx]
  205. if ch.isspace():
  206. kind = "space"
  207. elif ch.isalnum() or ch == "_":
  208. kind = "word"
  209. else:
  210. kind = "punct"
  211. tokens.append(Token(ch, idx, idx + 1, kind))
  212. def tokenize_preserve(text: str) -> List[Token]:
  213. tokens: List[Token] = []
  214. if not text:
  215. return tokens
  216. last_end = 0
  217. for match in TOKEN_REGEX.finditer(text):
  218. if match.start() > last_end:
  219. _append_fallback_tokens(text, last_end, match.start(), tokens)
  220. seg = text[match.start() : match.end()]
  221. tokens.append(Token(seg, match.start(), match.end(), _classify_segment(seg)))
  222. last_end = match.end()
  223. if last_end < len(text):
  224. _append_fallback_tokens(text, last_end, len(text), tokens)
  225. if not tokens and text:
  226. tokens = [Token(text, 0, len(text), "word" if text[0].isalnum() else "punct")]
  227. return tokens
  228. def build_char_to_token_map(tokens: List[Token]) -> Dict[int, int]:
  229. mapping: Dict[int, int] = {}
  230. for idx, tok in enumerate(tokens):
  231. for pos in range(tok.start, tok.end):
  232. mapping[pos] = idx
  233. return mapping
  234. def char_span_to_token_span(
  235. char_start: int, char_end: int, mapping: Dict[int, int]
  236. ) -> Tuple[int, int]:
  237. if char_end <= char_start:
  238. return -1, -1
  239. start_idx = mapping.get(char_start)
  240. end_idx = mapping.get(char_end - 1)
  241. if start_idx is None or end_idx is None:
  242. return -1, -1
  243. return start_idx, end_idx + 1
  244. def add_char_based_span(
  245. spans: List[Span],
  246. char_start: int,
  247. char_end: int,
  248. cls: str,
  249. mapping: Dict[int, int],
  250. attrs: Optional[Dict[str, str]] = None,
  251. ) -> None:
  252. s_tok, e_tok = char_span_to_token_span(char_start, char_end, mapping)
  253. if s_tok < 0 or e_tok < 0:
  254. return
  255. safe_attrs = None
  256. if attrs:
  257. safe_attrs = {k: html.escape(v, quote=True) for k, v in attrs.items() if v}
  258. spans.append(Span(start_token=s_tok, end_token=e_tok, cls=cls, attrs=safe_attrs))
  259. def add_span(spans: List[Span], start_token: int, end_token: int, cls: str, attrs: Optional[Dict[str, str]] = None):
  260. if start_token < 0 or end_token < 0 or end_token <= start_token:
  261. return
  262. spans.append(Span(start_token=start_token, end_token=end_token, cls=cls, attrs=attrs))
  263. def subtree_char_span(token: SpacyToken) -> Tuple[int, int]:
  264. subtree = list(token.subtree)
  265. if not subtree:
  266. return token.idx, token.idx + len(token.text)
  267. return subtree[0].idx, subtree[-1].idx + len(subtree[-1].text)
  268. def _subtree_text(token: SpacyToken) -> str:
  269. span = token.doc[token.left_edge.i : token.right_edge.i + 1]
  270. return span.text
  271. def _find_antecedent_word(sentence: SpacySpan, clause_start_char: int) -> Optional[str]:
  272. candidate = None
  273. for tok in sentence:
  274. if tok.idx >= clause_start_char:
  275. break
  276. if tok.pos_ in {"NOUN", "PROPN", "PRON"}:
  277. candidate = tok.text
  278. return candidate
  279. def _is_nonfinite_clause(span: SpacySpan) -> bool:
  280. tags = {tok.tag_ for tok in span if tok.tag_}
  281. if tags & FINITE_VERB_TAGS:
  282. return False
  283. if "TO" in tags or tags & NONFINITE_VERB_TAGS:
  284. return True
  285. return False
  286. def _classify_noun_clause(span: SpacySpan) -> Optional[str]:
  287. deps = {tok.dep_ for tok in span}
  288. if deps & {"csubj", "csubjpass"}:
  289. return "subject"
  290. if deps & {"ccomp", "xcomp"}:
  291. return "complement"
  292. if deps & {"dobj", "obj"}:
  293. return "object"
  294. return None
  295. def _split_paragraph_ranges(text: str) -> List[Tuple[int, int]]:
  296. """Return inclusive paragraph ranges, keeping separators intact."""
  297. if not text:
  298. return [(0, 0)]
  299. ranges: List[Tuple[int, int]] = []
  300. start = 0
  301. for match in PARAGRAPH_BREAK_RE.finditer(text):
  302. ranges.append((start, match.start()))
  303. start = match.end()
  304. ranges.append((start, len(text)))
  305. # Ensure at least one range and sorted order
  306. if not ranges:
  307. ranges = [(0, len(text))]
  308. return ranges
  309. def _circled_number(value: int) -> str:
  310. """Return the circled number style for sentence numbering."""
  311. if value <= 0:
  312. return ""
  313. if value <= 20:
  314. return chr(ord("\u2460") + value - 1)
  315. if 21 <= value <= 35:
  316. return chr(ord("\u3251") + value - 21)
  317. if 36 <= value <= 50:
  318. return chr(ord("\u32B1") + value - 36)
  319. return f"({value})"
  320. def annotate_constituents(
  321. sentence: SpacySpan,
  322. spans: List[Span],
  323. mapping: Dict[int, int],
  324. sentence_start_char: int,
  325. sentence_end_char: int,
  326. summary: Optional[SentenceSummary] = None,
  327. ) -> None:
  328. # If benepar is not attached or a previous warning indicates fallback, skip.
  329. if not HAS_BENEPAR or BENE_PAR_WARNING:
  330. _ensure_benepar_warning(
  331. "Benepar component missing or unavailable. Using dependency-based spans."
  332. )
  333. return
  334. # If the extension is not present, skip
  335. if not SpacySpan.has_extension("constituents"):
  336. _ensure_benepar_warning(
  337. "Benepar component missing from spaCy pipeline. Falling back to dependency spans."
  338. )
  339. return
  340. try:
  341. constituents = sentence._.constituents
  342. except Exception as exc:
  343. # Catch any error while accessing benepar results and fallback safely
  344. _ensure_benepar_warning(
  345. f"Benepar constituency parse unavailable: {exc}. Falling back to dependency spans."
  346. )
  347. return
  348. seen_ranges = set()
  349. for const in constituents:
  350. label = getattr(const, "label_", None)
  351. if not label:
  352. continue
  353. start_char, end_char = const.start_char, const.end_char
  354. if start_char == sentence_start_char and end_char == sentence_end_char:
  355. continue # skip the entire sentence span itself
  356. key = (start_char, end_char, label)
  357. is_relative = False
  358. if label in {"PP", "ADVP"}:
  359. if key in seen_ranges:
  360. continue
  361. seen_ranges.add(key)
  362. add_char_based_span(spans, start_char, end_char, "role-adverbial", mapping)
  363. continue
  364. if label == "SBAR" and const:
  365. first_token = const[0]
  366. lowered = first_token.text.lower()
  367. if lowered in RELATIVE_PRONOUNS:
  368. antecedent = _find_antecedent_word(sentence, start_char)
  369. attrs = {"data-modifies": antecedent} if antecedent else None
  370. add_char_based_span(spans, start_char, end_char, "clause-relative", mapping, attrs)
  371. if summary:
  372. summary.clauses.append("定语从句")
  373. is_relative = True
  374. else:
  375. function = SUBORDINATORS_TO_FUNCTION.get(lowered)
  376. attrs = {"data-function": function}
  377. add_char_based_span(spans, start_char, end_char, "clause-adverbial", mapping, attrs)
  378. if summary:
  379. summary.clauses.append("状语从句")
  380. if function:
  381. summary.clause_functions.append(function)
  382. continue
  383. if label in {"S", "VP"}:
  384. if _is_nonfinite_clause(const):
  385. add_char_based_span(spans, start_char, end_char, "clause-nonfinite", mapping)
  386. if summary:
  387. summary.clauses.append("非限定结构")
  388. continue
  389. if label == "S" and not is_relative:
  390. role = _classify_noun_clause(const)
  391. if role:
  392. attrs = {"data-clause-role": role}
  393. add_char_based_span(spans, start_char, end_char, "clause-noun", mapping, attrs)
  394. if summary:
  395. summary.clauses.append(f"名词性从句({role})")
  396. def _predicate_span_bounds(head: SpacyToken) -> Tuple[int, int]:
  397. """Return a character range covering predicate head + functional dependents."""
  398. tokens = [head]
  399. for child in head.children:
  400. if child.dep_ in {"aux", "auxpass", "prt", "cop", "neg"}:
  401. tokens.append(child)
  402. start_char = min(tok.idx for tok in tokens)
  403. end_char = max(tok.idx + len(tok.text) for tok in tokens)
  404. return start_char, end_char
  405. def _predicate_heads(sentence: SpacySpan) -> List[SpacyToken]:
  406. """Collect predicate heads including coordinated verbs."""
  407. candidates: List[SpacyToken] = []
  408. for tok in sentence:
  409. if tok.pos_ not in {"VERB", "AUX"} and tok.tag_ not in FINITE_VERB_TAGS:
  410. continue
  411. if tok.dep_ == "ROOT":
  412. candidates.append(tok)
  413. continue
  414. if tok.dep_ == "conj" and tok.head.pos_ in {"VERB", "AUX"}:
  415. candidates.append(tok)
  416. continue
  417. if tok.dep_ in {"ccomp", "xcomp", "advcl", "acl", "relcl", "parataxis"}:
  418. candidates.append(tok)
  419. seen = set()
  420. ordered: List[SpacyToken] = []
  421. for tok in sorted(candidates, key=lambda t: t.i):
  422. if tok.i in seen:
  423. continue
  424. seen.add(tok.i)
  425. ordered.append(tok)
  426. return ordered
  427. def _add_fixed_phrases(
  428. sentence: SpacySpan,
  429. mapping: Dict[int, int],
  430. spans: List[Span],
  431. summary: Optional[SentenceSummary] = None,
  432. ) -> None:
  433. base = sentence.start_char
  434. text = sentence.text
  435. for pattern, label in FIXED_MULTIWORD_PHRASES:
  436. for match in pattern.finditer(text):
  437. start_char = base + match.start()
  438. end_char = base + match.end()
  439. add_char_based_span(
  440. spans,
  441. start_char,
  442. end_char,
  443. "phrase-fixed",
  444. mapping,
  445. attrs={"data-phrase": label},
  446. )
  447. if summary is not None:
  448. summary.connectors.append(label.lower())
  449. def annotate_sentence(
  450. tokens: List[Token],
  451. sentence: SpacySpan,
  452. mapping: Dict[int, int],
  453. collect_summary: bool = True,
  454. ) -> Tuple[List[Span], Optional[SentenceSummary]]:
  455. spans: List[Span] = []
  456. summary = SentenceSummary(sentence_length=len(sentence)) if collect_summary else None
  457. sent_bounds = char_span_to_token_span(sentence.start_char, sentence.end_char, mapping)
  458. sent_start_tok, sent_end_tok = sent_bounds
  459. def add_subtree(token: SpacyToken, cls: str):
  460. start_char, end_char = subtree_char_span(token)
  461. add_char_based_span(spans, start_char, end_char, cls, mapping)
  462. def add_token(token: SpacyToken, cls: str):
  463. add_char_based_span(spans, token.idx, token.idx + len(token.text), cls, mapping)
  464. for tok in sentence:
  465. if tok.dep_ in SUBJECT_DEPS:
  466. add_subtree(tok, "role-subject")
  467. if summary is not None:
  468. summary.subjects.append(_subtree_text(tok))
  469. for head in _predicate_heads(sentence):
  470. start_char, end_char = _predicate_span_bounds(head)
  471. add_char_based_span(spans, start_char, end_char, "role-predicate", mapping)
  472. predicate_text = sentence.doc.text[start_char:end_char].strip()
  473. if summary is not None:
  474. summary.predicates.append(predicate_text or head.text)
  475. for tok in sentence:
  476. if tok.dep_ in DIRECT_OBJECT_DEPS:
  477. add_subtree(tok, "role-object-do")
  478. if summary is not None:
  479. summary.objects.append(_subtree_text(tok))
  480. break
  481. io_token = next((tok for tok in sentence if tok.dep_ in INDIRECT_OBJECT_DEPS), None)
  482. if io_token is None:
  483. for tok in sentence:
  484. if tok.dep_ == "pobj" and tok.head.dep_ == "prep" and tok.head.lemma_.lower() in {"to", "for"}:
  485. io_token = tok
  486. break
  487. if io_token:
  488. add_subtree(io_token, "role-object-io")
  489. if summary is not None:
  490. summary.objects.append(_subtree_text(io_token))
  491. for tok in sentence:
  492. if tok.dep_ in COMPLEMENT_DEPS:
  493. add_subtree(tok, "role-complement")
  494. if summary is not None:
  495. summary.complements.append(_subtree_text(tok))
  496. break
  497. for tok in sentence:
  498. lowered = tok.text.lower()
  499. if tok.dep_ in {"cc", "mark", "preconj"} or tok.pos_ in {"CCONJ", "SCONJ"}:
  500. add_token(tok, "role-connector")
  501. if summary is not None:
  502. summary.connectors.append(lowered)
  503. if tok.dep_ == "det" or tok.pos_ == "DET":
  504. add_token(tok, "role-determiner")
  505. if tok.dep_ in {"amod", "poss", "compound", "nummod"}:
  506. add_token(tok, "role-modifier")
  507. adverbial_ranges = set()
  508. for tok in sentence:
  509. if tok.dep_ in ADVERBIAL_DEPS:
  510. adverbial_ranges.add(subtree_char_span(tok))
  511. for start_char, end_char in adverbial_ranges:
  512. add_char_based_span(spans, start_char, end_char, "role-adverbial", mapping)
  513. for tok in sentence:
  514. if tok.dep_ == "appos":
  515. add_subtree(tok, "role-apposition")
  516. if sent_start_tok >= 0 and sent_end_tok >= 0:
  517. stack = []
  518. for idx in range(sent_start_tok, sent_end_tok):
  519. token = tokens[idx]
  520. if token.text == "(":
  521. stack.append(idx)
  522. elif token.text == ")" and stack:
  523. add_span(spans, stack.pop(), idx + 1, "role-parenthetical")
  524. comma_token_idxs = [
  525. i
  526. for i in range(sent_start_tok, sent_end_tok)
  527. if tokens[i].kind == "punct" and tokens[i].text == ","
  528. ]
  529. for idx, first_comma in enumerate(comma_token_idxs):
  530. if idx + 1 >= len(comma_token_idxs):
  531. break
  532. second_comma = comma_token_idxs[idx + 1]
  533. start_char = tokens[first_comma].start
  534. end_char = tokens[second_comma].end
  535. span = sentence.doc.char_span(start_char, end_char, alignment_mode="expand")
  536. if span and any(tok.tag_ == "VBG" for tok in span):
  537. add_span(spans, first_comma, second_comma + 1, "role-absolute")
  538. annotate_constituents(
  539. sentence,
  540. spans,
  541. mapping,
  542. sentence.start_char,
  543. sentence.end_char,
  544. summary,
  545. )
  546. _add_fixed_phrases(sentence, mapping, spans, summary)
  547. return spans, summary
  548. def _label_residual_token(token: SpacyToken) -> Optional[str]:
  549. dep_label = RESIDUAL_DEP_LABELS.get(token.dep_)
  550. if dep_label:
  551. return dep_label
  552. return RESIDUAL_POS_LABELS.get(token.pos_)
  553. def _collect_residual_roles(
  554. sentence: SpacySpan,
  555. tokens: List[Token],
  556. spans: List[Span],
  557. sent_bounds: Tuple[int, int],
  558. summary: Optional[SentenceSummary],
  559. mapping: Dict[int, int],
  560. ) -> None:
  561. sent_start, sent_end = sent_bounds
  562. if sent_start < 0 or sent_end < 0 or sent_start >= sent_end:
  563. return
  564. coverage = [False] * (sent_end - sent_start)
  565. for span in spans:
  566. lo = max(span.start_token, sent_start)
  567. hi = min(span.end_token, sent_end)
  568. for idx in range(lo, hi):
  569. coverage[idx - sent_start] = True
  570. doc = sentence.doc
  571. for offset, covered in enumerate(coverage):
  572. if covered:
  573. continue
  574. token = tokens[sent_start + offset]
  575. if token.kind != "word":
  576. continue
  577. span = doc.char_span(token.start, token.end, alignment_mode="expand")
  578. if not span or not span.text.strip():
  579. continue
  580. label = _label_residual_token(span[0])
  581. if summary is not None and label and label not in summary.residual_roles:
  582. summary.residual_roles.append(label)
  583. if label:
  584. add_char_based_span(
  585. spans,
  586. token.start,
  587. token.end,
  588. "role-residual",
  589. mapping,
  590. attrs={"data-role": label},
  591. )
  592. def _classify_sentence_complexity(summary: SentenceSummary) -> Tuple[str, bool]:
  593. clause_count = len(summary.clauses)
  594. connector_count = len(summary.connectors)
  595. word_count = summary.sentence_length
  596. if clause_count >= 2:
  597. return "多重复杂句", True
  598. if clause_count == 1:
  599. return "主从复合句", True
  600. if connector_count >= 2:
  601. return "并列复合句", True
  602. if word_count >= 25:
  603. return "长句", True
  604. return "简单句", False
  605. def _translate_clause_functions(functions: List[str]) -> List[str]:
  606. translated = []
  607. for item in functions:
  608. label = CLAUSE_FUNCTION_LABELS.get(item, item)
  609. if label not in translated:
  610. translated.append(label)
  611. return translated
  612. def build_sentence_note(summary: SentenceSummary) -> Tuple[str, bool]:
  613. note_parts: List[str] = []
  614. clause_label = "无"
  615. if summary.clauses:
  616. counts = Counter(summary.clauses)
  617. clause_label = "、".join(
  618. f"{name}×{count}" if count > 1 else name for name, count in counts.items()
  619. )
  620. functions = _translate_clause_functions(summary.clause_functions)
  621. connectors = list(dict.fromkeys(summary.connectors))
  622. residual = summary.residual_roles
  623. subjects_seq = list(dict.fromkeys(summary.subjects))
  624. predicates_seq = list(dict.fromkeys(summary.predicates))
  625. objects_seq = list(dict.fromkeys(summary.objects))
  626. complements_seq = list(dict.fromkeys(summary.complements))
  627. subjects = "、".join(subjects_seq) if subjects_seq else "未识别"
  628. predicates = "、".join(predicates_seq) if predicates_seq else "未识别"
  629. objects = "、".join(objects_seq) if objects_seq else "无"
  630. complements = "、".join(complements_seq) if complements_seq else "无"
  631. note_parts.append(f"主语:{subjects}")
  632. note_parts.append(f"谓语:{predicates}")
  633. note_parts.append(f"宾语:{objects}")
  634. if complements != "无":
  635. note_parts.append(f"补语:{complements}")
  636. note_parts.append(f"从句:{clause_label}")
  637. if functions:
  638. note_parts.append(f"从句功能:{'、'.join(functions)}")
  639. connector_text = "、".join(connectors) if connectors else "未检测到典型连接词"
  640. note_parts.append(f"连接词:{connector_text}")
  641. if residual:
  642. note_parts.append(f"未高亮:{'、'.join(residual)}")
  643. complexity_label, is_complex = _classify_sentence_complexity(summary)
  644. note_parts.insert(0, f"句型:{complexity_label}")
  645. note_parts.append(f"词数:{summary.sentence_length}")
  646. return ";".join(note_parts), is_complex
  647. def render_with_spans(tokens: List[Token], spans: List[Span]) -> str:
  648. spans = sorted(spans, key=lambda s: (s.start_token, -s.end_token))
  649. out_parts: List[str] = []
  650. active_stack: List[Span] = []
  651. span_queue = list(spans)
  652. current_idx = 0
  653. def open_span(span: Span):
  654. attrs = ""
  655. if span.attrs:
  656. attrs = " " + " ".join(
  657. f"{k}='" + html.escape(v, quote=True) + "'" for k, v in span.attrs.items()
  658. )
  659. out_parts.append(f"<span class='{span.cls}'{attrs}>")
  660. def close_span():
  661. out_parts.append("</span>")
  662. while current_idx < len(tokens):
  663. opening = [sp for sp in span_queue if sp.start_token == current_idx]
  664. for sp in opening:
  665. open_span(sp)
  666. active_stack.append(sp)
  667. span_queue.remove(sp)
  668. token = tokens[current_idx]
  669. out_parts.append(html.escape(token.text))
  670. current_idx += 1
  671. while active_stack and active_stack[-1].end_token == current_idx:
  672. active_stack.pop()
  673. close_span()
  674. while active_stack:
  675. active_stack.pop()
  676. close_span()
  677. return "".join(out_parts)
  678. def _run_pipeline_without_benepar(text: str) -> "spacy.tokens.Doc":
  679. """Run the spaCy pipeline skipping benepar, for robust fallback."""
  680. assert NLP is not None
  681. doc = NLP.make_doc(text)
  682. for name, proc in NLP.pipeline:
  683. if name == "benepar":
  684. continue
  685. doc = proc(doc)
  686. return doc
  687. def highlight_text_with_spacy(
  688. text: str,
  689. paragraph_meta: Optional[List[Dict[str, str]]] = None,
  690. include_helper: bool = False,
  691. ) -> str:
  692. if NLP is None:
  693. raise RuntimeError(f"spaCy pipeline unavailable: {NLP_LOAD_ERROR}")
  694. tokens = tokenize_preserve(text)
  695. if not tokens:
  696. return ""
  697. mapping = build_char_to_token_map(tokens)
  698. # Robust doc creation: if benepar causes any error, skip it and fallback.
  699. try:
  700. doc = NLP(text)
  701. except Exception as exc:
  702. _ensure_benepar_warning(
  703. f"Benepar failed during processing: {exc}. Falling back to dependency-based spans."
  704. )
  705. doc = _run_pipeline_without_benepar(text)
  706. paragraph_ranges = _split_paragraph_ranges(text)
  707. paragraph_counters = [0 for _ in paragraph_ranges]
  708. paragraph_idx = 0
  709. paragraph_spans: List[Span] = []
  710. paragraph_attrs = paragraph_meta if paragraph_meta and len(paragraph_meta) == len(paragraph_ranges) else None
  711. for idx, (start, end) in enumerate(paragraph_ranges):
  712. attrs = None
  713. if paragraph_attrs:
  714. attrs = paragraph_attrs[idx] or None
  715. add_char_based_span(paragraph_spans, start, end, "paragraph-scope", mapping, attrs=attrs)
  716. spans: List[Span] = list(paragraph_spans)
  717. for sent in doc.sents:
  718. while paragraph_idx < len(paragraph_ranges) and paragraph_ranges[paragraph_idx][1] <= sent.start_char:
  719. paragraph_idx += 1
  720. current_idx = min(paragraph_idx, len(paragraph_ranges) - 1)
  721. paragraph_counters[current_idx] += 1
  722. sentence_label = _circled_number(paragraph_counters[current_idx])
  723. sentence_spans, summary = annotate_sentence(tokens, sent, mapping, collect_summary=include_helper)
  724. sent_bounds = char_span_to_token_span(sent.start_char, sent.end_char, mapping)
  725. sent_start, sent_end = sent_bounds
  726. if sent_start >= 0 and sent_end >= 0:
  727. _collect_residual_roles(sent, tokens, sentence_spans, sent_bounds, summary, mapping)
  728. helper_note = ""
  729. is_complex = False
  730. if include_helper and summary is not None:
  731. helper_note, is_complex = build_sentence_note(summary)
  732. attrs = {
  733. "data-sid": sentence_label,
  734. }
  735. if include_helper:
  736. attrs["data-complex"] = "1" if is_complex else "0"
  737. attrs["data-note"] = helper_note
  738. sentence_spans.append(Span(start_token=sent_start, end_token=sent_end, cls="sentence-scope", attrs=attrs))
  739. spans.extend(sentence_spans)
  740. return render_with_spans(tokens, spans)
  741. def _build_analysis_container(fragment: str, include_helper: bool) -> str:
  742. helper_state = "on" if include_helper else "off"
  743. return f"<div class='analysis' data-helper='{helper_state}'>{fragment}</div>"
  744. def _build_highlighted_html(fragment: str, include_helper: bool) -> str:
  745. return f"{STYLE_BLOCK}{_build_analysis_container(fragment, include_helper)}"
  746. def _perform_analysis(text: str, include_helper: bool) -> AnalyzeResponse:
  747. sanitized_fragment = highlight_text_with_spacy(text, include_helper=include_helper)
  748. highlighted_html = _build_highlighted_html(sanitized_fragment, include_helper)
  749. return AnalyzeResponse(highlighted_html=highlighted_html)
  750. app = FastAPI(title="Grammar Highlight API (spaCy + benepar)")
  751. app.add_middleware(
  752. CORSMiddleware,
  753. allow_origins=["*"],
  754. allow_credentials=True,
  755. allow_methods=["*"],
  756. allow_headers=["*"],
  757. )
  758. @app.post("/analyze", response_model=AnalyzeResponse)
  759. async def analyze(req: AnalyzeRequest):
  760. text = req.text
  761. if text is None or not text.strip():
  762. raise HTTPException(status_code=400, detail="Text is required")
  763. try:
  764. return _perform_analysis(text, include_helper=False)
  765. except RuntimeError as exc:
  766. raise HTTPException(status_code=500, detail=str(exc)) from exc
  767. except Exception as exc: # pragma: no cover - defensive
  768. raise HTTPException(status_code=500, detail=f"Analysis failed: {exc}") from exc
  769. @app.post("/analyze/detail", response_model=AnalyzeResponse)
  770. async def analyze_with_helper(req: AnalyzeRequest):
  771. text = req.text
  772. if text is None or not text.strip():
  773. raise HTTPException(status_code=400, detail="Text is required")
  774. try:
  775. return _perform_analysis(text, include_helper=True)
  776. except RuntimeError as exc:
  777. raise HTTPException(status_code=500, detail=str(exc)) from exc
  778. except Exception as exc: # pragma: no cover - defensive
  779. raise HTTPException(status_code=500, detail=f"Analysis failed: {exc}") from exc
  780. @app.get("/health")
  781. async def health():
  782. status = "ok" if NLP is not None else "failed"
  783. detail = None if NLP is not None else str(NLP_LOAD_ERROR)
  784. payload = {"status": status}
  785. if detail:
  786. payload["detail"] = detail
  787. if BENE_PAR_WARNING:
  788. payload["warning"] = BENE_PAR_WARNING
  789. payload["benepar_attached"] = HAS_BENEPAR
  790. return payload
  791. @app.get("/proxy", response_class=HTMLResponse)
  792. async def proxy(url: Optional[str] = None, show_images: bool = False):
  793. if not url:
  794. return HTMLResponse(_render_proxy_page(show_images=show_images))
  795. try:
  796. normalized_url, title, page_text, images, code_blocks, paragraph_meta = await _fetch_remote_plaintext(url)
  797. highlighted_fragment = highlight_text_with_spacy(page_text, paragraph_meta=paragraph_meta or None)
  798. if code_blocks:
  799. highlighted_fragment = _inject_proxy_codeblocks(highlighted_fragment, code_blocks)
  800. image_notice = None
  801. if images:
  802. if show_images:
  803. highlighted_fragment = _inject_proxy_images(highlighted_fragment, images)
  804. else:
  805. highlighted_fragment = _strip_proxy_image_markers(highlighted_fragment)
  806. image_notice = (
  807. f"检测到 {len(images)} 张正文图片,为提速默认隐藏。勾选“显示图片”后重新抓取即可加载原图。"
  808. )
  809. html_body = _render_proxy_page(
  810. url_value=normalized_url,
  811. message="分析完成,结果如下。",
  812. highlight_fragment=highlighted_fragment,
  813. source_url=normalized_url,
  814. source_title=title,
  815. show_images=show_images,
  816. image_notice=image_notice,
  817. source_plaintext=page_text,
  818. )
  819. return HTMLResponse(html_body)
  820. except ValueError as exc:
  821. body = _render_proxy_page(url_value=url or "", message=str(exc), is_error=True, show_images=show_images)
  822. return HTMLResponse(body, status_code=400)
  823. except httpx.HTTPError as exc:
  824. # Provide a clearer message for common HTTP errors from the remote site.
  825. msg = None
  826. if isinstance(exc, httpx.HTTPStatusError) and exc.response is not None:
  827. status = exc.response.status_code
  828. if status == 403:
  829. msg = (
  830. "抓取页面失败:目标站点返回 403 Forbidden(禁止访问)。"
  831. "该网站很可能禁止自动抓取或代理访问,目前无法通过本工具获取正文,"
  832. "可以尝试在浏览器中打开并手动复制需要的内容。"
  833. )
  834. else:
  835. msg = f"抓取页面失败:目标站点返回 HTTP {status}。"
  836. if msg is None:
  837. msg = f"抓取页面失败:{exc}"
  838. body = _render_proxy_page(
  839. url_value=url or "",
  840. message=msg,
  841. is_error=True,
  842. show_images=show_images,
  843. )
  844. return HTMLResponse(body, status_code=502)
  845. except Exception as exc:
  846. body = _render_proxy_page(
  847. url_value=url or "",
  848. message=f"代理分析失败:{exc}",
  849. is_error=True,
  850. show_images=show_images,
  851. )
  852. return HTMLResponse(body, status_code=500)
  853. @app.get("/", response_class=HTMLResponse)
  854. async def ui():
  855. return """<!DOCTYPE html>
  856. <html lang=\"zh-CN\">
  857. <head>
  858. <meta charset=\"UTF-8\" />
  859. <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />
  860. <title>Grammar Highlighter</title>
  861. <style>
  862. body { font-family: system-ui, -apple-system, sans-serif; margin: 2rem; line-height: 1.6; }
  863. textarea { width: 100%; min-height: 140px; font-size: 1rem; padding: 0.75rem; border: 1px solid #d0d7de; border-radius: 0.5rem; }
  864. button { margin-top: 0.75rem; padding: 0.6rem 1.4rem; font-size: 1rem; cursor: pointer; border: none; border-radius: 999px; background: #1f7a8c; color: #fff; }
  865. button + button { margin-left: 0.5rem; background: #6b7280; }
  866. button:disabled { opacity: 0.6; cursor: wait; }
  867. #result { margin-top: 1.5rem; border-top: 1px solid #e5e7eb; padding-top: 1rem; min-height: 2rem; }
  868. #status { margin-left: 0.75rem; color: #3b82f6; }
  869. .err { color: #b00020; }
  870. .muted { color: #6b7280; font-size: 0.9rem; }
  871. .tts-controls { margin-top: 0.75rem; display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; }
  872. .tts-controls button { margin-top: 0; background: #f97316; }
  873. .tts-status { font-size: 0.95rem; color: #475569; }
  874. .sentence-scope.anchor-highlight { outline: 2px dashed #f97316; outline-offset: 2px; }
  875. </style>
  876. </head>
  877. <body>
  878. <h1>Grammar Highlighter (spaCy + benepar)</h1>
  879. <textarea id=\"text\" placeholder=\"Type the English text you want to analyze...\"></textarea>
  880. <div>
  881. <button type=\"button\" id=\"submit\">Analyze</button>
  882. <button type=\"button\" id=\"clear\">清空输入</button>
  883. <span id=\"status\"></span>
  884. </div>
  885. <div class=\"tts-controls\">
  886. <button type=\"button\" id=\"tts\">朗读高亮文本</button>
  887. <button type=\"button\" id=\"tts-selection\">朗读选中文本</button>
  888. <button type=\"button\" id=\"tts-anchor\" disabled>从点击处朗读</button>
  889. <button type=\"button\" id=\"tts-toggle\" disabled>暂停播放</button>
  890. <span class=\"tts-status\" id=\"tts-status\"></span>
  891. </div>
  892. <div id=\"result\"></div>
  893. <script>
  894. const btn = document.getElementById('submit');
  895. const btnClear = document.getElementById('clear');
  896. const textarea = document.getElementById('text');
  897. const statusEl = document.getElementById('status');
  898. const ttsBtn = document.getElementById('tts');
  899. const ttsSelectionBtn = document.getElementById('tts-selection');
  900. const ttsAnchorBtn = document.getElementById('tts-anchor');
  901. const ttsToggleBtn = document.getElementById('tts-toggle');
  902. const ttsStatus = document.getElementById('tts-status');
  903. const result = document.getElementById('result');
  904. const TTS_ENDPOINT = 'http://141.140.15.30:8028/generate';
  905. let currentAudio = null;
  906. let queuedAudios = [];
  907. let streamingFinished = false;
  908. let lastAnalyzedText = '';
  909. let anchorSentenceIndex = 0;
  910. let isPaused = false;
  911. let hasHighlightContent = false;
  912. function resetUI() {
  913. result.innerHTML = '';
  914. statusEl.textContent = '';
  915. statusEl.classList.remove('err');
  916. ttsStatus.textContent = '';
  917. hasHighlightContent = false;
  918. if (ttsAnchorBtn) {
  919. ttsAnchorBtn.disabled = true;
  920. }
  921. resetAnchorState();
  922. setTtsButtonsDisabled(false);
  923. resetAudioPlayback();
  924. }
  925. function getSentenceNodes() {
  926. const analysis = result.querySelector('.analysis');
  927. return analysis ? Array.from(analysis.querySelectorAll('.sentence-scope')) : [];
  928. }
  929. function clearAnchorHighlight() {
  930. const highlighted = result.querySelectorAll('.sentence-scope.anchor-highlight');
  931. highlighted.forEach(el => el.classList.remove('anchor-highlight'));
  932. }
  933. function resetAnchorState() {
  934. anchorSentenceIndex = 0;
  935. clearAnchorHighlight();
  936. }
  937. function setAnchorFromSentence(sentenceEl) {
  938. const sentences = getSentenceNodes();
  939. const idx = sentences.indexOf(sentenceEl);
  940. if (idx === -1) return;
  941. anchorSentenceIndex = idx;
  942. clearAnchorHighlight();
  943. sentenceEl.classList.add('anchor-highlight');
  944. const sid = sentenceEl.getAttribute('data-sid') || (idx + 1);
  945. ttsStatus.textContent = '已选择第 ' + sid + ' 句作为朗读起点';
  946. }
  947. btn.addEventListener('click', async () => {
  948. resetUI();
  949. const value = textarea.value.trim();
  950. if (!value) {
  951. statusEl.textContent = '请输入要分析的英文文本。';
  952. statusEl.classList.add('err');
  953. return;
  954. }
  955. btn.disabled = true;
  956. statusEl.textContent = 'Analyzing ...';
  957. try {
  958. const response = await fetch('/analyze', {
  959. method: 'POST',
  960. headers: { 'Content-Type': 'application/json' },
  961. body: JSON.stringify({ text: value })
  962. });
  963. if (!response.ok) {
  964. const error = await response.json().catch(() => ({ detail: 'Request failed' }));
  965. throw new Error(error.detail || 'Request failed');
  966. }
  967. const data = await response.json();
  968. result.innerHTML = data.highlighted_html || '';
  969. lastAnalyzedText = value;
  970. resetAnchorState();
  971. hasHighlightContent = true;
  972. if (ttsAnchorBtn) {
  973. ttsAnchorBtn.disabled = false;
  974. }
  975. statusEl.textContent = '';
  976. } catch (err) {
  977. statusEl.textContent = '错误:' + (err.message || 'Unknown error');
  978. statusEl.classList.add('err');
  979. } finally {
  980. btn.disabled = false;
  981. }
  982. });
  983. btnClear.addEventListener('click', () => {
  984. textarea.value = '';
  985. lastAnalyzedText = '';
  986. resetUI();
  987. textarea.focus();
  988. });
  989. result.addEventListener('click', event => {
  990. if (!hasHighlightContent) {
  991. return;
  992. }
  993. const target = event.target;
  994. const isTextNode = typeof Node !== 'undefined' && target && target.nodeType === Node.TEXT_NODE;
  995. const base = isTextNode ? target.parentElement : target;
  996. if (!base || typeof base.closest !== 'function') {
  997. return;
  998. }
  999. const sentenceEl = base.closest('.sentence-scope');
  1000. if (sentenceEl) {
  1001. setAnchorFromSentence(sentenceEl);
  1002. }
  1003. });
  1004. function extractHighlightedText() {
  1005. const highlightRoot = result.querySelector('.analysis');
  1006. return highlightRoot ? highlightRoot.textContent.trim() : '';
  1007. }
  1008. function getFullTextForTts() {
  1009. return lastAnalyzedText || extractHighlightedText();
  1010. }
  1011. function extractAnchorText() {
  1012. const sentences = getSentenceNodes();
  1013. if (!sentences.length) return '';
  1014. const start = Math.min(anchorSentenceIndex, sentences.length - 1);
  1015. const parts = [];
  1016. for (let i = start; i < sentences.length; i++) {
  1017. const text = sentences[i].textContent.trim();
  1018. if (text) {
  1019. parts.push(text);
  1020. }
  1021. }
  1022. return parts.join(' ');
  1023. }
  1024. function setTtsButtonsDisabled(disabled) {
  1025. if (ttsBtn) {
  1026. ttsBtn.disabled = disabled;
  1027. }
  1028. if (ttsSelectionBtn) {
  1029. ttsSelectionBtn.disabled = disabled;
  1030. }
  1031. if (ttsAnchorBtn) {
  1032. ttsAnchorBtn.disabled = disabled || !hasHighlightContent;
  1033. }
  1034. }
  1035. function resetAudioPlayback() {
  1036. queuedAudios = [];
  1037. streamingFinished = false;
  1038. if (currentAudio) {
  1039. currentAudio.pause();
  1040. currentAudio = null;
  1041. }
  1042. resetPauseResumeState();
  1043. }
  1044. function setPauseResumeEnabled(enabled) {
  1045. if (ttsToggleBtn) {
  1046. ttsToggleBtn.disabled = !enabled;
  1047. }
  1048. }
  1049. function resetPauseResumeState() {
  1050. isPaused = false;
  1051. if (ttsToggleBtn) {
  1052. ttsToggleBtn.textContent = '暂停播放';
  1053. }
  1054. setPauseResumeEnabled(false);
  1055. }
  1056. function markStreamingFinished() {
  1057. streamingFinished = true;
  1058. if (!currentAudio && !queuedAudios.length && !isPaused) {
  1059. ttsStatus.textContent = '播放完成';
  1060. setPauseResumeEnabled(false);
  1061. }
  1062. }
  1063. function playNextAudioChunk() {
  1064. if (!queuedAudios.length) {
  1065. currentAudio = null;
  1066. if (streamingFinished && !isPaused) {
  1067. ttsStatus.textContent = '播放完成';
  1068. setPauseResumeEnabled(false);
  1069. } else if (!streamingFinished) {
  1070. ttsStatus.textContent = '等待更多语音...';
  1071. }
  1072. return;
  1073. }
  1074. const chunk = queuedAudios.shift();
  1075. ttsStatus.textContent = '播放中...';
  1076. currentAudio = new Audio('data:audio/wav;base64,' + chunk);
  1077. currentAudio.onended = () => {
  1078. if (!isPaused) {
  1079. playNextAudioChunk();
  1080. }
  1081. };
  1082. currentAudio.onerror = () => {
  1083. ttsStatus.textContent = '播放失败';
  1084. currentAudio = null;
  1085. setPauseResumeEnabled(false);
  1086. };
  1087. currentAudio.play().catch(err => {
  1088. ttsStatus.textContent = '自动播放被阻止:' + err.message;
  1089. currentAudio = null;
  1090. queuedAudios.unshift(chunk);
  1091. setPauseResumeEnabled(true);
  1092. });
  1093. }
  1094. function enqueueAudioChunk(chunk) {
  1095. queuedAudios.push(chunk);
  1096. setPauseResumeEnabled(true);
  1097. if (!currentAudio) {
  1098. playNextAudioChunk();
  1099. }
  1100. }
  1101. function handlePauseResumeToggle() {
  1102. if (!ttsToggleBtn) {
  1103. return;
  1104. }
  1105. if (!currentAudio && !queuedAudios.length) {
  1106. ttsStatus.textContent = '暂无可暂停的语音';
  1107. return;
  1108. }
  1109. if (!currentAudio) {
  1110. playNextAudioChunk();
  1111. ttsToggleBtn.textContent = '暂停播放';
  1112. return;
  1113. }
  1114. if (!isPaused) {
  1115. currentAudio.pause();
  1116. isPaused = true;
  1117. ttsToggleBtn.textContent = '继续播放';
  1118. ttsStatus.textContent = '已暂停';
  1119. } else {
  1120. currentAudio.play().then(() => {
  1121. isPaused = false;
  1122. ttsToggleBtn.textContent = '暂停播放';
  1123. ttsStatus.textContent = '播放中...';
  1124. }).catch(err => {
  1125. ttsStatus.textContent = '无法继续播放:' + err.message;
  1126. });
  1127. }
  1128. }
  1129. function parseTtsLine(line) {
  1130. try {
  1131. const parsed = JSON.parse(line);
  1132. if (parsed && parsed.audio) {
  1133. enqueueAudioChunk(parsed.audio);
  1134. return true;
  1135. }
  1136. } catch (err) {
  1137. console.warn('无法解析TTS响应行', err);
  1138. }
  1139. return false;
  1140. }
  1141. async function consumeTtsResponse(response) {
  1142. let chunkCount = 0;
  1143. const handleLine = rawLine => {
  1144. const trimmed = rawLine.replace(/\\r/g, '').trim();
  1145. if (!trimmed) return;
  1146. if (parseTtsLine(trimmed)) {
  1147. chunkCount += 1;
  1148. }
  1149. };
  1150. if (response.body && response.body.getReader) {
  1151. const reader = response.body.getReader();
  1152. const decoder = new TextDecoder();
  1153. let buffer = '';
  1154. while (true) {
  1155. const { value, done } = await reader.read();
  1156. if (done) break;
  1157. buffer += decoder.decode(value, { stream: true });
  1158. let newlineIndex;
  1159. while ((newlineIndex = buffer.indexOf('\\n')) >= 0) {
  1160. const line = buffer.slice(0, newlineIndex);
  1161. buffer = buffer.slice(newlineIndex + 1);
  1162. handleLine(line);
  1163. }
  1164. }
  1165. buffer += decoder.decode();
  1166. if (buffer) {
  1167. handleLine(buffer);
  1168. }
  1169. } else {
  1170. const payload = await response.text();
  1171. payload.split('\\n').forEach(handleLine);
  1172. }
  1173. return chunkCount;
  1174. }
  1175. function getSelectedPageText() {
  1176. const selection = window.getSelection ? window.getSelection() : null;
  1177. return selection ? selection.toString().trim() : '';
  1178. }
  1179. async function streamTtsRequest(text) {
  1180. const response = await fetch(TTS_ENDPOINT, {
  1181. method: 'POST',
  1182. headers: { 'Content-Type': 'application/json' },
  1183. body: JSON.stringify({ text })
  1184. });
  1185. if (!response.ok) {
  1186. throw new Error('接口响应错误');
  1187. }
  1188. const chunkCount = await consumeTtsResponse(response);
  1189. if (!chunkCount) {
  1190. throw new Error('接口未返回音频数据');
  1191. }
  1192. markStreamingFinished();
  1193. }
  1194. function createTtsRequest(textResolver, emptyMessage) {
  1195. return async () => {
  1196. const text = textResolver();
  1197. if (!text) {
  1198. ttsStatus.textContent = emptyMessage;
  1199. return;
  1200. }
  1201. setTtsButtonsDisabled(true);
  1202. ttsStatus.textContent = '请求语音...';
  1203. resetAudioPlayback();
  1204. try {
  1205. await streamTtsRequest(text);
  1206. } catch (err) {
  1207. ttsStatus.textContent = 'TTS 出错:' + (err && err.message ? err.message : err);
  1208. resetAudioPlayback();
  1209. } finally {
  1210. setTtsButtonsDisabled(false);
  1211. }
  1212. };
  1213. }
  1214. if (ttsBtn) {
  1215. ttsBtn.addEventListener('click', createTtsRequest(getFullTextForTts, '请先生成高亮结果'));
  1216. }
  1217. if (ttsSelectionBtn) {
  1218. ttsSelectionBtn.addEventListener('click', createTtsRequest(getSelectedPageText, '请先选择要朗读的文本'));
  1219. }
  1220. if (ttsAnchorBtn) {
  1221. ttsAnchorBtn.addEventListener('click', createTtsRequest(extractAnchorText, '请先在结果中点击句子作为朗读起点'));
  1222. }
  1223. if (ttsToggleBtn) {
  1224. ttsToggleBtn.addEventListener('click', handlePauseResumeToggle);
  1225. }
  1226. </script>
  1227. </body>
  1228. </html>"""
  1229. PROXY_PAGE_TEMPLATE = Template(
  1230. """<!DOCTYPE html>
  1231. <html lang=\"zh-CN\">
  1232. <head>
  1233. <meta charset=\"UTF-8\" />
  1234. <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />
  1235. <title>Grammar Proxy Highlighter</title>
  1236. <style>
  1237. body { font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif; margin: 0 auto; max-width: 860px; padding: 1.5rem; line-height: 1.65; }
  1238. h1 { font-size: 1.45rem; margin-bottom: 1rem; }
  1239. form { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; }
  1240. input[type=\"url\"] { flex: 1 1 260px; padding: 0.65rem; font-size: 1rem; border-radius: 0.5rem; border: 1px solid #d0d7de; }
  1241. button { padding: 0.65rem 1.4rem; border: none; border-radius: 999px; background: #2563eb; color: #fff; font-size: 1rem; cursor: pointer; }
  1242. .show-images-toggle { display: inline-flex; align-items: center; gap: 0.35rem; font-size: 0.9rem; color: #475569; }
  1243. .show-images-toggle input { width: auto; }
  1244. .tts-controls { margin-top: 0.5rem; display: flex; align-items: center; flex-wrap: wrap; gap: 0.75rem; }
  1245. .tts-controls button { background: #f97316; }
  1246. .tts-status { font-size: 0.95rem; color: #475569; }
  1247. .sentence-scope.anchor-highlight { outline: 2px dashed #f97316; outline-offset: 2px; }
  1248. .status { margin-top: 0.25rem; font-size: 0.95rem; }
  1249. .status.err { color: #b00020; }
  1250. .status.ok { color: #059669; }
  1251. section.result { margin-top: 1.4rem; padding-top: 1rem; border-top: 1px solid #e5e7eb; }
  1252. section.result .source { font-size: 0.95rem; margin-bottom: 0.5rem; color: #475569; word-break: break-word; }
  1253. section.result .source a { color: inherit; text-decoration: underline; }
  1254. section.result img { display:block; margin:0.75rem auto; max-width:100%; height:auto; max-width:min(100%,800px); }
  1255. .image-hint { font-size:0.9rem; color:#6b7280; margin:0.5rem 0 0; }
  1256. .clear-floating { position: fixed; left: 0; right: 0; bottom: 0; padding: 0.55rem 1.5rem; border-radius: 0; border-top: 1px solid #e5e7eb; background: rgba(249,250,251,0.96); display: flex; justify-content: center; z-index: 40; }
  1257. .clear-floating button { padding: 0.55rem 1.8rem; border-radius: 999px; background: #6b7280; color: #fff; font-size: 0.95rem; }
  1258. .clear-floating button:hover { filter: brightness(1.05); }
  1259. @media (prefers-reduced-motion: reduce) { .clear-floating { scroll-behavior: auto; } }
  1260. @media (max-width: 640px) { body { padding-bottom: 3.2rem; } }
  1261. </style>
  1262. $style_block
  1263. </head>
  1264. <body>
  1265. <h1>网页代理高亮</h1>
  1266. <form method=\"get\" action=\"/proxy\" class=\"url-form\">
  1267. <input type=\"url\" name=\"url\" value=\"$url_value\" placeholder=\"https://example.com/article\" required />
  1268. <button type=\"submit\">抓取并高亮</button>
  1269. <label class=\"show-images-toggle\">
  1270. <input type=\"checkbox\" name=\"show_images\" value=\"1\" $show_images_checked />
  1271. <span>显示图片(默认关闭以提升速度)</span>
  1272. </label>
  1273. </form>
  1274. $status_block
  1275. <div class=\"tts-controls\">
  1276. <button type=\"button\" id=\"proxy-tts-btn\" disabled>朗读高亮文本</button>
  1277. <button type=\"button\" id=\"proxy-tts-selection\">朗读选中文本</button>
  1278. <button type=\"button\" id=\"proxy-tts-anchor\" disabled>从点击处朗读</button>
  1279. <button type=\"button\" id=\"proxy-tts-toggle\" disabled>暂停播放</button>
  1280. <span class=\"tts-status\" id=\"proxy-tts-status\"></span>
  1281. </div>
  1282. $result_block
  1283. $source_text_script
  1284. <div class=\"clear-floating\">
  1285. <button type=\"button\" id=\"proxy-reset\">清空并重置</button>
  1286. </div>
  1287. <script>
  1288. (function() {
  1289. var resetBtn = document.getElementById('proxy-reset');
  1290. if (resetBtn) {
  1291. resetBtn.addEventListener('click', function() {
  1292. window.location.href = '/proxy';
  1293. });
  1294. }
  1295. var ttsBtn = document.getElementById('proxy-tts-btn');
  1296. var ttsSelectionBtn = document.getElementById('proxy-tts-selection');
  1297. var ttsAnchorBtn = document.getElementById('proxy-tts-anchor');
  1298. var ttsToggleBtn = document.getElementById('proxy-tts-toggle');
  1299. var ttsStatus = document.getElementById('proxy-tts-status');
  1300. var analysisRoot = document.querySelector('section.result .analysis');
  1301. var proxySourceText = window.__proxySourceText || '';
  1302. var TTS_ENDPOINT = 'http://141.140.15.30:8028/generate';
  1303. var currentAudio = null;
  1304. var queuedAudios = [];
  1305. var streamingFinished = false;
  1306. var anchorSentenceIndex = 0;
  1307. var isPaused = false;
  1308. if (analysisRoot && ttsBtn) {
  1309. ttsBtn.disabled = false;
  1310. }
  1311. if (analysisRoot && ttsAnchorBtn) {
  1312. ttsAnchorBtn.disabled = false;
  1313. }
  1314. function extractProxyText() {
  1315. var container = document.querySelector('section.result .analysis');
  1316. return container ? container.textContent.trim() : '';
  1317. }
  1318. function getSentenceNodes() {
  1319. var container = document.querySelector('section.result .analysis');
  1320. return container ? Array.from(container.querySelectorAll('.sentence-scope')) : [];
  1321. }
  1322. function clearAnchorHighlight() {
  1323. var highlighted = document.querySelectorAll('section.result .sentence-scope.anchor-highlight');
  1324. highlighted.forEach(function(el) {
  1325. el.classList.remove('anchor-highlight');
  1326. });
  1327. }
  1328. function resetAnchorState() {
  1329. anchorSentenceIndex = 0;
  1330. clearAnchorHighlight();
  1331. }
  1332. function setAnchorFromSentence(sentenceEl) {
  1333. var sentences = getSentenceNodes();
  1334. var idx = sentences.indexOf(sentenceEl);
  1335. if (idx === -1) return;
  1336. anchorSentenceIndex = idx;
  1337. clearAnchorHighlight();
  1338. sentenceEl.classList.add('anchor-highlight');
  1339. var sid = sentenceEl.getAttribute('data-sid') || (idx + 1);
  1340. ttsStatus.textContent = '已选择第 ' + sid + ' 句作为朗读起点';
  1341. }
  1342. resetAnchorState();
  1343. var resultSection = document.querySelector('section.result');
  1344. if (resultSection) {
  1345. resultSection.addEventListener('click', function(evt) {
  1346. var target = evt.target;
  1347. var isTextNode = typeof Node !== 'undefined' && target && target.nodeType === Node.TEXT_NODE;
  1348. var base = isTextNode ? target.parentElement : target;
  1349. if (!base || typeof base.closest !== 'function') {
  1350. return;
  1351. }
  1352. var sentenceEl = base.closest('.sentence-scope');
  1353. if (sentenceEl) {
  1354. setAnchorFromSentence(sentenceEl);
  1355. }
  1356. });
  1357. }
  1358. function getFullTextForTts() {
  1359. var text = proxySourceText || extractProxyText();
  1360. return text.trim();
  1361. }
  1362. function extractAnchorText() {
  1363. var sentences = getSentenceNodes();
  1364. if (!sentences.length) return '';
  1365. var start = Math.min(anchorSentenceIndex, sentences.length - 1);
  1366. var parts = [];
  1367. for (var i = start; i < sentences.length; i++) {
  1368. var text = sentences[i].textContent.trim();
  1369. if (text) {
  1370. parts.push(text);
  1371. }
  1372. }
  1373. return parts.join(' ');
  1374. }
  1375. function setTtsButtonsDisabled(disabled) {
  1376. if (ttsBtn) {
  1377. ttsBtn.disabled = disabled;
  1378. }
  1379. if (ttsSelectionBtn) {
  1380. ttsSelectionBtn.disabled = disabled;
  1381. }
  1382. if (ttsAnchorBtn) {
  1383. ttsAnchorBtn.disabled = disabled || !analysisRoot;
  1384. }
  1385. }
  1386. function resetAudioPlayback() {
  1387. queuedAudios = [];
  1388. streamingFinished = false;
  1389. if (currentAudio) {
  1390. currentAudio.pause();
  1391. currentAudio = null;
  1392. }
  1393. resetPauseResumeState();
  1394. }
  1395. function setPauseResumeEnabled(enabled) {
  1396. if (ttsToggleBtn) {
  1397. ttsToggleBtn.disabled = !enabled;
  1398. }
  1399. }
  1400. function resetPauseResumeState() {
  1401. isPaused = false;
  1402. if (ttsToggleBtn) {
  1403. ttsToggleBtn.textContent = '暂停播放';
  1404. }
  1405. setPauseResumeEnabled(false);
  1406. }
  1407. function markStreamingFinished() {
  1408. streamingFinished = true;
  1409. if (!currentAudio && !queuedAudios.length && !isPaused) {
  1410. ttsStatus.textContent = '播放完成';
  1411. setPauseResumeEnabled(false);
  1412. }
  1413. }
  1414. function playNextAudioChunk() {
  1415. if (!queuedAudios.length) {
  1416. currentAudio = null;
  1417. if (streamingFinished && !isPaused) {
  1418. ttsStatus.textContent = '播放完成';
  1419. setPauseResumeEnabled(false);
  1420. } else if (!streamingFinished) {
  1421. ttsStatus.textContent = '等待更多语音...';
  1422. }
  1423. return;
  1424. }
  1425. var chunk = queuedAudios.shift();
  1426. ttsStatus.textContent = '播放中...';
  1427. currentAudio = new Audio('data:audio/wav;base64,' + chunk);
  1428. currentAudio.onended = function() {
  1429. if (!isPaused) {
  1430. playNextAudioChunk();
  1431. }
  1432. };
  1433. currentAudio.onerror = function() {
  1434. ttsStatus.textContent = '播放失败';
  1435. currentAudio = null;
  1436. setPauseResumeEnabled(false);
  1437. };
  1438. currentAudio.play().catch(function(err) {
  1439. ttsStatus.textContent = '自动播放被阻止:' + err.message;
  1440. currentAudio = null;
  1441. queuedAudios.unshift(chunk);
  1442. setPauseResumeEnabled(true);
  1443. });
  1444. }
  1445. function enqueueAudioChunk(chunk) {
  1446. queuedAudios.push(chunk);
  1447. setPauseResumeEnabled(true);
  1448. if (!currentAudio) {
  1449. playNextAudioChunk();
  1450. }
  1451. }
  1452. function handlePauseResumeToggle() {
  1453. if (!ttsToggleBtn) {
  1454. return;
  1455. }
  1456. if (!currentAudio && !queuedAudios.length) {
  1457. ttsStatus.textContent = '暂无可暂停的语音';
  1458. return;
  1459. }
  1460. if (!currentAudio) {
  1461. playNextAudioChunk();
  1462. ttsToggleBtn.textContent = '暂停播放';
  1463. return;
  1464. }
  1465. if (!isPaused) {
  1466. currentAudio.pause();
  1467. isPaused = true;
  1468. ttsToggleBtn.textContent = '继续播放';
  1469. ttsStatus.textContent = '已暂停';
  1470. } else {
  1471. currentAudio.play().then(function() {
  1472. isPaused = false;
  1473. ttsToggleBtn.textContent = '暂停播放';
  1474. ttsStatus.textContent = '播放中...';
  1475. }).catch(function(err) {
  1476. ttsStatus.textContent = '无法继续播放:' + err.message;
  1477. });
  1478. }
  1479. }
  1480. function parseTtsLine(line) {
  1481. try {
  1482. var parsed = JSON.parse(line);
  1483. if (parsed && parsed.audio) {
  1484. enqueueAudioChunk(parsed.audio);
  1485. return true;
  1486. }
  1487. } catch (err) {
  1488. console.warn('无法解析TTS响应行', err);
  1489. }
  1490. return false;
  1491. }
  1492. async function consumeTtsResponse(response) {
  1493. var chunkCount = 0;
  1494. var handleLine = function(rawLine) {
  1495. var trimmed = rawLine.replace(/\\r/g, '').trim();
  1496. if (!trimmed) return;
  1497. if (parseTtsLine(trimmed)) {
  1498. chunkCount += 1;
  1499. }
  1500. };
  1501. if (response.body && response.body.getReader) {
  1502. var reader = response.body.getReader();
  1503. var decoder = new TextDecoder();
  1504. var buffer = '';
  1505. while (true) {
  1506. var readResult = await reader.read();
  1507. if (readResult.done) {
  1508. break;
  1509. }
  1510. buffer += decoder.decode(readResult.value, { stream: true });
  1511. var newlineIndex;
  1512. while ((newlineIndex = buffer.indexOf('\\n')) >= 0) {
  1513. var line = buffer.slice(0, newlineIndex);
  1514. buffer = buffer.slice(newlineIndex + 1);
  1515. handleLine(line);
  1516. }
  1517. }
  1518. buffer += decoder.decode();
  1519. if (buffer) {
  1520. handleLine(buffer);
  1521. }
  1522. } else {
  1523. var payload = await response.text();
  1524. payload.split('\\n').forEach(handleLine);
  1525. }
  1526. return chunkCount;
  1527. }
  1528. function getSelectedPageText() {
  1529. var selection = window.getSelection ? window.getSelection() : null;
  1530. return selection ? selection.toString().trim() : '';
  1531. }
  1532. async function streamTtsRequest(text) {
  1533. var response = await fetch(TTS_ENDPOINT, {
  1534. method: 'POST',
  1535. headers: { 'Content-Type': 'application/json' },
  1536. body: JSON.stringify({ text: text })
  1537. });
  1538. if (!response.ok) {
  1539. throw new Error('接口响应错误');
  1540. }
  1541. var chunkCount = await consumeTtsResponse(response);
  1542. if (!chunkCount) {
  1543. throw new Error('接口未返回音频数据');
  1544. }
  1545. markStreamingFinished();
  1546. }
  1547. function createTtsRequest(textResolver, emptyMessage) {
  1548. return async function() {
  1549. var text = textResolver();
  1550. if (!text) {
  1551. ttsStatus.textContent = emptyMessage;
  1552. return;
  1553. }
  1554. setTtsButtonsDisabled(true);
  1555. ttsStatus.textContent = '请求语音...';
  1556. resetAudioPlayback();
  1557. try {
  1558. await streamTtsRequest(text);
  1559. } catch (err) {
  1560. ttsStatus.textContent = 'TTS 出错:' + (err && err.message ? err.message : err);
  1561. resetAudioPlayback();
  1562. } finally {
  1563. setTtsButtonsDisabled(false);
  1564. }
  1565. };
  1566. }
  1567. if (ttsBtn) {
  1568. ttsBtn.addEventListener('click', createTtsRequest(getFullTextForTts, '请先抓取文章内容再朗读'));
  1569. }
  1570. if (ttsSelectionBtn) {
  1571. ttsSelectionBtn.addEventListener('click', createTtsRequest(getSelectedPageText, '请先选择要朗读的文本'));
  1572. }
  1573. if (ttsAnchorBtn) {
  1574. ttsAnchorBtn.addEventListener('click', createTtsRequest(extractAnchorText, '请先点击句子作为朗读起点'));
  1575. }
  1576. if (ttsToggleBtn) {
  1577. ttsToggleBtn.addEventListener('click', handlePauseResumeToggle);
  1578. }
  1579. })();
  1580. </script>
  1581. </body>
  1582. </html>"""
  1583. )
  1584. ALLOWED_URL_SCHEMES = {"http", "https"}
  1585. MAX_REMOTE_HTML_BYTES = 1_000_000
  1586. REMOTE_FETCH_TIMEOUT = 10.0
  1587. REMOTE_FETCH_HEADERS = {
  1588. # Use a browser-like user agent and common headers so that sites which
  1589. # block generic HTTP clients are more likely to return normal content.
  1590. "User-Agent": (
  1591. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
  1592. "AppleWebKit/537.36 (KHTML, like Gecko) "
  1593. "Chrome/124.0.0.0 Safari/537.36"
  1594. ),
  1595. "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  1596. "Accept-Language": "en-US,en;q=0.9",
  1597. # Let httpx / the underlying HTTP stack negotiate an encoding it can
  1598. # actually decode. If we unconditionally advertise "br" but the runtime
  1599. # does not have brotli support installed, some sites will respond with
  1600. # brotli-compressed payloads that end up as乱码 or decoding errors.
  1601. #
  1602. # Most modern servers default to gzip or identity when the header is
  1603. # absent, which are both handled fine by httpx.
  1604. # "Accept-Encoding": "gzip, deflate, br",
  1605. "Connection": "keep-alive",
  1606. "Upgrade-Insecure-Requests": "1",
  1607. # A few anti‑bot setups check these request headers; keeping them close
  1608. # to real desktop Chrome values slightly improves compatibility, even
  1609. # though they are not a guarantee against 403 responses.
  1610. "Sec-Fetch-Site": "none",
  1611. "Sec-Fetch-Mode": "navigate",
  1612. "Sec-Fetch-User": "?1",
  1613. "Sec-Fetch-Dest": "document",
  1614. }
  1615. SIMPLE_FETCH_HEADERS = {
  1616. # Minimal browser-like headers for the fallback "simple request" path.
  1617. "User-Agent": (
  1618. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
  1619. "AppleWebKit/537.36 (KHTML, like Gecko) "
  1620. "Chrome/124.0.0.0 Safari/537.36"
  1621. ),
  1622. "Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",
  1623. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  1624. "Connection": "close",
  1625. }
  1626. def _inject_proxy_images(html_fragment: str, images: List[Dict[str, str]]) -> str:
  1627. """Replace stable image placeholders with <img> tags in the highlighted HTML."""
  1628. result = html_fragment
  1629. for idx, img in enumerate(images):
  1630. marker = img.get("marker") or f"__GHIMG_{idx}__"
  1631. src = html.escape(img.get("src", "") or "", quote=True)
  1632. if not src:
  1633. continue
  1634. alt = html.escape(img.get("alt", "") or "", quote=True)
  1635. title = html.escape(img.get("title", "") or "", quote=True)
  1636. attrs = [f"src='{src}'"]
  1637. if alt:
  1638. attrs.append(f"alt='{alt}'")
  1639. if title:
  1640. attrs.append(f"title='{title}'")
  1641. # Preserve simple width/height hints when they look safe. Most modern
  1642. # pages rely on CSS for sizing, but explicit attributes can help keep
  1643. # code snippets or diagrams close to their original scale.
  1644. def _safe_dim(value: Optional[str]) -> Optional[str]:
  1645. if not value:
  1646. return None
  1647. value = value.strip()
  1648. if re.fullmatch(r"\d+(?:\.\d+)?(px|%)?", value):
  1649. return value
  1650. return None
  1651. width = _safe_dim(img.get("width"))
  1652. height = _safe_dim(img.get("height"))
  1653. if width:
  1654. attrs.append(f"width='{html.escape(width, quote=True)}'")
  1655. if height:
  1656. attrs.append(f"height='{html.escape(height, quote=True)}'")
  1657. img_tag = "<img " + " ".join(attrs) + " />"
  1658. # Simple textual replacement is sufficient because placeholders
  1659. # are emitted as plain word tokens without HTML meta characters.
  1660. result = result.replace(marker, img_tag)
  1661. return result
  1662. IMG_MARKER_RE = re.compile(r"__GHIMG_\d+__")
  1663. def _strip_proxy_image_markers(html_fragment: str) -> str:
  1664. """Remove residual image placeholders when images are hidden."""
  1665. if IMG_MARKER_RE.search(html_fragment) is None:
  1666. return html_fragment
  1667. return IMG_MARKER_RE.sub("", html_fragment)
  1668. def _inject_proxy_codeblocks(html_fragment: str, code_blocks: List[Dict[str, str]]) -> str:
  1669. """Replace code placeholders with <pre><code> blocks, preserving formatting."""
  1670. result = html_fragment
  1671. for idx, block in enumerate(code_blocks):
  1672. marker = block.get("marker") or f"__GHCODE_{idx}__"
  1673. raw = block.get("text") or ""
  1674. if not raw.strip():
  1675. continue
  1676. # Escape HTML but keep newlines so that <pre> preserves formatting.
  1677. code_html = html.escape(raw, quote=False)
  1678. pre_tag = f"<pre><code>{code_html}</code></pre>"
  1679. result = result.replace(marker, pre_tag)
  1680. return result
  1681. class SimpleHTMLStripper(HTMLParser):
  1682. def __init__(self):
  1683. super().__init__()
  1684. # Accumulate visible text into paragraph-like blocks while skipping
  1685. # navigation / sidebars / ads etc. We do this with a small HTML
  1686. # structure–aware state machine instead of flattening everything.
  1687. self._blocks: List[Dict[str, Any]] = []
  1688. self._current_parts: List[str] = []
  1689. # Track when we are inside potentially main content containers
  1690. # like <article> or <main>.
  1691. self._article_depth = 0
  1692. # Track whether we are inside a preformatted code block so that we
  1693. # can preserve indentation and line breaks instead of collapsing
  1694. # whitespace as normal text.
  1695. self._in_pre = False
  1696. self._in_code = False
  1697. self._current_code_chunks: List[str] = []
  1698. self._code_blocks: List[Dict[str, str]] = []
  1699. # Stack of flags indicating which open tags should be skipped.
  1700. # When any active flag is True, textual data is ignored.
  1701. self._skip_stack: List[bool] = []
  1702. self._skip_depth = 0
  1703. self._title_chunks: List[str] = []
  1704. self._in_title = False
  1705. self._h1_chunks: List[str] = []
  1706. self._h1_main_chunks: List[str] = []
  1707. self._in_h1 = False
  1708. # Collected inline images from the main content, in document order.
  1709. # Each image is represented as a small dict with sanitized attributes.
  1710. self._images: List[Dict[str, str]] = []
  1711. # Active list containers (<ul>/<ol>) and current <li> nesting state.
  1712. self._list_stack: List[Dict[str, Any]] = []
  1713. self._list_item_stack: List[Dict[str, Any]] = []
  1714. # Keywords commonly used in class/id attributes for non‑article areas
  1715. _NOISE_KEYWORDS = {
  1716. "sidebar",
  1717. "side-bar",
  1718. "aside",
  1719. "nav",
  1720. "menu",
  1721. "breadcrumb",
  1722. "breadcrumbs",
  1723. "pagination",
  1724. "pager",
  1725. "comment",
  1726. "comments",
  1727. "reply",
  1728. "advert",
  1729. "ad-",
  1730. "ads",
  1731. "sponsor",
  1732. "promo",
  1733. "promotion",
  1734. "related",
  1735. "recommend",
  1736. "share",
  1737. "social",
  1738. "subscribe",
  1739. "signup",
  1740. "login",
  1741. "popup",
  1742. "modal",
  1743. "banner",
  1744. "cookie",
  1745. "notification",
  1746. "toolbar",
  1747. "footer",
  1748. "header-bar",
  1749. }
  1750. # Tags whose textual content is almost never part of the main article.
  1751. _ALWAYS_SKIP_TAGS = {
  1752. "script",
  1753. "style",
  1754. "noscript",
  1755. "nav",
  1756. "aside",
  1757. "footer",
  1758. "form",
  1759. "svg",
  1760. "iframe",
  1761. "button",
  1762. "input",
  1763. "textarea",
  1764. "select",
  1765. "option",
  1766. "label",
  1767. }
  1768. # Structural container tags where noise classes/roles are meaningful.
  1769. # For purely inline tags we avoid applying aggressive noise heuristics
  1770. # so that important inline text (e.g. spans in the first sentence) is
  1771. # not accidentally dropped.
  1772. _STRUCTURAL_NOISE_TAGS = {
  1773. "div",
  1774. "section",
  1775. "aside",
  1776. "nav",
  1777. "header",
  1778. "footer",
  1779. "main",
  1780. "article",
  1781. "ul",
  1782. "ol",
  1783. "li",
  1784. }
  1785. # Block-level tags that naturally mark paragraph boundaries.
  1786. _BLOCK_TAGS = {
  1787. "p",
  1788. "li",
  1789. "blockquote",
  1790. "h1",
  1791. "h2",
  1792. "h3",
  1793. "h4",
  1794. "h5",
  1795. "h6",
  1796. "pre",
  1797. "table",
  1798. "tr",
  1799. }
  1800. # Keywords for containers that are likely to hold the main article body.
  1801. # Used to decide which regions count as "main content" for both text
  1802. # and inline images.
  1803. _CONTENT_KEYWORDS = {
  1804. "content",
  1805. "main-content",
  1806. "article-body",
  1807. "post-body",
  1808. "post-content",
  1809. "entry-content",
  1810. "story-body",
  1811. "blog-post",
  1812. "markdown-body",
  1813. "readable-content",
  1814. }
  1815. # Keywords on image-related class/id/src that usually indicate avatars,
  1816. # logo icons, decorative banners, etc., which we want to drop from the
  1817. # extracted main content.
  1818. _IMAGE_NOISE_KEYWORDS = {
  1819. "avatar",
  1820. "author",
  1821. "logo",
  1822. "icon",
  1823. "favicon",
  1824. "badge",
  1825. "banner",
  1826. "thumb",
  1827. "thumbnail",
  1828. "profile",
  1829. "cover",
  1830. "background",
  1831. "sprite",
  1832. "emoji",
  1833. "reaction",
  1834. }
  1835. _TEXT_NOISE_KEYWORDS = {
  1836. "menu",
  1837. "menus",
  1838. "navigation",
  1839. "nav",
  1840. "目录",
  1841. "目錄",
  1842. "导航",
  1843. "導航",
  1844. "菜单",
  1845. "菜單",
  1846. "广告",
  1847. "廣告",
  1848. "ad",
  1849. "ads",
  1850. "sponsor",
  1851. "sponsored",
  1852. "上一篇",
  1853. "下一篇",
  1854. "返回顶部",
  1855. "返回頂部",
  1856. "分享",
  1857. "分享至",
  1858. "相关推荐",
  1859. "相关阅读",
  1860. "相關閱讀",
  1861. "recommended",
  1862. "related posts",
  1863. "login",
  1864. "signup",
  1865. }
  1866. _TEXT_NOISE_PREFIXES = (
  1867. "目录",
  1868. "目錄",
  1869. "导航",
  1870. "導航",
  1871. "菜单",
  1872. "菜單",
  1873. "广告",
  1874. "廣告",
  1875. "上一篇",
  1876. "下一篇",
  1877. "上一页",
  1878. "下一页",
  1879. "返回目录",
  1880. "返回目錄",
  1881. "返回顶部",
  1882. "返回頂部",
  1883. "分享",
  1884. "相关",
  1885. "相關",
  1886. "recommended",
  1887. "login",
  1888. "signup",
  1889. )
  1890. def _finish_paragraph(self) -> None:
  1891. """Flush current buffered tokens into a paragraph list."""
  1892. if not self._current_parts:
  1893. return
  1894. # For regular paragraphs we still collapse excessive internal
  1895. # whitespace, but we keep logical breaks between paragraphs
  1896. # themselves so that the downstream highlighter can reconstruct
  1897. # paragraph structure.
  1898. text = " ".join(self._current_parts)
  1899. text = re.sub(r"\s+", " ", text).strip()
  1900. self._current_parts = []
  1901. if not text:
  1902. return
  1903. if self._looks_like_noise_paragraph(text):
  1904. return
  1905. block_kind = "paragraph"
  1906. list_kind: Optional[str] = None
  1907. list_depth = 0
  1908. list_index: Optional[int] = None
  1909. if self._list_item_stack:
  1910. list_ctx = self._list_item_stack[-1]
  1911. block_kind = "list-item"
  1912. list_kind = list_ctx.get("list_type") or "ul"
  1913. depth_value = list_ctx.get("depth", 1)
  1914. try:
  1915. depth_int = int(depth_value)
  1916. except (TypeError, ValueError):
  1917. depth_int = 1
  1918. list_depth = min(max(depth_int, 1), 5)
  1919. if list_kind == "ol":
  1920. idx = list_ctx.get("index")
  1921. if isinstance(idx, int):
  1922. list_index = idx
  1923. self._blocks.append(
  1924. {
  1925. "text": text,
  1926. "is_main": self._article_depth > 0,
  1927. "kind": block_kind,
  1928. "list_kind": list_kind,
  1929. "list_depth": list_depth,
  1930. "list_index": list_index,
  1931. }
  1932. )
  1933. def _looks_like_noise_paragraph(self, text: str) -> bool:
  1934. normalized = text.strip()
  1935. if not normalized:
  1936. return True
  1937. lowered = normalized.lower()
  1938. compact = re.sub(r"\s+", "", lowered)
  1939. for prefix in self._TEXT_NOISE_PREFIXES:
  1940. if lowered.startswith(prefix.lower()):
  1941. if len(normalized) <= 80:
  1942. return True
  1943. if len(normalized) <= 80:
  1944. for keyword in self._TEXT_NOISE_KEYWORDS:
  1945. if keyword in lowered or keyword in compact:
  1946. return True
  1947. # Skip very short bullet-like crumbs that mostly consist of symbols.
  1948. if len(normalized) <= 6 and sum(ch.isalnum() for ch in normalized) <= 1:
  1949. return True
  1950. return False
  1951. @staticmethod
  1952. def _parse_ordered_start(raw_value: Optional[str]) -> int:
  1953. if raw_value is None:
  1954. return 1
  1955. value = raw_value.strip()
  1956. if not value:
  1957. return 1
  1958. try:
  1959. parsed = int(value)
  1960. return parsed if parsed >= 1 else 1
  1961. except ValueError:
  1962. return 1
  1963. def handle_starttag(self, tag, attrs):
  1964. lowered = tag.lower()
  1965. # Paragraph boundary before starting a new block element or <br>.
  1966. if lowered in self._BLOCK_TAGS or lowered == "br":
  1967. if self._skip_depth == 0:
  1968. self._finish_paragraph()
  1969. # Entering a <pre> region – treat it as a dedicated code block.
  1970. if lowered == "pre" and self._skip_depth == 0:
  1971. self._finish_paragraph()
  1972. self._in_pre = True
  1973. self._current_code_chunks = []
  1974. # Decide whether this element should be skipped entirely.
  1975. attr_dict = {k.lower(): (v or "") for k, v in attrs}
  1976. role = attr_dict.get("role", "").lower()
  1977. classes_ids = (attr_dict.get("class", "") + " " + attr_dict.get("id", "")).lower()
  1978. is_noise_attr = False
  1979. # Only treat class/id keywords as layout "noise" on structural
  1980. # containers (div/section/nav/etc). Inline tags with "comment"
  1981. # in their class (like mdspan-comment on Towards Data Science)
  1982. # should not be discarded, otherwise we lose the first words
  1983. # of sentences.
  1984. if lowered in self._STRUCTURAL_NOISE_TAGS:
  1985. is_noise_attr = any(key in classes_ids for key in self._NOISE_KEYWORDS)
  1986. if role in {"navigation", "banner", "contentinfo", "complementary"}:
  1987. is_noise_attr = True
  1988. skip_this = lowered in self._ALWAYS_SKIP_TAGS or is_noise_attr
  1989. if skip_this:
  1990. self._skip_depth += 1
  1991. self._skip_stack.append(skip_this)
  1992. # Track when we are inside an article-like container; only count if not skipped.
  1993. if self._skip_depth == 0 and lowered in {"article", "main", "section", "div"}:
  1994. # Treat semantic containers and common "main content" classes as
  1995. # part of the article area so that we keep their text and inline
  1996. # media but still avoid sidebars / nav.
  1997. if lowered in {"article", "main"} or any(
  1998. key in classes_ids for key in self._CONTENT_KEYWORDS
  1999. ) or role == "main":
  2000. self._article_depth += 1
  2001. if self._skip_depth == 0 and lowered in {"ul", "ol"}:
  2002. start = 1
  2003. if lowered == "ol":
  2004. start = self._parse_ordered_start(attr_dict.get("start"))
  2005. self._list_stack.append(
  2006. {
  2007. "type": lowered,
  2008. "start": start,
  2009. "next_index": start,
  2010. }
  2011. )
  2012. if lowered == "li" and self._skip_depth == 0:
  2013. list_ctx = self._list_stack[-1] if self._list_stack else None
  2014. depth = len(self._list_stack) if self._list_stack else 1
  2015. list_type = list_ctx.get("type") if list_ctx else "ul"
  2016. index = None
  2017. if list_ctx and list_ctx["type"] == "ol":
  2018. index = list_ctx["next_index"]
  2019. list_ctx["next_index"] = index + 1
  2020. li_value = attr_dict.get("value")
  2021. if li_value and list_ctx and list_ctx["type"] == "ol":
  2022. try:
  2023. value_idx = int(li_value)
  2024. index = value_idx
  2025. list_ctx["next_index"] = value_idx + 1
  2026. except ValueError:
  2027. pass
  2028. self._list_item_stack.append(
  2029. {
  2030. "list_type": list_type,
  2031. "index": index,
  2032. "depth": depth,
  2033. }
  2034. )
  2035. if lowered == "title" and self._skip_depth == 0:
  2036. self._in_title = True
  2037. if lowered == "h1" and self._skip_depth == 0:
  2038. self._in_h1 = True
  2039. if lowered == "code" and self._skip_depth == 0 and self._in_pre:
  2040. # Nested <code> inside <pre> – keep track but we don't need
  2041. # separate buffering beyond the enclosing pre block.
  2042. self._in_code = True
  2043. # Inline image handling: only keep <img> elements that are inside the
  2044. # main article content (tracked via _article_depth) and that do not
  2045. # look like avatars / logos / decorative icons. We insert a stable
  2046. # placeholder token into the text stream so that the /proxy renderer
  2047. # can later replace it with a real <img> tag while preserving the
  2048. # grammar highlighting.
  2049. if lowered == "img" and self._skip_depth == 0 and self._article_depth > 0:
  2050. src = attr_dict.get("src", "").strip()
  2051. if src:
  2052. alt = attr_dict.get("alt", "") or ""
  2053. title = attr_dict.get("title", "") or ""
  2054. width = (attr_dict.get("width") or "").strip()
  2055. height = (attr_dict.get("height") or "").strip()
  2056. img_classes_ids = classes_ids + " " + src.lower()
  2057. if any(key in img_classes_ids for key in self._IMAGE_NOISE_KEYWORDS):
  2058. return
  2059. marker = f"__GHIMG_{len(self._images)}__"
  2060. img_info: Dict[str, str] = {
  2061. "marker": marker,
  2062. "src": src,
  2063. "alt": alt,
  2064. "title": title,
  2065. }
  2066. if width:
  2067. img_info["width"] = width
  2068. if height:
  2069. img_info["height"] = height
  2070. self._images.append(img_info)
  2071. # Treat the image as an inline token within the current
  2072. # paragraph. Paragraph finishing logic will ensure it
  2073. # stays grouped with surrounding text.
  2074. self._current_parts.append(marker)
  2075. def handle_endtag(self, tag):
  2076. lowered = tag.lower()
  2077. if lowered == "code" and self._in_code:
  2078. self._in_code = False
  2079. if lowered == "pre" and self._in_pre:
  2080. self._in_pre = False
  2081. # Finalize the current code block into a single placeholder
  2082. # token so that it passes through the grammar highlighter
  2083. # untouched, and can later be restored as a <pre><code> block.
  2084. code_text = "".join(self._current_code_chunks)
  2085. self._current_code_chunks = []
  2086. if code_text.strip() and self._skip_depth == 0:
  2087. marker = f"__GHCODE_{len(self._code_blocks)}__"
  2088. self._code_blocks.append({"marker": marker, "text": code_text})
  2089. # We append the marker to the paragraph parts so that
  2090. # get_text() emits it in the right position.
  2091. self._current_parts.append(marker)
  2092. # Closing a block element ends the current paragraph.
  2093. if lowered in self._BLOCK_TAGS and self._skip_depth == 0:
  2094. self._finish_paragraph()
  2095. if lowered == "li" and self._skip_depth == 0 and self._list_item_stack:
  2096. self._list_item_stack.pop()
  2097. if lowered in {"ul", "ol"} and self._skip_depth == 0 and self._list_stack:
  2098. self._list_stack.pop()
  2099. if lowered == "title":
  2100. self._in_title = False
  2101. if lowered == "h1":
  2102. self._in_h1 = False
  2103. if lowered in {"article", "main", "section"} and self._skip_depth == 0 and self._article_depth > 0:
  2104. self._article_depth -= 1
  2105. if self._skip_stack:
  2106. skip_this = self._skip_stack.pop()
  2107. if skip_this and self._skip_depth > 0:
  2108. self._skip_depth -= 1
  2109. def handle_data(self, data):
  2110. if self._skip_depth > 0:
  2111. return
  2112. if self._in_pre or self._in_code:
  2113. # Preserve code blocks exactly as they appear, including
  2114. # newlines and indentation.
  2115. self._current_code_chunks.append(data)
  2116. return
  2117. stripped = data.strip()
  2118. if not stripped:
  2119. return
  2120. if self._in_title:
  2121. self._title_chunks.append(stripped)
  2122. return
  2123. # Regular visible text
  2124. self._current_parts.append(stripped)
  2125. if self._in_h1:
  2126. self._h1_chunks.append(stripped)
  2127. if self._article_depth > 0:
  2128. self._h1_main_chunks.append(stripped)
  2129. def get_text(self) -> str:
  2130. # Flush any trailing paragraph.
  2131. self._finish_paragraph()
  2132. blocks = self._selected_blocks()
  2133. if not blocks:
  2134. return ""
  2135. return "\n\n".join(block["text"] for block in blocks)
  2136. def _selected_blocks(self) -> List[Dict[str, Any]]:
  2137. if not self._blocks:
  2138. return []
  2139. main_blocks = [block for block in self._blocks if block.get("is_main")]
  2140. return main_blocks if main_blocks else self._blocks
  2141. def get_blocks(self) -> List[Dict[str, Any]]:
  2142. blocks = self._selected_blocks()
  2143. return [dict(block) for block in blocks]
  2144. def get_title(self) -> str:
  2145. # Prefer <h1> heading (especially inside <article>/<main>) as the
  2146. # primary title; fall back to <title>.
  2147. if self._h1_main_chunks:
  2148. raw = " ".join(self._h1_main_chunks)
  2149. elif self._h1_chunks:
  2150. raw = " ".join(self._h1_chunks)
  2151. elif self._title_chunks:
  2152. raw = " ".join(self._title_chunks)
  2153. else:
  2154. return ""
  2155. return re.sub(r"\s+", " ", raw).strip()
  2156. def get_images(self) -> List[Dict[str, str]]:
  2157. """Return the list of captured inline images in document order."""
  2158. return list(self._images)
  2159. def get_code_blocks(self) -> List[Dict[str, str]]:
  2160. """Return captured code blocks (from <pre>/<code>) in document order."""
  2161. return list(self._code_blocks)
  2162. def _normalize_target_url(raw_url: str) -> str:
  2163. candidate = (raw_url or "").strip()
  2164. if not candidate:
  2165. raise ValueError("请输入要抓取的 URL。")
  2166. parsed = urlparse(candidate if "://" in candidate else f"https://{candidate}")
  2167. if parsed.scheme not in ALLOWED_URL_SCHEMES:
  2168. raise ValueError("仅支持 http/https 协议链接。")
  2169. if not parsed.netloc:
  2170. raise ValueError("URL 缺少域名部分。")
  2171. sanitized = parsed._replace(fragment="")
  2172. return urlunparse(sanitized)
  2173. def _fallback_html_to_text(html_body: str) -> str:
  2174. """Very simple HTML-to-text fallback used when structured extraction fails.
  2175. This does not attempt to distinguish main content from navigation, but it
  2176. guarantees we return *something* for pages whose structure confuses the
  2177. SimpleHTMLStripper heuristics (e.g. some mirror sites).
  2178. """
  2179. # Drop script/style/noscript content outright.
  2180. cleaned = re.sub(
  2181. r"(?is)<(script|style|noscript)[^>]*>.*?</\1>",
  2182. " ",
  2183. html_body,
  2184. )
  2185. # Convert common block separators into newlines.
  2186. cleaned = re.sub(r"(?i)<br\s*/?>", "\n", cleaned)
  2187. cleaned = re.sub(r"(?i)</p\s*>", "\n\n", cleaned)
  2188. cleaned = re.sub(r"(?i)</(div|section|article|li|h[1-6])\s*>", "\n\n", cleaned)
  2189. # Remove all remaining tags.
  2190. cleaned = re.sub(r"(?is)<[^>]+>", " ", cleaned)
  2191. cleaned = html.unescape(cleaned)
  2192. # Normalize whitespace but keep paragraph-level blank lines.
  2193. cleaned = cleaned.replace("\r", "")
  2194. # Collapse runs of spaces/tabs inside lines.
  2195. cleaned = re.sub(r"[ \t\f\v]+", " ", cleaned)
  2196. # Collapse 3+ blank lines into just 2.
  2197. cleaned = re.sub(r"\n\s*\n\s*\n+", "\n\n", cleaned)
  2198. cleaned = cleaned.strip()
  2199. return cleaned
  2200. def _build_paragraph_metadata(blocks: List[Dict[str, Any]]) -> List[Dict[str, str]]:
  2201. """Convert stripped block info into span attributes for downstream rendering."""
  2202. if not blocks:
  2203. return []
  2204. paragraph_meta: List[Dict[str, str]] = []
  2205. for block in blocks:
  2206. attrs: Dict[str, str] = {}
  2207. if block.get("kind") == "list-item" and block.get("list_kind"):
  2208. attrs["data-list-kind"] = str(block["list_kind"])
  2209. depth = block.get("list_depth")
  2210. if depth:
  2211. attrs["data-list-depth"] = str(depth)
  2212. if block.get("list_kind") == "ol" and block.get("list_index") is not None:
  2213. attrs["data-list-index"] = str(block["list_index"])
  2214. paragraph_meta.append(attrs)
  2215. return paragraph_meta
  2216. def _decode_html_bytes(raw_content: bytes, encoding_hint: Optional[str]) -> str:
  2217. encoding_candidates: List[str] = []
  2218. if encoding_hint:
  2219. encoding_candidates.append(encoding_hint)
  2220. encoding_candidates.extend(["utf-8", "latin-1"])
  2221. last_exc: Optional[Exception] = None
  2222. for enc in encoding_candidates:
  2223. try:
  2224. html_body = raw_content.decode(enc, errors="replace")
  2225. break
  2226. except Exception as exc: # pragma: no cover - defensive
  2227. last_exc = exc
  2228. else: # pragma: no cover - extremely unlikely
  2229. raise RuntimeError(f"无法解码远程页面内容: {last_exc}")
  2230. if len(html_body) > MAX_REMOTE_HTML_BYTES:
  2231. html_body = html_body[:MAX_REMOTE_HTML_BYTES]
  2232. return html_body
  2233. async def _download_html_via_httpx(url: str) -> str:
  2234. async with httpx.AsyncClient(timeout=REMOTE_FETCH_TIMEOUT, follow_redirects=True) as client:
  2235. response = await client.get(url, headers=REMOTE_FETCH_HEADERS)
  2236. html_body = _decode_html_bytes(response.content, response.encoding)
  2237. response.raise_for_status()
  2238. return html_body
  2239. async def _download_html_via_stdlib(url: str) -> str:
  2240. def _sync_fetch() -> Tuple[bytes, Optional[str]]:
  2241. req = urllib_request.Request(url, headers=SIMPLE_FETCH_HEADERS)
  2242. opener = urllib_request.build_opener(urllib_request.ProxyHandler({}))
  2243. with opener.open(req, timeout=REMOTE_FETCH_TIMEOUT) as resp:
  2244. data = resp.read(MAX_REMOTE_HTML_BYTES + 1)
  2245. headers = getattr(resp, "headers", None)
  2246. encoding_hint = None
  2247. if headers is not None:
  2248. get_charset = getattr(headers, "get_content_charset", None)
  2249. if callable(get_charset):
  2250. encoding_hint = get_charset()
  2251. if not encoding_hint:
  2252. content_type = headers.get("Content-Type", "")
  2253. match = re.search(r"charset=([\w-]+)", content_type or "", re.IGNORECASE)
  2254. if match:
  2255. encoding_hint = match.group(1)
  2256. return data, encoding_hint
  2257. raw_content, encoding_hint = await asyncio.to_thread(_sync_fetch)
  2258. return _decode_html_bytes(raw_content, encoding_hint)
  2259. async def _download_html_with_fallback(url: str) -> str:
  2260. first_exc: Optional[Exception] = None
  2261. try:
  2262. return await _download_html_via_httpx(url)
  2263. except httpx.HTTPStatusError as exc:
  2264. status = exc.response.status_code if exc.response is not None else None
  2265. if status not in {401, 403, 407, 451, 429}:
  2266. raise
  2267. first_exc = exc
  2268. except httpx.HTTPError as exc:
  2269. first_exc = exc
  2270. try:
  2271. return await _download_html_via_stdlib(url)
  2272. except (urllib_error.URLError, urllib_error.HTTPError, TimeoutError) as fallback_exc:
  2273. if first_exc:
  2274. raise first_exc from fallback_exc
  2275. raise
  2276. async def _fetch_remote_plaintext(
  2277. url: str,
  2278. ) -> Tuple[str, str, str, List[Dict[str, str]], List[Dict[str, str]], List[Dict[str, str]]]:
  2279. normalized = _normalize_target_url(url)
  2280. html_body = await _download_html_with_fallback(normalized)
  2281. stripper = SimpleHTMLStripper()
  2282. stripper.feed(html_body)
  2283. title = stripper.get_title() or normalized
  2284. images = stripper.get_images()
  2285. code_blocks = stripper.get_code_blocks()
  2286. plain_text = stripper.get_text()
  2287. block_info = stripper.get_blocks()
  2288. if not plain_text:
  2289. plain_text = _fallback_html_to_text(html_body)
  2290. if not plain_text:
  2291. raise ValueError("未能从该页面提取正文。")
  2292. # Fallback text no longer contains structured placeholders, so any
  2293. # collected media/code markers would be invalid.
  2294. images = []
  2295. code_blocks = []
  2296. block_info = []
  2297. paragraph_meta = _build_paragraph_metadata(block_info)
  2298. return normalized, title, plain_text, images, code_blocks, paragraph_meta
  2299. def _render_proxy_page(
  2300. *,
  2301. url_value: str = "",
  2302. message: Optional[str] = None,
  2303. is_error: bool = False,
  2304. highlight_fragment: Optional[str] = None,
  2305. helper_enabled: bool = False,
  2306. source_url: Optional[str] = None,
  2307. source_title: Optional[str] = None,
  2308. show_images: bool = False,
  2309. image_notice: Optional[str] = None,
  2310. source_plaintext: Optional[str] = None,
  2311. ) -> str:
  2312. helper_state = "on" if helper_enabled else "off"
  2313. status_block = ""
  2314. if message:
  2315. cls = "status err" if is_error else "status ok"
  2316. status_block = f"<p class='{cls}'>{html.escape(message)}</p>"
  2317. style_block = STYLE_BLOCK if highlight_fragment else ""
  2318. result_block = ""
  2319. source_script = ""
  2320. if highlight_fragment and source_url:
  2321. safe_url = html.escape(source_url, quote=True)
  2322. safe_title = html.escape(source_title or source_url)
  2323. image_hint = ""
  2324. if image_notice:
  2325. image_hint = f"<p class='image-hint'>{html.escape(image_notice)}</p>"
  2326. if source_plaintext:
  2327. source_script = f"<script>window.__proxySourceText = {json.dumps(source_plaintext)}</script>"
  2328. result_block = (
  2329. "<section class='result'>"
  2330. f"<div class='source'>原页面:<a href='{safe_url}' target='_blank' rel='noopener'>{safe_title}</a></div>"
  2331. f"<div class='analysis' data-helper='{helper_state}'>{highlight_fragment}</div>"
  2332. f"{image_hint}"
  2333. "</section>"
  2334. )
  2335. show_images_checked = "checked" if show_images else ""
  2336. return PROXY_PAGE_TEMPLATE.substitute(
  2337. style_block=style_block,
  2338. url_value=html.escape(url_value or "", quote=True),
  2339. status_block=status_block,
  2340. result_block=result_block,
  2341. show_images_checked=show_images_checked,
  2342. source_text_script=source_script,
  2343. )