mainspacy.py 95 KB

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