Spaces:
Sleeping
Sleeping
Update backend/server.py
Browse files1234567891011121314151617181920219 unmodified lines31323334353686 unmodified lines12312412512612712812930 unmodified lines1601611621631641651663 unmodified lines17017117217317417517612 unmodified lines1891901911921931941951961971981998 unmodified lines20820921021121221312 unmodified lines2262272282292302312328 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228316 unmodified lines3003013023033043053064 unmodified lines311312313314315316317318170 unmodified lines48949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056132 unmodified lines59459559659759859920 unmodified lines6206216226236246253 unmodified lines62963063163263363463519 unmodified lines65565665765865966066122 unmodified lines68468568668768868969069169237 unmodified lines73073173273373473563 unmodified lines79980080180280380480580680731 unmodified lines8398408418428438448458468478488498508518 unmodified lines8608618628638648658668678688698708718728738748758 unmodified lines884885886887888889import asyncio, base64, copy, hashlib, io, json, os, re, tempfile, time, uuid, httpxfrom backend import lens_core as corefrom collections import OrderedDictfrom threading import Lockfrom dataclasses import dataclassfrom typing import Any, Dict, List, Optionalfrom fastapi import FastAPI, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewareSERVER_MAX_WORKERS = int(os.environ.get('SERVER_MAX_WORKERS', '15'))JOB_TTL_SEC = int(os.environ.get('JOB_TTL_SEC', '3600'))HTTP_TIMEOUT_SEC = float(os.environ.get('HTTP_TIMEOUT_SEC', str(getattr(core, 'AI_TIMEOUT_SEC', 120))))SUPPORTED_MODES = {"lens_images", "lens_text"}BUILD_ID = os.environ.get('TP_BUILD_ID', 'v9-backendfix-20260129')TP_DEBUG = str(os.environ.get('TP_DEBUG', '')).strip().lower() in ('1', 'true', 'yes', 'on')TP_PARA_MARKER_PREFIX = '<<TP_P'TP_PARA_MARKER_SUFFIX = '>>'9 unmodified lines_result_cache_lock = Lock()_ai_cache_lock = Lock()def _dbg(tag: str, data=None) -> None:if not TP_DEBUG:return86 unmodified linesidx = _extract_marker_indices(ai_text_full)if len(idx) >= expected_paras:return Falseif (TP_PARA_MARKER_PREFIX in (ai_text_full or '')) and (TP_PARA_MARKER_SUFFIX not in (ai_text_full or '')):return Truereturn True30 unmodified linesreturn hashlib.sha256(t.encode('utf-8')).hexdigest()[:12]def _build_cache_key(img_hash: str, lang: str, mode: str, source: str, ai_cfg: Optional["AiConfig"]) -> str:parts = [img_hash, _normalize_lang(lang), (mode or '').strip(), (source or '').strip()]if ai_cfg and (source or '').strip().lower() == 'ai':parts.extend([(ai_cfg.provider or '').strip(),3 unmodified lines])return '|'.join([p for p in parts if p is not None])def _b64_to_bytes(b64: str) -> bytes:pad = '=' * ((4 - (len(b64) % 4)) % 4)return base64.b64decode(b64 + pad)12 unmodified linesb64 = base64.b64encode(blob).decode('ascii')return f"data:{mime};base64,{b64}"def _download_bytes(url: str) -> tuple[bytes, str]:u = (url or '').strip()if not u:return b'', ''with httpx.Client(timeout=HTTP_TIMEOUT_SEC, follow_redirects=True) as client:r = client.get(u)r.raise_for_status()ct = (r.headers.get('content-type') or '').split(';')[0].strip()8 unmodified linesdef _resolve_model(provider: str, model: str) -> str:return core._resolve_model(provider, model)def _normalize_lang(lang: str) -> str:return core._normalize_lang(lang)12 unmodified linest = str(marked_text or "")if not t:return ""indices = _extract_marker_indices(t)if not indices:return _collapse_ws(t)out_lines: List[str] = []8 unmodified linesout_lines.append("")return "\n".join(out_lines).strip("\n")def _build_ai_prompt_packet_custom(target_lang: str, original_text_full: str, prompt_editable: str, is_retry: bool = False) -> tuple[str, List[str]]:lang = _normalize_lang(target_lang)style_prompt = (prompt_editable or "").strip()if not style_prompt:style_prompt = (getattr(core, "ai_prompt_user_default",lambda _l: "")(lang) or "").strip()input_json = json.dumps({"target_lang": lang, "stylePrompt": style_prompt,"originalTextFull": str(original_text_full or "")},ensure_ascii=False,)system_parts: List[str] = ["SYSTEM: You translate manga dialogue.","Task: Translate originalTextFull into target_lang. Apply stylePrompt.","Markers: Keep every paragraph marker like <<TP_P0>> unchanged and in order. Do not remove or add markers.","Output: Return ONLY JSON (no markdown, no extra text).","OUTPUT_JSON schema: {\"aiTextFull\":\"...\"}","aiTextFull must include all the same markers, each followed by that paragraph's translated text.","Keep text concise for speech bubbles. Avoid long repeated characters (max 12).",]if is_retry:system_parts.append("Retry: Your previous output may have been truncated. You MUST output ALL markers from the first to the last marker in the input.")system_text = "\n".join([p for p in system_parts if p])user_text = ("INPUT_JSON (json):\n```json\n"+ input_json+ "\n```\n\nOUTPUT_JSON (json):\n```json\n{\"aiTextFull\":\"...\"}\n```")return system_text, [user_text]def ai_translate_text(original_text_full: str, target_lang: str, ai: AiConfig, is_retry: bool = False) -> dict:api_key = (ai.api_key or '').strip()if not api_key:raise Exception('AI api_key is required')16 unmodified lines'base_url') or 'https://api.openai.com/v1'system_text, user_parts = _build_ai_prompt_packet_custom(target_lang, original_text_full, ai.prompt_editable, is_retry=is_retry)started = _now()used_model = model4 unmodified linesraw = core._anthropic_generate_json(api_key, model, system_text, user_parts)else:raw, used_model = core._openai_compat_generate_json(api_key, base_url, model, system_text, user_parts)ai_text_full = core._parse_ai_textfull_only(raw) if core.DO_AI_JSON else core._parse_ai_textfull_text_only(raw)170 unmodified linessrc_paras = _tree_to_paragraph_texts(original_tree or {})src_text = _apply_para_markers(src_paras) if src_paras else str(out.get('originalTextFull') or '')ai = ai_translate_text(src_text, target_lang, ai_cfg)if src_paras and _needs_ai_retry(str(ai.get('aiTextFull') or ''), len(src_paras)):_dbg('ai.retry', {'expected_paras': len(src_paras),'found_markers': len(_extract_marker_indices(str(ai.get('aiTextFull') or ''))),})retry_paras = [_clamp_runaway_repeats(p) for p in src_paras]retry_text = _apply_para_markers(retry_paras) or src_textai = ai_translate_text(retry_text, target_lang, ai_cfg, is_retry=True)template_tree = _pick_ai_template_tree()_dbg('ai.template.pick', {'score_original': _tree_score(original_tree),'score_translated': _tree_score(translated_tree),'picked': 'original' if template_tree is original_tree else ('translated' if template_tree is translated_tree else 'none'),})if not isinstance(template_tree, dict):template_tree = original_tree if isinstance(original_tree, dict) else (translated_tree if isinstance(translated_tree, dict) else {})patched = core.patch({'Ai': {'aiTextFull': str(ai.get('aiTextFull') or ''), 'aiTree': template_tree}},W,H,thai_font or '',latin_font or '',lang=target_lang,)ai_tree = (patched.get('Ai') or {}).get('aiTree') or {}_dbg('ai.patched', {'ai_text_len': len(str(ai.get('aiTextFull') or '')),'stats_ai': _tree_stats(ai_tree),'stats_original': _tree_stats(original_tree or {}),'stats_translated': _tree_stats(translated_tree or {}),'mode': mode_id,'lang': target_lang,})shared_para_sizes = core._compute_shared_para_sizes([original_tree or {}, translated_tree or {}, ai_tree or {}],thai_font or '',latin_font or '',W,H,)core._apply_para_font_size(original_tree or {}, shared_para_sizes)core._apply_para_font_size(translated_tree or {}, shared_para_sizes)core._apply_para_font_size(ai_tree or {}, shared_para_sizes)core._rebuild_ai_spans_after_font_resize(ai_tree or {}, W, H, thai_font or '', latin_font or '', lang=target_lang)out['AiTextFull'] = str(ai.get('aiTextFull') or '')out['Ai'] = {'aiTextFull': str(ai.get('aiTextFull') or ''),'aiTree': ai_tree,'meta': ai.get('meta') or {},}if getattr(core, 'DO_AI_HTML', True):core.fit_tree_font_sizes_for_tp_html(ai_tree, thai_font or '', latin_font or '', W, H)out['Ai']['aihtml'] = core.ai_tree_to_tp_html(ai_tree, W, H)out['Ai']['aihtmlMeta'] = {'baseW': int(W),'baseH': int(H),'format': 'tp',}if getattr(core, 'DO_ORIGINAL', True) and getattr(core, 'DO_ORIGINAL_HTML', True) and isinstance(original_tree, dict):core.fit_tree_font_sizes_for_tp_html(32 unmodified linesallow_headers=['*'],)async def _cleanup_jobs_loop():while True:await asyncio.sleep(60)20 unmodified linesmode = (payload.get('mode') or 'lens_images')lang = (payload.get('lang') or 'en')src = (payload.get('src') or '').strip()img_bytes = b''mime = ''3 unmodified lineselif src.startswith('data:'):img_bytes, mime = _datauri_to_bytes(src)else:img_bytes, mime = _download_bytes(src)t_img = time.perf_counter()19 unmodified linesimg_hash = _sha256_hex(img_bytes)cache_key = ''if mode == 'lens_text' and img_hash:cache_key = _build_cache_key(img_hash, lang, mode, source, ai_cfg)cached = Noneif source == 'ai':cached = _lru_get(_ai_result_cache, _ai_cache_lock, cache_key)22 unmodified lines}if cache_key and isinstance(out, dict):if source == 'ai':_lru_set(_ai_result_cache, _ai_cache_lock, cache_key, out, TP_AI_RESULT_CACHE_MAX)else:_lru_set(_result_cache, _result_cache_lock, cache_key, out, TP_RESULT_CACHE_MAX)return outfinally:try:37 unmodified lines@app.post('/translate')async def translate(payload: Dict[str, Any]):jid = str(uuid.uuid4())_jobs[jid] = {'status': 'queued', 'ts': _now()}await _job_queue.put((jid, payload))return {'id': jid}63 unmodified linesif provider == 'huggingface' and not models:models = ['google/gemma-3-27b-it:featherless-a',]if not models:fallback_models: List[str] = []preset_model = str(preset.get('model') or '').strip()if preset_model:31 unmodified lineskey=str.lower,)if models and requested_model.lower() in ('', 'auto') and resolved_model not in models:resolved_model = models[0]defaults = core._remote_defaults()prompt_default = (getattr(core, 'ai_prompt_user_default',lambda _l, _d=None: '')(lang, defaults) or '').strip()return {'ok': True,8 unmodified lines@app.get('/ai/prompt/default')async def ai_prompt_default(lang: str = 'en'):l = _normalize_lang(lang)defaults = core._remote_defaults()styles = core.ai_lang_style_map(defaults)return {'ok': True,'lang': l,'prompt_editable_default': (getattr(core, 'ai_prompt_user_default', lambda _l, _d=None: '')(l, defaults) or '').strip(),'lang_style': styles.get(l) or styles.get('default') or '','system_base': core.ai_prompt_system_base(defaults).strip(),'contract': core._active_ai_contract(),'data_template': core._active_ai_data_template(),}@app.websocket('/ws')8 unmodified linescontinuejid = str(data.get('id') or '')payload = data.get('payload') or {}try:result = await asyncio.to_thread(_process_payload, payload)try:123456789101112131415161718192021229 unmodified lines3233343536373839404142434445464748495051525354555657585986 unmodified lines14614714814915015115230 unmodified lines1831841851861871881891903 unmodified lines19419519619719819912 unmodified lines2122132142152162172182192202212222232242252262272282298 unmodified lines23823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429512 unmodified lines3083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373388 unmodified lines34734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841916 unmodified lines4364374384394404414424434 unmodified lines448449450451452453454455456457458459170 unmodified lines63063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775832 unmodified lines79179279379479579679779879980080180280380480580680780880981081181281381420 unmodified lines8358368378388398408418428438443 unmodified lines84884985085185285385419 unmodified lines87487587687787887988088188222 unmodified lines90590690790890991091191291391491537 unmodified lines95395495595695795895996096196296396496596663 unmodified lines10301031103210331034103510361037103810391040104131 unmodified lines107310741075107610771078107910801081108210838 unmodified lines109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611178 unmodified lines11261127112811291130113111321133113411351136113711381139import asyncio, base64, copy, hashlib, io, json, os, re, tempfile, time, uuid, httpx, loggingfrom backend import lens_core as corefrom http import HTTPStatusfrom collections import OrderedDictfrom threading import Lock, Semaphorefrom dataclasses import dataclassfrom typing import Any, Dict, List, Optionalfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, Requestfrom fastapi.middleware.cors import CORSMiddlewareSERVER_MAX_WORKERS = int(os.environ.get('SERVER_MAX_WORKERS', '15'))JOB_TTL_SEC = int(os.environ.get('JOB_TTL_SEC', '3600'))HTTP_TIMEOUT_SEC = float(os.environ.get('HTTP_TIMEOUT_SEC', str(getattr(core, 'AI_TIMEOUT_SEC', 120))))SUPPORTED_MODES = {"lens_images", "lens_text"}BUILD_ID = os.environ.get('TP_BUILD_ID', 'v9-backendfix-20260129')TP_DEBUG = str(os.environ.get('TP_DEBUG', '')).strip().lower() in ('1', 'true', 'yes', 'on')TP_PARA_MARKER_PREFIX = '<<TP_P'TP_PARA_MARKER_SUFFIX = '>>'9 unmodified lines_result_cache_lock = Lock()_ai_cache_lock = Lock()HF_AI_MAX_CONCURRENCY = max(1, int(os.environ.get('HF_AI_MAX_CONCURRENCY', '1')))HF_AI_MIN_INTERVAL_SEC = max(0.0, float(os.environ.get('HF_AI_MIN_INTERVAL_SEC', '5')))HF_AI_MAX_RETRIES = max(1, int(os.environ.get('HF_AI_MAX_RETRIES', '6')))HF_AI_RETRY_BASE_SEC = max(0.2, float(os.environ.get('HF_AI_RETRY_BASE_SEC', '2')))_hf_ai_sem = Semaphore(HF_AI_MAX_CONCURRENCY)_hf_ai_lock = Lock()_hf_ai_last_ts = 0.0_tp_marker_re = re.compile(r'<<TP_P\d+>>')TP_ACCESS_LOG_MODE = (os.environ.get('TP_ACCESS_LOG_MODE', 'custom') or 'custom').strip().lower()if TP_ACCESS_LOG_MODE in ('custom', 'tp', 'plain'):try:_uv = logging.getLogger('uvicorn.access')_uv.disabled = True_uv.propagate = False_uv.setLevel(logging.CRITICAL)except Exception:passdef _dbg(tag: str, data=None) -> None:if not TP_DEBUG:return86 unmodified linesidx = _extract_marker_indices(ai_text_full)if len(idx) >= expected_paras:return Falseif (TP_PARA_MARKER_PREFIX in (ai_text_full or '')) and (TP_PARA_MARKER_SUFFIX not in (ai_text_full or '')):return Truereturn True30 unmodified linesreturn hashlib.sha256(t.encode('utf-8')).hexdigest()[:12]def _build_cache_key(img_hash: str, lang: str, mode: str, source: str, ai_cfg: Optional["AiConfig"]) -> str:parts = [img_hash, _normalize_lang(lang), (mode or '').strip(), (source or '').strip()]if ai_cfg and (source or '').strip().lower() == 'ai':parts.extend([(ai_cfg.provider or '').strip(),3 unmodified lines])return '|'.join([p for p in parts if p is not None])def _b64_to_bytes(b64: str) -> bytes:pad = '=' * ((4 - (len(b64) % 4)) % 4)return base64.b64decode(b64 + pad)12 unmodified linesb64 = base64.b64encode(blob).decode('ascii')return f"data:{mime};base64,{b64}"def _download_bytes(url: str, referer: str = '') -> tuple[bytes, str]:u = (url or '').strip()if not u:return b'', ''headers = {'user-agent': 'Mozilla/5.0 (TextPhantomOCR; +https://huggingface.co/spaces)',}ref = (referer or '').strip()if ref:headers['referer'] = refwith httpx.Client(timeout=HTTP_TIMEOUT_SEC, follow_redirects=True, headers=headers) as client:r = client.get(u)r.raise_for_status()ct = (r.headers.get('content-type') or '').split(';')[0].strip()8 unmodified linesdef _resolve_model(provider: str, model: str) -> str:return core._resolve_model(provider, model)def _has_meaningful_text(s: str) -> bool:t = _tp_marker_re.sub('', str(s or ''))return bool(t.strip())def _is_hf_provider(provider: str, base_url: str) -> bool:p = (provider or '').strip().lower()b = (base_url or '').strip().lower()return p == 'huggingface' or 'router.huggingface.co' in bdef _is_hf_rate_limited_error(msg: str) -> bool:t = (msg or '').lower()if 'rate limit' in t or 'ratelimit' in t or 'too many requests' in t:return Trueif 'http 429' in t or ' 429' in t:return Trueif 'http 503' in t or ' 503' in t or 'overloaded' in t or 'temporarily' in t:return Truereturn Falsedef _hf_throttle_before_call() -> None:if HF_AI_MIN_INTERVAL_SEC <= 0:returnglobal _hf_ai_last_tswith _hf_ai_lock:now = _now()dt = now - float(_hf_ai_last_ts or 0.0)wait = HF_AI_MIN_INTERVAL_SEC - dtif wait > 0:time.sleep(wait)_hf_ai_last_ts = _now()def _openai_compat_generate_with_hf_backoff(api_key: str, base_url: str, model: str, system_text: str, user_parts: List[str]):last_err: Optional[Exception] = Nonefor attempt in range(int(HF_AI_MAX_RETRIES)):try:with _hf_ai_sem:_hf_throttle_before_call()return core._openai_compat_generate_json(api_key, base_url, model, system_text, user_parts)except Exception as e:last_err = eif not _is_hf_rate_limited_error(str(e)):raisedelay = min(15.0, max(float(HF_AI_MIN_INTERVAL_SEC), float(HF_AI_RETRY_BASE_SEC) * (2 ** min(attempt, 4))))_dbg('ai.hf.backoff', {'attempt': attempt + 1, 'delay_sec': round(delay, 2), 'err': str(e)[:240]})time.sleep(delay)continueif last_err is not None:raise last_errraise Exception('hf_backoff_failed')def _normalize_lang(lang: str) -> str:return core._normalize_lang(lang)12 unmodified linest = str(marked_text or "")if not t:return ""t = t.replace("\r\n", "\n").replace("\r", "\n")t = re.sub(r"<<TP_P(?!\d+>>)[^\s>]*>?", "", t)t = re.sub(r"(?m)^\s*(<<TP_P\d+>>)\s*(\S)", r"\1\n\2", t)lines = t.split("\n")out0: List[str] = []for line in lines:if "<<TP_P" not in line:out0.append(line)continuem = re.match(r"^\s*(<<TP_P\d+>>)\s*$", line)if m:out0.append(m.group(1))continuem2 = re.match(r"^\s*(<<TP_P\d+>>)\s*(.*)$", line)if m2:out0.append(m2.group(1))rest = (m2.group(2) or "").strip()if rest:out0.append(rest)continueout0.append(re.sub(r"<<TP_P\d+>>", "", line))t = "\n".join(out0)indices = sorted(_extract_marker_indices(t))if not indices:return _collapse_ws(t)out_lines: List[str] = []8 unmodified linesout_lines.append("")return "\n".join(out_lines).strip("\n")def _has_complete_marker_sequence(ai_text_full: str, expected_paras: int) -> bool:if expected_paras <= 0:return Truet = str(ai_text_full or "")need = list(range(int(expected_paras)))idx = sorted(_extract_marker_indices(t))if len(idx) < len(need):return Falseif idx[:len(need)] != need:return Falselast = -1for i in need:m = f"<<TP_P{i}>>"p = t.find(m)if p < 0 or p <= last:return Falselast = preturn Truedef _build_ai_prompt_packet_custom(target_lang: str, original_text_full: str, prompt_editable: str, is_retry: bool = False) -> tuple[str, List[str]]:lang = _normalize_lang(target_lang)style_prompt = (prompt_editable or "").strip()if not style_prompt:style_prompt = (getattr(core, "ai_prompt_user_default",lambda _l, _m=None: "")(lang)or "").strip()base = (getattr(core, "AI_PROMPT_SYSTEM_BASE", "") or "").strip()style = ((getattr(core, "AI_LANG_STYLE", {}) or {}).get(lang)or (getattr(core, "AI_LANG_STYLE", {}) or {}).get("default")or "").strip()contract_parts: List[str] = ["Follow the user's StylePrompt as hard constraints (unless it would break marker rules).","Output ONLY the translated text (no JSON, no markdown, no extra commentary).","Markers: Keep every paragraph marker like <<TP_P0>> unchanged and in order. Do not remove, rename, or add markers.","For each marker, output the marker followed by that paragraph's translated text.",]if is_retry:contract_parts.append("Retry: You MUST output ALL markers from the first to the last marker in the input.")system_text = "\n\n".join([p for p in [base, style, "\n".join(contract_parts)] if p])user_parts: List[str] = []if style_prompt:user_parts.append("StylePrompt:\n" + style_prompt)user_parts.append("Input:\n" + str(original_text_full or ""))return system_text, user_partsdef ai_translate_text(original_text_full: str, target_lang: str, ai: AiConfig, is_retry: bool = False) -> dict:if not _has_meaningful_text(original_text_full):return {'aiTextFull': '','meta': {'skipped': True,'skipped_reason': 'no_text',},}api_key = (ai.api_key or '').strip()if not api_key:raise Exception('AI api_key is required')16 unmodified lines'base_url') or 'https://api.openai.com/v1'system_text, user_parts = _build_ai_prompt_packet_custom(target_lang, original_text_full, ai.prompt_editable, is_retry=is_retry)started = _now()used_model = model4 unmodified linesraw = core._anthropic_generate_json(api_key, model, system_text, user_parts)else:if _is_hf_provider(provider, base_url):raw, used_model = _openai_compat_generate_with_hf_backoff(api_key, base_url, model, system_text, user_parts)else:raw, used_model = core._openai_compat_generate_json(api_key, base_url, model, system_text, user_parts)ai_text_full = core._parse_ai_textfull_only(raw) if core.DO_AI_JSON else core._parse_ai_textfull_text_only(raw)170 unmodified linessrc_paras = _tree_to_paragraph_texts(original_tree or {})src_text = _apply_para_markers(src_paras) if src_paras else str(out.get('originalTextFull') or '')if not _has_meaningful_text(src_text):out['AiTextFull'] = ''out['Ai'] = {'meta': {'skipped': True,'skipped_reason': 'no_text',}}else:ai = ai_translate_text(src_text, target_lang, ai_cfg)if src_paras and _needs_ai_retry(str(ai.get('aiTextFull') or ''), len(src_paras)):_dbg('ai.retry', {'expected_paras': len(src_paras),'found_markers': len(_extract_marker_indices(str(ai.get('aiTextFull') or ''))),})retry_paras = [_clamp_runaway_repeats(p) for p in src_paras]retry_text = _apply_para_markers(retry_paras) or src_textai = ai_translate_text(retry_text, target_lang, ai_cfg, is_retry=True)ai_text_full = str(ai.get('aiTextFull') or '')meta0 = ai.get('meta') or {}if src_paras:expected = len(src_paras)if not _has_complete_marker_sequence(ai_text_full, expected):fallback_paras = _tree_to_paragraph_texts(translated_tree or {})if len(fallback_paras) < expected:fallback_paras = (fallback_paras + src_paras)[:expected]else:fallback_paras = fallback_paras[:expected]found = sorted(_extract_marker_indices(ai_text_full))seg_map: Dict[int, str] = {}for idx in found:if idx < 0 or idx >= expected:continuemarker = f"<<TP_P{idx}>>"m = re.search(rf"{re.escape(marker)}\s*([\s\S]*?)(?=<<TP_P\d+>>|\Z)", ai_text_full)seg = _collapse_ws(m.group(1) if m else '')if seg and idx not in seg_map:seg_map[idx] = segmissing = 0out_lines: List[str] = []for i in range(expected):seg = seg_map.get(i) or _collapse_ws(fallback_paras[i] if i < len(fallback_paras) else '')if not seg_map.get(i):missing += 1out_lines.append(f"<<TP_P{i}>>")out_lines.append(seg)out_lines.append('')ai_text_full = "\n".join(out_lines).strip("\n")_dbg('ai.marker.repaired', {'expected_paras': expected,'found_markers': len(seg_map),'missing': missing,})meta0 = {**meta0,'marker_repaired': True,'marker_expected': expected,'marker_found': len(seg_map),'marker_missing': missing,}template_tree = _pick_ai_template_tree()_dbg('ai.template.pick', {'score_original': _tree_score(original_tree),'score_translated': _tree_score(translated_tree),'picked': 'original' if template_tree is original_tree else ('translated' if template_tree is translated_tree else 'none'),})if not isinstance(template_tree, dict):template_tree = original_tree if isinstance(original_tree, dict) else (translated_tree if isinstance(translated_tree, dict) else {})patched = core.patch({'Ai': {'aiTextFull': str(ai_text_full or ''), 'aiTree': template_tree}},W,H,thai_font or '',latin_font or '',lang=target_lang,)ai_tree = (patched.get('Ai') or {}).get('aiTree') or {}_dbg('ai.patched', {'ai_text_len': len(ai_text_full),'stats_ai': _tree_stats(ai_tree),'stats_original': _tree_stats(original_tree or {}),'stats_translated': _tree_stats(translated_tree or {}),'mode': mode_id,'lang': target_lang,})shared_para_sizes = core._compute_shared_para_sizes([original_tree or {}, translated_tree or {}, ai_tree or {}],thai_font or '',latin_font or '',W,H,)core._apply_para_font_size(original_tree or {}, shared_para_sizes)core._apply_para_font_size(translated_tree or {}, shared_para_sizes)core._apply_para_font_size(ai_tree or {}, shared_para_sizes)core._rebuild_ai_spans_after_font_resize(ai_tree or {}, W, H, thai_font or '', latin_font or '', lang=target_lang)out['AiTextFull'] = ai_text_fullout['Ai'] = {'aiTextFull': ai_text_full,'aiTree': ai_tree,'meta': meta0,}if getattr(core, 'DO_AI_HTML', True):core.fit_tree_font_sizes_for_tp_html(ai_tree, thai_font or '', latin_font or '', W, H)out['Ai']['aihtml'] = core.ai_tree_to_tp_html(ai_tree, W, H)out['Ai']['aihtmlMeta'] = {'baseW': int(W),'baseH': int(H),'format': 'tp',}if getattr(core, 'DO_ORIGINAL', True) and getattr(core, 'DO_ORIGINAL_HTML', True) and isinstance(original_tree, dict):core.fit_tree_font_sizes_for_tp_html(32 unmodified linesallow_headers=['*'],)@app.middleware("http")async def _tp_access_log(request: Request, call_next):resp = await call_next(request)if TP_ACCESS_LOG_MODE in ('uvicorn', 'off', 'none'):return resptry:path = request.url.pathif request.method == 'GET' and path.startswith("/translate/"):client = request.clienthost = client.host if client else "-"port = client.port if client else 0ver = request.scope.get("http_version") or "1.1"phrase = HTTPStatus(resp.status_code).phraseprint(f'{host}:{port} - "{request.method} {path} HTTP/{ver}" {resp.status_code} {phrase}', flush=True)except Exception:passreturn respasync def _cleanup_jobs_loop():while True:await asyncio.sleep(60)20 unmodified linesmode = (payload.get('mode') or 'lens_images')lang = (payload.get('lang') or 'en')context = payload.get('context') if isinstance(payload.get('context'), dict) else {}page_url = str((context or {}).get('page_url') or '').strip()src = (payload.get('src') or '').strip()img_bytes = b''mime = ''3 unmodified lineselif src.startswith('data:'):img_bytes, mime = _datauri_to_bytes(src)else:img_bytes, mime = _download_bytes(src, page_url)t_img = time.perf_counter()19 unmodified linesimg_hash = _sha256_hex(img_bytes)cache_key = ''if mode == 'lens_text' and img_hash:cache_source = 'ai' if source == 'ai' else 'text'cache_key = _build_cache_key(img_hash, lang, mode, cache_source, ai_cfg)cached = Noneif source == 'ai':cached = _lru_get(_ai_result_cache, _ai_cache_lock, cache_key)22 unmodified lines}if cache_key and isinstance(out, dict):if source == 'ai':_lru_set(_ai_result_cache, _ai_cache_lock,cache_key, out, TP_AI_RESULT_CACHE_MAX)else:_lru_set(_result_cache, _result_cache_lock,cache_key, out, TP_RESULT_CACHE_MAX)return outfinally:try:37 unmodified lines@app.post('/translate')async def translate(payload: Dict[str, Any]):jid = str(uuid.uuid4())_dbg('rest.enqueue', {'id': jid,'mode': str(payload.get('mode') or ''),'lang': str(payload.get('lang') or ''),'source': str(payload.get('source') or ''),'has_datauri': bool(payload.get('imageDataUri')),'has_src': bool(payload.get('src')),})_jobs[jid] = {'status': 'queued', 'ts': _now()}await _job_queue.put((jid, payload))return {'id': jid}63 unmodified linesif provider == 'huggingface' and not models:models = ['google/gemma-3-27b-it:featherless-a','google/gemma-3-27b-it','google/gemma-2-2b-it','google/gemma-2-9b-it',]if provider != 'huggingface' and not models:fallback_models: List[str] = []preset_model = str(preset.get('model') or '').strip()if preset_model:31 unmodified lineskey=str.lower,)if models and resolved_model not in models:resolved_model = models[0]prompt_default = (getattr(core, 'ai_prompt_user_default',lambda _l: '')(lang) or '').strip()return {'ok': True,8 unmodified lines@app.get('/ai/prompt/default')async def ai_prompt_default(lang: str = 'en'):l = _normalize_lang(lang)base = (getattr(core, 'AI_PROMPT_SYSTEM_BASE', '') or '').strip()style = (getattr(core, 'AI_LANG_STYLE', {}) or {}).get(l) or (getattr(core, 'AI_LANG_STYLE', {}) or {}).get('default') or ''style = (style or '').strip()contract = "\n".join(['Return ONLY valid JSON (no markdown, no extra text).','Output JSON MUST have exactly one key: "aiTextFull".','Schema example: {"aiTextFull":"..."}','Markers: Keep every paragraph marker like <<TP_P0>> unchanged and in order. Do not remove or add markers.',"aiTextFull must include all markers, each followed by that paragraph's translated text.",])system_text = "\n\n".join([p for p in [base, style, contract] if p])return {'ok': True,'lang': l,'prompt_editable_default': (getattr(core, 'ai_prompt_user_default', lambda _l: '')(l) or '').strip(),'lang_style': style,'system_base': base,'contract': contract,'system_text': system_text,}@app.websocket('/ws')8 unmodified linescontinuejid = str(data.get('id') or '')payload = data.get('payload') or {}_dbg('ws.job', {'id': jid,'mode': str(payload.get('mode') or ''),'lang': str(payload.get('lang') or ''),'source': str(payload.get('source') or ''),'has_datauri': bool(payload.get('imageDataUri')),'has_src': bool(payload.get('src')),})try:result = await asyncio.to_thread(_process_payload, payload)try:
backend/server.py+373-123