File size: 17,030 Bytes
f6f8d06 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
import re
import time
import base64
import json
import cv2
import numpy as np
from typing import List, Optional
import openai
import httpx
from .base import register_OCR, OCRBase, TextBlock
@register_OCR("llm_ocr")
class LLM_OCR(OCRBase):
lang_map = {
"Auto Detect": None,
"Afrikaans": "af",
"Albanian": "sq",
"Amharic": "am",
"Arabic": "ar",
"Armenian": "hy",
"Assamese": "as",
"Azerbaijani": "az",
"Bangla": "bn",
"Basque": "eu",
"Belarusian": "be",
"Bengali": "bn",
"Bosnian": "bs",
"Breton": "br",
"Bulgarian": "bg",
"Burmese": "my",
"Catalan": "ca",
"Cebuano": "ceb",
"Cherokee": "chr",
"Chinese (Simplified)": "zh-CN",
"Chinese (Traditional)": "zh-TW",
"Corsican": "co",
"Croatian": "hr",
"Czech": "cs",
"Danish": "da",
"Dutch": "nl",
"English": "en",
"Esperanto": "eo",
"Estonian": "et",
"Faroese": "fo",
"Filipino": "fil",
"Finnish": "fi",
"French": "fr",
"Frisian": "fy",
"Galician": "gl",
"Georgian": "ka",
"German": "de",
"Greek": "el",
"Gujarati": "gu",
"Haitian Creole": "ht",
"Hausa": "ha",
"Hawaiian": "haw",
"Hebrew": "he",
"Hindi": "hi",
"Hmong": "hmn",
"Hungarian": "hu",
"Icelandic": "is",
"Igbo": "ig",
"Indonesian": "id",
"Interlingua": "ia",
"Irish": "ga",
"Italian": "it",
"Japanese": "ja",
"Javanese": "jv",
"Kannada": "kn",
"Kazakh": "kk",
"Khmer": "km",
"Korean": "ko",
"Kurdish": "ku",
"Kyrgyz": "ky",
"Lao": "lo",
"Latin": "la",
"Latvian": "lv",
"Lithuanian": "lt",
"Luxembourgish": "lb",
"Macedonian": "mk",
"Malagasy": "mg",
"Malay": "ms",
"Malayalam": "ml",
"Maltese": "mt",
"Maori": "mi",
"Marathi": "mr",
"Mongolian": "mn",
"Nepali": "ne",
"Norwegian": "no",
"Occitan": "oc",
"Oriya": "or",
"Pashto": "ps",
"Persian": "fa",
"Polish": "pl",
"Portuguese": "pt",
"Punjabi": "pa",
"Quechua": "qu",
"Romanian": "ro",
"Russian": "ru",
"Samoan": "sm",
"Scots Gaelic": "gd",
"Serbian (Cyrillic)": "sr-Cyrl",
"Serbian (Latin)": "sr-Latn",
"Shona": "sn",
"Sindhi": "sd",
"Sinhala": "si",
"Slovak": "sk",
"Slovenian": "sl",
"Somali": "so",
"Spanish": "es",
"Sundanese": "su",
"Swahili": "sw",
"Swedish": "sv",
"Tagalog": "tl",
"Tajik": "tg",
"Tamil": "ta",
"Tatar": "tt",
"Telugu": "te",
"Thai": "th",
"Tibetan": "bo",
"Tigrinya": "ti",
"Tongan": "to",
"Turkish": "tr",
"Ukrainian": "uk",
"Urdu": "ur",
"Uyghur": "ug",
"Uzbek": "uz",
"Vietnamese": "vi",
"Welsh": "cy",
"Xhosa": "xh",
"Yiddish": "yi",
"Yoruba": "yo",
"Zulu": "zu",
}
popular_models = [
"OAI: gpt-4o-mini",
"OAI: gpt-4-vision-preview",
"OAI: gpt-4o",
"OAI: gpt-4",
"GGL: gemini-1.5-pro-latest",
"GGL: gemini-1.5-flash-latest",
]
params = {
"provider": {
"type": "selector",
"options": ["OpenAI", "Google", "OpenRouter"],
"value": "OpenAI",
"description": "Select the LLM provider.",
},
"api_key": {
"value": "",
"description": "API key to use if multiple keys are not provided.",
},
"multiple_keys": {
"type": "editor",
"value": "",
"description": "API keys separated by semicolons (;). Requests will rotate.",
},
"endpoint": {
"value": "",
"description": "Base URL for the API. Leave empty for provider default.",
},
"model": {
"type": "selector",
"options": popular_models,
"value": "OAI: gpt-4o-mini",
"description": "Select the model to use.",
},
"override_model": {
"value": "",
"description": "Specify a custom model name to override the selected one.",
},
"language": {
"type": "selector",
"options": list(lang_map.keys()),
"value": "Japanese",
"description": "Language for OCR.",
},
"detail_level": {
"type": "selector",
"options": ["auto", "low", "high"],
"value": "auto",
"description": "Controls image detail level for vision models.",
},
"prompt": {
"type": "editor",
"value": "Perform OCR on the provided manga image snippet. The language is **{language}**.\nRecognize all text, including handwritten sound effects (SFX).\n**CRITICAL INSTRUCTION:** If you see jumbled characters, it is likely vertical text that was read horizontally. First, mentally reconstruct the correct vertical text.\n**OUTPUT FORMATTING:** All recognized text from the image must be consolidated into a **single, continuous horizontal line**. Do not use newlines.\nYour final output must be ONLY the recognized text. No explanations.",
"description": "The main prompt for the OCR task. Use {language} placeholder.",
},
"system_prompt": {
"type": "editor",
"value": "You are a specialized OCR engine for manga and comics. Your primary function is to accurately extract and consolidate all recognized text from an image into a **single, continuous horizontal line**. You must return only the raw, recognized text. You do not interpret, translate, or explain the content. You are designed to intelligently handle common OCR errors, such as reconstructing jumbled characters that result from misreading vertical text.",
"description": "Optional system prompt to guide the model's behavior.",
},
"proxy": {
"value": "",
"description": "Proxy address (e.g., http(s)://user:password@host:port)",
},
"delay": {"value": 1.0, "description": "Delay in seconds between requests."},
"requests_per_minute": {
"value": 15,
"description": "Maximum number of requests per minute per key.",
},
"max_response_tokens": {
"value": 4096,
"description": "Maximum number of tokens in the LLM's response.",
},
"description": "OCR using various vision-capable LLMs.",
}
def __init__(self, **params) -> None:
super().__init__(**params)
self.last_request_time = 0
self.client = None
self.request_count_minute = 0
self.minute_start_time = time.time()
self.key_usage = {}
self.current_key_index = 0
def _initialize_client(self, api_key_to_use: str):
endpoint = self.endpoint
provider = self.provider
if not endpoint:
if provider == "OpenAI":
endpoint = "https://api.openai.com/v1"
elif provider == "Google":
endpoint = "https://generativelanguage.googleapis.com/v1beta/openai"
elif provider == "OpenRouter":
endpoint = "https://openrouter.ai/api/v1"
http_client = None
if self.proxy:
try:
proxy_mounts = {"all://": httpx.HTTPTransport(proxy=self.proxy)}
http_client = httpx.Client(mounts=proxy_mounts)
except Exception as e:
self.logger.error(f"Failed to initialize proxy '{self.proxy}': {e}.")
masked_key = (
api_key_to_use[:4] + "..." + api_key_to_use[-4:]
if len(api_key_to_use) > 8
else api_key_to_use
)
self.logger.debug(
f"Initializing client for {provider} with key {masked_key} at endpoint {endpoint}"
)
self.client = openai.OpenAI(
api_key=api_key_to_use, base_url=endpoint, http_client=http_client
)
# --- Property Getters (similar to translator) ---
@property
def provider(self) -> str:
return self.get_param_value("provider")
@property
def api_key(self) -> str:
return self.get_param_value("api_key")
@property
def multiple_keys_list(self) -> List[str]:
keys_str = self.get_param_value("multiple_keys")
if not isinstance(keys_str, str):
return []
return [
key.strip()
for key in keys_str.strip().replace("\n", ";").split(";")
if key.strip()
]
@property
def endpoint(self) -> Optional[str]:
return self.get_param_value("endpoint") or None
@property
def model(self) -> str:
return self.get_param_value("model")
@property
def override_model(self) -> Optional[str]:
return self.get_param_value("override_model") or None
@property
def language(self) -> str:
return self.get_param_value("language")
@property
def detail_level(self) -> str:
return self.get_param_value("detail_level")
@property
def prompt(self) -> str:
return self.get_param_value("prompt")
@property
def system_prompt(self) -> str:
return self.get_param_value("system_prompt")
@property
def proxy(self) -> str:
return self.get_param_value("proxy")
@property
def requests_per_minute(self) -> int:
return int(self.get_param_value("requests_per_minute"))
@property
def max_response_tokens(self) -> int:
return int(self.get_param_value("max_response_tokens"))
@property
def request_delay(self) -> float:
try:
return float(self.get_param_value("delay"))
except (ValueError, TypeError):
return 1.0
def _respect_delay(self):
# This logic is identical to the one in LLM_API_Translator
current_time = time.time()
rpm = self.requests_per_minute
if rpm > 0:
if current_time - self.minute_start_time >= 60:
self.request_count_minute = 0
self.minute_start_time = current_time
if self.request_count_minute >= rpm:
wait_time = 60.1 - (current_time - self.minute_start_time)
if wait_time > 0:
self.logger.warning(
f"Global RPM limit ({rpm}) reached. Waiting {wait_time:.2f}s."
)
time.sleep(wait_time)
self.request_count_minute = 0
self.minute_start_time = time.time()
time_since_last_request = current_time - self.last_request_time
if time_since_last_request < self.request_delay:
sleep_time = self.request_delay - time_since_last_request
if self.debug_mode:
self.logger.debug(f"Global delay: Waiting {sleep_time:.3f}s.")
time.sleep(sleep_time)
self.last_request_time = time.time()
self.request_count_minute += 1
def _respect_key_limit(self, key: str) -> bool:
# This logic is identical to the one in LLM_API_Translator
rpm = self.requests_per_minute
if rpm <= 0:
return True
now = time.time()
count, start_time = self.key_usage.get(key, (0, now))
if now - start_time >= 60:
count, start_time = 0, now
if count >= rpm:
wait_time = 60.1 - (now - start_time)
if wait_time > 0:
self.logger.warning(
f"RPM limit ({rpm}) for key {key[:6]}... reached. Waiting {wait_time:.2f}s."
)
time.sleep(wait_time)
self.key_usage[key] = (0, time.time())
return False
return True
def _select_api_key(self) -> Optional[str]:
# This logic is identical to the one in LLM_API_Translator
api_keys = self.multiple_keys_list
single_key = self.api_key
if not api_keys and not single_key:
self.logger.error("No API keys provided.")
return None
if not api_keys:
if self._respect_key_limit(single_key):
now = time.time()
count, start_time = self.key_usage.get(single_key, (0, now))
self.key_usage[single_key] = (count + 1, start_time)
return single_key
return None
start_index = self.current_key_index
for i in range(len(api_keys)):
index = (start_index + i) % len(api_keys)
key = api_keys[index]
if self._respect_key_limit(key):
now = time.time()
count, start_time = self.key_usage.get(key, (0, now))
self.key_usage[key] = (count + 1, start_time)
self.current_key_index = (index + 1) % len(api_keys)
return key
self.logger.error("All API keys are rate-limited.")
return None
def ocr(self, img_base64: str, prompt_override: str = None) -> str:
api_key_to_use = self._select_api_key()
if not api_key_to_use:
return "[ERROR: No available API key]"
# Re-initialize client if key is different from the last one used
if not self.client or self.client.api_key != api_key_to_use:
self._initialize_client(api_key_to_use)
self._respect_delay()
try:
lang_name = self.language
prompt_text = (prompt_override or self.prompt).format(language=lang_name)
image_content_part = {
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_base64}"},
}
if self.provider in ["OpenAI", "Google", "OpenRouter"]:
detail_setting = self.detail_level
if detail_setting in ["low", "high"]:
image_content_part["image_url"]["detail"] = detail_setting
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
image_content_part,
],
}
]
if self.system_prompt:
messages.insert(0, {"role": "system", "content": self.system_prompt})
model_name = self.override_model or self.model
if ": " in model_name:
model_name = model_name.split(": ", 1)[1]
self.logger.debug(f"OCR request with model: {model_name}")
response = self.client.chat.completions.create(
model=model_name,
messages=messages,
max_tokens=self.max_response_tokens,
)
if response.choices and response.choices[0].message.content:
full_text = (
response.choices[0].message.content.replace("\n", " ").strip()
)
self.logger.debug(f"OCR result: {full_text}")
return full_text
else:
self.logger.warning("No text found in OCR response.")
return ""
except Exception as e:
self.logger.error(f"OCR error: {e}")
return f"[ERROR: {type(e).__name__}]"
def _ocr_blk_list(
self, img: np.ndarray, blk_list: List[TextBlock], *args, **kwargs
):
im_h, im_w = img.shape[:2]
for blk in blk_list:
x1, y1, x2, y2 = blk.xyxy
if 0 <= x1 < x2 <= im_w and 0 <= y1 < y2 <= im_h:
cropped_img = img[y1:y2, x1:x2]
_, buffer = cv2.imencode(".jpg", cropped_img)
img_base64 = base64.b64encode(buffer).decode("utf-8")
blk.text = self.ocr(img_base64, prompt_override=kwargs.get("prompt"))
else:
blk.text = ""
def ocr_img(self, img: np.ndarray, prompt: str = "") -> str:
_, buffer = cv2.imencode(".jpg", img)
img_base64 = base64.b64encode(buffer).decode("utf-8")
return self.ocr(img_base64, prompt_override=prompt)
def updateParam(self, param_key: str, param_content):
super().updateParam(param_key, param_content)
if param_key in ["api_key", "multiple_keys", "endpoint", "proxy", "provider"]:
self.client = None # Force re-initialization on next call
if param_key in ["requests_per_minute", "delay"]:
self.request_count_minute = 0
self.minute_start_time = time.time()
self.last_request_time = 0
|