Update backend/lens_core.py
Browse files186 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030131 unmodified lines333334335336337338339340341342100 unmodified lines4434444454464474484494504514524534544554564574584594604614624634645 unmodified lines47047147247347447547625 unmodified lines50250350450550650750853 unmodified lines56256356456556656756856957057157257357457557657757857958058158258358458558658758858959025 unmodified lines616617618619620621622943 unmodified lines156615671568156915701571157215731574157515761577157815791580158115821583158415855 unmodified lines15911592159315941595159615972 unmodified lines1600160116021603160416051606160716081 unmodified line16101611161216131614161516162 unmodified lines1619162016211622162316241625162616271628162916301631163295 unmodified lines1728172917301731173217331734182 unmodified lines1917191819191920192119221923621 unmodified lines2545254625472548254925502551351 unmodified lines290329042905290629072908290947 unmodified lines295729582959296029612962296342 unmodified lines3006300730083009301030113012186 unmodified lines}}AI_PROMPT_SYSTEM_BASE = ""AI_LANG_STYLE = {"default": ""}AI_PROMPT_USER_BY_LANG = {"default": ""}TP_REMOTE_DEFAULTS_URL = (os.environ.get("TP_REMOTE_DEFAULTS_URL")or "https://raw.githubusercontent.com/Kuju29/TextPhantomOCR_Overlay/refs/heads/main/defaults_api.json").strip()TP_REMOTE_DEFAULTS_TIMEOUT_SEC = float(os.environ.get("TP_REMOTE_DEFAULTS_TIMEOUT_SEC", "2"))def _remote_defaults() -> dict:url = TP_REMOTE_DEFAULTS_URLif not url:raise RuntimeError("TP_REMOTE_DEFAULTS_URL is required")if url.startswith("file://"):with open(url[len("file://"):], "r", encoding="utf-8") as f:raw = f.read()else:with httpx.Client(timeout=TP_REMOTE_DEFAULTS_TIMEOUT_SEC) as client:r = client.get(url,headers={"accept": "application/json"},follow_redirects=True,)r.raise_for_status()raw = r.textdata = json.loads((raw or "").strip() or "{}")if not isinstance(data, dict) or not data:raise RuntimeError("Remote defaults is empty")return datadef _remote_first_str(data: dict, *keys: str) -> str:if not data:return ""for k in keys:v = data.get(k)if isinstance(v, str) and v.strip():return v.strip()return ""def _remote_first_map(data: dict, *keys: str) -> dict:if not data:return {}for k in keys:v = data.get(k)if isinstance(v, dict) and v:return vreturn {}def ai_prompt_system_base(data: dict | None = None) -> str:d = data if isinstance(data, dict) else _remote_defaults()v = _remote_first_str(d,"AI_PROMPT_SYSTEM_BASE","aiPromptSystemBase","promptSystemBase","systemBase",)if not v:raise RuntimeError("Missing AI_PROMPT_SYSTEM_BASE in remote defaults")return vdef ai_lang_style_map(data: dict | None = None) -> dict[str, str]:d = data if isinstance(data, dict) else _remote_defaults()remote = _remote_first_map(d, "AI_LANG_STYLE", "aiLangStyle", "langStyle")if not remote:raise RuntimeError("Missing AI_LANG_STYLE in remote defaults")out: dict[str, str] = {}for k, v in remote.items():if not isinstance(k, str) or not isinstance(v, str):continuekk = _normalize_lang(k)if not kk:continueout[kk] = v.strip()out.setdefault("default", "")return outdef ai_prompt_user_by_lang_map(data: dict | None = None) -> dict[str, str]:d = data if isinstance(data, dict) else _remote_defaults()remote = _remote_first_map(d,"AI_PROMPT_USER_BY_LANG","aiPromptUserByLang","promptUserByLang",)if not remote:raise RuntimeError("Missing AI_PROMPT_USER_BY_LANG in remote defaults")out: dict[str, str] = {}for k, v in remote.items():if not isinstance(k, str) or not isinstance(v, str):continuekk = _normalize_lang(k)if not kk:continueout[kk] = v.strip()out.setdefault("default", "")return outAI_PROMPT_RESPONSE_CONTRACT_JSON = ("Return ONLY valid JSON (no markdown, no extra text).\n"31 unmodified lines_TP_HTML_EPS_PX = 0.0ZWSP = "\u200b"def ai_prompt_user_default(lang: str, data: dict | None = None) -> str:l = _normalize_lang(lang)m = ai_prompt_user_by_lang_map(data)return (m.get(l) or m.get("default") or "").strip()def _active_ai_contract() -> str:return AI_PROMPT_RESPONSE_CONTRACT_JSON if DO_AI_JSON else AI_PROMPT_RESPONSE_CONTRACT_TEXT100 unmodified linesjson.dump(cache, f, ensure_ascii=False)os.replace(tmp, path)def _build_ai_prompt_packet(target_lang: str, original_text_full: str, defaults: dict | None = None):lang = _normalize_lang(target_lang)d = defaults if isinstance(defaults, dict) else _remote_defaults()input_json = json.dumps({"target_lang": lang, "originalTextFull": original_text_full}, ensure_ascii=False)output_schema = json.dumps({"aiTextFull": "..."}, ensure_ascii=False)data_template = _active_ai_data_template()if DO_AI_JSON:data_text = data_template.format(input_json=input_json, output_schema=output_schema)else:data_text = data_template.format(input_json=input_json)styles = ai_lang_style_map(d)style = styles.get(lang) or styles.get("default") or ""editable = (ai_prompt_user_default(lang, d) or "").strip()system_parts = [ai_prompt_system_base(d)]if style:system_parts.append(style)system_parts.append(_active_ai_contract())5 unmodified linesuser_parts.append(data_text)return system_text, user_partsdef _gemini_generate_json(api_key: str, model: str, system_text: str, user_parts: list[str]):url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"parts = [{"text": p} for p in user_parts if (p or "").strip()]25 unmodified linesraise Exception("Gemini returned empty text")return txtdef _read_first_env(*names: str) -> str:for n in names:v = (os.environ.get(n) or "").strip()53 unmodified linesdef _openai_compat_generate_json(api_key: str, base_url: str, model: str, system_text: str, user_parts: list[str]):url = (base_url.rstrip("/") + "/chat/completions")def _user_only_prompt_for_model(m: str) -> bool:ml = (m or "").strip().lower()if not ml:return Falseif "gemma-3" in ml or "gemma-2" in ml:return Trueif "gemma" in ml and ("-it" in ml or "instruct" in ml):return Truereturn Falsedef _build_messages(m: str):parts = [p.strip() for p in (user_parts or []) if isinstance(p, str) and p.strip()]sys = (system_text or "").strip()if _user_only_prompt_for_model(m):combined = "\n\n".join([x for x in ([sys] + parts) if x])return [{"role": "user", "content": combined}]msgs = [{"role": "system", "content": system_text}]for p in parts:msgs.append({"role": "user", "content": p})return msgsmessages = _build_messages(model)payload = {"model": model,"messages": messages,25 unmodified linesfallback = _pick_hf_fallback_model(models)if fallback and fallback != model:payload["model"] = fallbackpayload["messages"] = _build_messages(fallback)used_model = fallbackr2 = client.post(url, json=payload, headers=headers)try:943 unmodified linesif not api_key:raise Exception("AI_API_KEY is required for AI translation")defaults = _remote_defaults()lang = _normalize_lang(target_lang)styles = ai_lang_style_map(defaults)edit_map = ai_prompt_user_by_lang_map(defaults)sys_base = ai_prompt_system_base(defaults)prompt_sig = _sha1(json.dumps({"sys": sys_base,"edit": edit_map,"contract": _active_ai_contract(),"data": _active_ai_data_template(),"style": styles.get(lang) or styles.get("default") or "",},ensure_ascii=False,)5 unmodified linescache = _load_ai_cache(AI_CACHE_PATH)cache_key = _sha1(json.dumps({"provider": provider, "m": model, "u": base_url, "l": lang, "p": prompt_sig, "t": original_text_full},ensure_ascii=False,))2 unmodified linesif lang == "th" and cached:t = str(cached.get("aiTextFull") or "")if t:t2 = re.sub(r"(?:(?<=^)|(?<=[\s\"'ββββ()\[\]{}<>]))ΰΈΰΈ²ΰΈ’(?=(?:\s|$))", "", t)t2 = re.sub(r"[ ]{2,}", " ", t2)t2 = re.sub(r"^[ ]+", "", t2, flags=re.MULTILINE)if t2 != t:cached = dict(cached)cached["aiTextFull"] = t21 unmodified line_save_ai_cache(AI_CACHE_PATH, cache)return cachedsystem_text, user_parts = _build_ai_prompt_packet(lang, original_text_full, defaults)started = time.time()used_model = model2 unmodified lineselif provider == "anthropic":raw = _anthropic_generate_json(api_key, model, system_text, user_parts)else:raw, used_model = _openai_compat_generate_json(api_key, base_url, model, system_text, user_parts)ai_text_full = _parse_ai_textfull_only(raw) if DO_AI_JSON else _parse_ai_textfull_text_only(raw)if lang == "th" and ai_text_full:ai_text_full = re.sub(r"(?:(?<=^)|(?<=[\s\"'ββββ()\[\]{}<>]))ΰΈΰΈ²ΰΈ’(?=(?:\s|$))", "", ai_text_full)ai_text_full = re.sub(r"[ ]{2,}", " ", ai_text_full)ai_text_full = re.sub(r"^[ ]+", "", ai_text_full, flags=re.MULTILINE)result = {"aiTextFull": ai_text_full,95 unmodified linesreturn b2f(v)return Nonedef _get_points_from_geom(geom_bytes):pts = []height = None182 unmodified linesangle_deg_raw = math.degrees(math.atan2(dy, dx))angle_deg = _normalize_angle_deg(angle_deg_raw)angle_deg_css = angle_degheight_px = height_norm * img_h621 unmodified linesitem_idx = int(_tp_num(it.get("item_index")) or ii)fs_raw = _tp_num(it.get("font_size_px"))fs = int(round(fs_raw)) if fs_raw and fs_raw > 0 else max(10, int(round(h0 * 0.85)))fs = max(6, min(fs, max(6, int(math.floor(h0 * 0.95)))))351 unmodified linesdef _item_avail_w_px(item: dict, W: int, H: int) -> float:b = item.get("box") or {}w_box = float(b.get("width") or 0.0) * float(W)L = 0.0p1 = item.get("baseline_p1") or {}p2 = item.get("baseline_p2") or {}47 unmodified linesif (tw2 <= avail_w * 0.999) and (th2 <= avail_h * 0.999):breaksize -= 1if size <= 12 and avail_h >= 24:tw0, th0, _ = mif tw0 > (avail_w * 1.2):42 unmodified linesif not fits:continuefits.sort()p["para_font_size_px"] = int(fits[len(fits) // 2])186 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625731 unmodified lines289290291292293294295296297100 unmodified lines3983994004014024034044054064074084094104114124134144154164174184195 unmodified lines42542642742842943025 unmodified lines45645745845946046153 unmodified lines51551651751851952052152252352425 unmodified lines550551552553554555943 unmodified lines1499150015011502150315041505150615071508150915101511151215135 unmodified lines151915201521152215231524152515262 unmodified lines15291530153115321533153415351536153715381 unmodified line15401541154215431544154515462 unmodified lines1549155015511552155315541555155615571558155915601561156215631564156595 unmodified lines166116621663166416651666182 unmodified lines1849185018511852185318541855621 unmodified lines2477247824792480248124822483351 unmodified lines283528362837283828392840284147 unmodified lines288928902891289228932894289542 unmodified lines2938293929402941294229432944186 unmodified lines}}AI_PROMPT_SYSTEM_BASE = ("You are a professional manga translator and dialogue localizer.\n""Rewrite each paragraph as natural dialogue in the target language while preserving meaning, tone, intent, and character voice.\n""Keep lines concise for speech bubbles. Do not add new information. Do not omit meaning. Do not explain.\n""Preserve emphasis (β¦ ! ?). Avoid excessive punctuation.\n""If the input is already in the target language, improve it (dialogue polish) without changing meaning.")AI_LANG_STYLE = {"th": ("Target language: Thai\\n""Write Thai manga dialogue that reads like a high-quality Thai scanlation: natural, concise, and in-character.\\n""Keep lines short for speech bubbles; avoid stiff, literal phrasing.\\n""Default: omit pronouns and omit gendered polite sentence-final particles unless the source line clearly requires them.\\n""Never use the word 'ΰΈΰΈ±ΰΈ'. Prefer omitting the subject.\\n""Never use a male-coded second-person pronoun. When addressing someone by name, do not add a second-person pronoun after the name; prefer NAME + clause.\\n""If a second-person reference is unavoidable, use a neutral/casual form appropriate to tone, but keep it gender-neutral and consistent with the line.\\n""Use particles/interjections sparingly to match tone; do not overuse.\\n""Keep names/terms consistent; transliterate when appropriate.\\n""Output only the translated text."),"en": ("Target language: English\n""Write natural English manga dialogue: concise, conversational, with contractions where natural.\n""Localize tone and character voice; keep emotion and emphasis.\n""Keep proper nouns consistent; do not over-explain."),"ja": ("Target language: Japanese\n""Write natural Japanese manga dialogue: concise, spoken.\n""Choose δΈε―§θͺ/γΏγ‘ε£ to match context; keep emotion and emphasis.\n""Keep proper nouns consistent; keep SFX natural in Japanese."),"default": ("Write natural manga dialogue in the target language: concise, spoken, faithful to meaning and tone."),}AI_PROMPT_USER_BY_LANG = {"th": """ΰΉΰΈΰΉΰΈ²ΰΈ«ΰΈ‘ΰΈ²ΰΈ’ΰΈ ΰΈ²ΰΈ©ΰΈ²: ΰΉΰΈΰΈ’ΰΉΰΈΰΈ₯ΰΈΰΉΰΈΰΈΰΈ§ΰΈ²ΰΈ‘ OCR ΰΉΰΈΰΈ‘ΰΈ±ΰΈΰΈΰΈ°ΰΉΰΈΰΉΰΈΰΈ ΰΈ²ΰΈ©ΰΈ²ΰΉΰΈΰΈ’ΰΈΰΈ£ΰΈ£ΰΈ‘ΰΈΰΈ²ΰΈΰΈ΄ΰΉΰΈΰΈΰΈΰΈΰΈͺΰΈΰΈΰΈΰΈ²ΰΈΰΈΰΈΰΉΰΈ³ΰΉΰΈͺΰΈ΅ΰΈ’ΰΈ/ΰΈΰΈ²ΰΈ£ΰΈ‘ΰΈΰΉΰΉΰΈ«ΰΉΰΉΰΈ«ΰΈ‘ΰΈ²ΰΈ°ΰΈΰΈ±ΰΈΰΈΰΈ£ΰΈ΄ΰΈΰΈΰΈͺΰΈ±ΰΉΰΈ ΰΈΰΈ£ΰΈ°ΰΈΰΈ±ΰΈ ΰΈΰΉΰΈ²ΰΈΰΈ₯ΰΈ·ΰΉΰΈ ΰΈ«ΰΉΰΈ²ΰΈ‘ΰΉΰΈͺΰΉΰΈΰΈ³ΰΈΰΈΰΈ΄ΰΈΰΈ²ΰΈ’ΰΈ«ΰΈ£ΰΈ·ΰΈΰΈΰΈ£ΰΈ£ΰΈ’ΰΈ²ΰΈ’ΰΉΰΈΰΈ΄ΰΉΰΈ‘ΰΈΰΈΰΈΰΈ·ΰΉΰΈΰΉΰΈΰΈΰΈ²ΰΈ°/ΰΈ¨ΰΈ±ΰΈΰΈΰΉΰΉΰΈΰΈΰΈ²ΰΈ°ΰΉΰΈ«ΰΉΰΈͺΰΈ‘ΰΉΰΈ³ΰΉΰΈͺΰΈ‘ΰΈ ΰΉΰΈ₯ΰΈ°ΰΈͺΰΉΰΈΰΈΰΈΰΈΰΉΰΈΰΉΰΈΰΈΰΉΰΈΰΈΰΈ§ΰΈ²ΰΈ‘ΰΉΰΈΰΈ’ΰΉΰΈΰΉΰΈ²ΰΈΰΈ±ΰΉΰΈ""".strip(),"en": """Style preferences:- Keep English dialogue concise and conversational.- Keep lines short for speech bubbles.- Keep names and recurring terms consistent.- Keep SFX short; avoid very long repeated characters.""".strip(),"ja": """Style preferences:- Keep Japanese dialogue concise and natural for manga.- Keep lines short for speech bubbles.- Keep names and recurring terms consistent.- Keep SFX short; avoid very long repeated characters.""".strip(),"default": """Style preferences:- Keep dialogue concise, spoken, and faithful to tone.- Keep lines short for speech bubbles.- Keep names and recurring terms consistent.- Keep SFX short; avoid very long repeated characters.""".strip(),}AI_PROMPT_RESPONSE_CONTRACT_JSON = ("Return ONLY valid JSON (no markdown, no extra text).\n"31 unmodified lines_TP_HTML_EPS_PX = 0.0ZWSP = "\u200b"def ai_prompt_user_default(lang: str, model: str = "auto") -> str:l = _normalize_lang(lang)return (AI_PROMPT_USER_BY_LANG.get(l) or AI_PROMPT_USER_BY_LANG.get("default") or "").strip()def _active_ai_contract() -> str:return AI_PROMPT_RESPONSE_CONTRACT_JSON if DO_AI_JSON else AI_PROMPT_RESPONSE_CONTRACT_TEXT100 unmodified linesjson.dump(cache, f, ensure_ascii=False)os.replace(tmp, path)def _build_ai_prompt_packet(target_lang: str, original_text_full: str):lang = _normalize_lang(target_lang)input_json = json.dumps({"target_lang": lang, "originalTextFull": original_text_full}, ensure_ascii=False)output_schema = json.dumps({"aiTextFull": "..."}, ensure_ascii=False)data_template = _active_ai_data_template()if DO_AI_JSON:data_text = data_template.format(input_json=input_json, output_schema=output_schema)else:data_text = data_template.format(input_json=input_json)style = AI_LANG_STYLE.get(lang) or AI_LANG_STYLE.get("default") or ""editable = (ai_prompt_user_default(lang) or "").strip()system_parts = [AI_PROMPT_SYSTEM_BASE]if style:system_parts.append(style)system_parts.append(_active_ai_contract())5 unmodified linesuser_parts.append(data_text)return system_text, user_partsdef _gemini_generate_json(api_key: str, model: str, system_text: str, user_parts: list[str]):url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"parts = [{"text": p} for p in user_parts if (p or "").strip()]25 unmodified linesraise Exception("Gemini returned empty text")return txtdef _read_first_env(*names: str) -> str:for n in names:v = (os.environ.get(n) or "").strip()53 unmodified linesdef _openai_compat_generate_json(api_key: str, base_url: str, model: str, system_text: str, user_parts: list[str]):url = (base_url.rstrip("/") + "/chat/completions")messages = [{"role": "system", "content": system_text}]for p in user_parts:if (p or "").strip():messages.append({"role": "user", "content": p})payload = {"model": model,"messages": messages,25 unmodified linesfallback = _pick_hf_fallback_model(models)if fallback and fallback != model:payload["model"] = fallbackused_model = fallbackr2 = client.post(url, json=payload, headers=headers)try:943 unmodified linesif not api_key:raise Exception("AI_API_KEY is required for AI translation")lang = _normalize_lang(target_lang)prompt_sig = _sha1(json.dumps({"sys": AI_PROMPT_SYSTEM_BASE,"edit": AI_PROMPT_USER_BY_LANG,"contract": _active_ai_contract(),"data": _active_ai_data_template(),"style": AI_LANG_STYLE.get(lang) or AI_LANG_STYLE.get("default") or "",},ensure_ascii=False,)5 unmodified linescache = _load_ai_cache(AI_CACHE_PATH)cache_key = _sha1(json.dumps({"provider": provider, "m": model, "u": base_url,"l": lang, "p": prompt_sig, "t": original_text_full},ensure_ascii=False,))2 unmodified linesif lang == "th" and cached:t = str(cached.get("aiTextFull") or "")if t:t2 = re.sub(r"(?:(?<=^)|(?<=[\s\"'ββββ()\[\]{}<>]))\u0e19\u0e32\u0e22(?=(?:\s|$))", "", t)t2 = re.sub(r"[ \t]{2,}", " ", t2)t2 = re.sub(r"^[ \t]+", "", t2, flags=re.MULTILINE)if t2 != t:cached = dict(cached)cached["aiTextFull"] = t21 unmodified line_save_ai_cache(AI_CACHE_PATH, cache)return cachedsystem_text, user_parts = _build_ai_prompt_packet(lang, original_text_full)started = time.time()used_model = model2 unmodified lineselif provider == "anthropic":raw = _anthropic_generate_json(api_key, model, system_text, user_parts)else:raw, used_model = _openai_compat_generate_json(api_key, base_url, model, system_text, user_parts)ai_text_full = _parse_ai_textfull_only(raw) if DO_AI_JSON else _parse_ai_textfull_text_only(raw)if lang == "th" and ai_text_full:ai_text_full = re.sub(r"(?:(?<=^)|(?<=[\s\"'ββββ()\[\]{}<>]))\u0e19\u0e32\u0e22(?=(?:\s|$))", "", ai_text_full)ai_text_full = re.sub(r"[ \t]{2,}", " ", ai_text_full)ai_text_full = re.sub(r"^[ \t]+", "", ai_text_full, flags=re.MULTILINE)result = {"aiTextFull": ai_text_full,95 unmodified linesreturn b2f(v)return Nonedef _get_points_from_geom(geom_bytes):pts = []height = None182 unmodified linesangle_deg_raw = math.degrees(math.atan2(dy, dx))angle_deg = _normalize_angle_deg(angle_deg_raw)angle_deg_css = angle_degheight_px = height_norm * img_h621 unmodified linesitem_idx = int(_tp_num(it.get("item_index")) or ii)fs_raw = _tp_num(it.get("font_size_px"))fs = int(round(fs_raw)) if fs_raw and fs_raw > 0 else max(10, int(round(h0 * 0.85)))fs = max(6, min(fs, max(6, int(math.floor(h0 * 0.95)))))351 unmodified linesdef _item_avail_w_px(item: dict, W: int, H: int) -> float:b = item.get("box") or {}w_box = float(b.get("width") or 0.0) * float(W)L = 0.0p1 = item.get("baseline_p1") or {}p2 = item.get("baseline_p2") or {}47 unmodified linesif (tw2 <= avail_w * 0.999) and (th2 <= avail_h * 0.999):breaksize -= 1if size <= 12 and avail_h >= 24:tw0, th0, _ = mif tw0 > (avail_w * 1.2):42 unmodified linesif not fits:continuefits.sort()p["para_font_size_px"] = int(fits[len(fits) // 2])
backend/lens_core.py+100-168