mainspacy.py 96 KB

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