mainspacy.py 92 KB

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