plan291037 commited on
Commit
56af988
·
verified ·
1 Parent(s): 33a9181

Upload 6 files

Browse files
Files changed (6) hide show
  1. Dockerfile +16 -0
  2. app/__init__.py +1 -0
  3. app/lens_images_core.py +303 -0
  4. app/lens_text_core.py +387 -0
  5. app/main.py +243 -0
  6. requirements.txt +6 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ RUN apt-get update && \
4
+ apt-get install -y --no-install-recommends \
5
+ chromium chromium-driver fonts-liberation libgbm1 libnss3 libgconf-2-4 && \
6
+ rm -rf /var/lib/apt/lists/*
7
+
8
+ ENV CHROME_BINARY=/usr/bin/chromium
9
+ ENV CHROME_EXTRA_ARGS="--no-sandbox --disable-dev-shm-usage --disable-gpu --window-size=1920,1080 --headless=new"
10
+
11
+ COPY requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ COPY . /app
15
+ WORKDIR /app
16
+ CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8080", "app.main:app"]
app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # ensures app is a proper package for PyInstaller
app/lens_images_core.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, json, time, hashlib, httpx, base64, re, asyncio, threading, shutil, logging
3
+ from typing import Dict, Any
4
+ from urllib.parse import urlparse
5
+
6
+ from selenium import webdriver
7
+ from selenium.webdriver.chrome.options import Options as ChromeOptions
8
+ from selenium.webdriver.chrome.service import Service as ChromeService
9
+
10
+ LOGGER = logging.getLogger("lens_images_core")
11
+ if not LOGGER.handlers:
12
+ logging.basicConfig(
13
+ level=logging.INFO,
14
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
15
+ )
16
+
17
+ COOKIE_JSON_URL = os.getenv("COOKIE_JSON_URL", "")
18
+ UA = "Mozilla/5.0 (Lens OCR Images)"
19
+
20
+ _COMMON_CHROME_PATHS = [
21
+ # Linux
22
+ "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser",
23
+ "/snap/bin/chromium",
24
+ "/opt/google/chrome/google-chrome",
25
+ # macOS
26
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
27
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
28
+ # Windows
29
+ r"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
30
+ r"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
31
+ ]
32
+
33
+ def _find_chrome_binary() -> str | None:
34
+ env = os.getenv("CHROME_BINARY")
35
+ if env and shutil.which(env):
36
+ return env
37
+ for p in _COMMON_CHROME_PATHS:
38
+ if os.path.isfile(p) and os.access(p, os.X_OK):
39
+ return p
40
+ try:
41
+ import subprocess, shlex
42
+ out = subprocess.check_output(shlex.split("which google-chrome"), stderr=subprocess.DEVNULL).decode().strip()
43
+ if out:
44
+ return out
45
+ except Exception:
46
+ pass
47
+ return None
48
+
49
+ def _build_chrome() -> webdriver.Chrome:
50
+ bin_loc = _find_chrome_binary() or "/usr/bin/chromium"
51
+ drv_path = os.getenv("CHROMEDRIVER", "/usr/bin/chromedriver")
52
+ opts = ChromeOptions()
53
+ opts.binary_location = bin_loc
54
+
55
+ extra = os.getenv(
56
+ "CHROME_EXTRA_ARGS",
57
+ "--disable-gpu --no-sandbox --disable-dev-shm-usage --window-size=1920,1080 --headless=new",
58
+ ).split()
59
+ for a in extra:
60
+ if a:
61
+ opts.add_argument(a)
62
+ service = ChromeService(executable_path=drv_path)
63
+ return webdriver.Chrome(service=service, options=opts)
64
+
65
+ _cached_cookie_obj: Dict[str, Any] | None = None
66
+ _cached_cookie_fetched_at: float = 0.0
67
+ _CACHE_TTL = 300
68
+ _BROWSER_TTL = 900
69
+ _cookie_lock = threading.Lock()
70
+
71
+ _IDLE_TIMEOUT = int(os.getenv("CHROME_IDLE_SECONDS", "60"))
72
+ _driver_lock = threading.Lock()
73
+ _global_driver = None
74
+ _driver_last_use = 0.0
75
+
76
+ def _ensure_cookie_driver():
77
+ global _global_driver, _driver_last_use
78
+ with _driver_lock:
79
+ if _global_driver is None:
80
+ LOGGER.info("▶️ starting headless Chrome for cookies")
81
+ _global_driver = _build_chrome()
82
+ _driver_last_use = time.time()
83
+ return _global_driver
84
+
85
+ def _quit_cookie_driver():
86
+ global _global_driver
87
+ try:
88
+ if _global_driver:
89
+ _global_driver.quit()
90
+ except Exception:
91
+ pass
92
+ finally:
93
+ _global_driver = None
94
+
95
+ def _driver_reaper_loop():
96
+ global _driver_last_use
97
+ while True:
98
+ try:
99
+ time.sleep(1)
100
+ with _driver_lock:
101
+ if _global_driver and (time.time() - _driver_last_use) > _IDLE_TIMEOUT:
102
+ LOGGER.info("♻️ quitting idle cookie driver")
103
+ _quit_cookie_driver()
104
+ except Exception:
105
+ pass
106
+
107
+ _reaper_started = False
108
+ def _ensure_reaper_started():
109
+ global _reaper_started
110
+ if _reaper_started:
111
+ return
112
+ try:
113
+ threading.Thread(target=_driver_reaper_loop, daemon=True).start()
114
+ _reaper_started = True
115
+ LOGGER.debug("cookie driver reaper started")
116
+ except Exception as e:
117
+ LOGGER.warning("could not start cookie driver reaper: %s", e)
118
+
119
+ def _grab_cookies_with_browser() -> Dict[str, Any]:
120
+ drv = _ensure_cookie_driver()
121
+ with _driver_lock:
122
+ drv.get("https://lens.google.com/")
123
+ jar = {}
124
+ for c in drv.get_cookies():
125
+ dom = c.get("domain") or ""
126
+ if dom.endswith(".google.com") or dom.endswith("google.com"):
127
+ jar[c["name"]] = c["value"]
128
+ return {"cookies": jar, "_source": "browser"}
129
+
130
+ async def _cookie_header() -> str:
131
+ global _cached_cookie_obj, _cached_cookie_fetched_at
132
+ now = time.time()
133
+
134
+ _ensure_reaper_started()
135
+
136
+ def extract_obj(obj):
137
+ if isinstance(obj, dict):
138
+ return obj.get("cookies", obj)
139
+ return obj
140
+
141
+ with _cookie_lock:
142
+ if _cached_cookie_obj:
143
+ ttl = _BROWSER_TTL if _cached_cookie_obj.get("_source") == "browser" else _CACHE_TTL
144
+ if (now - _cached_cookie_fetched_at) < ttl:
145
+ return "; ".join(f"{k}={v}" for k, v in extract_obj(_cached_cookie_obj).items())
146
+
147
+ if COOKIE_JSON_URL:
148
+ try:
149
+ async with httpx.AsyncClient(timeout=5) as cli:
150
+ resp = await cli.get(COOKIE_JSON_URL)
151
+ resp.raise_for_status()
152
+ data = resp.json()
153
+ with _cookie_lock:
154
+ data["_source"] = "remote"
155
+ _cached_cookie_obj, _cached_cookie_fetched_at = data, now
156
+ return "; ".join(f"{k}={v}" for k, v in extract_obj(data).items())
157
+ except Exception as e:
158
+ LOGGER.warning("COOKIE_JSON_URL fetch failed: %s – falling back to headless chrome", e)
159
+
160
+ loop = asyncio.get_running_loop()
161
+ data: Dict[str, Any] = await loop.run_in_executor(None, _grab_cookies_with_browser)
162
+ with _cookie_lock:
163
+ _cached_cookie_obj, _cached_cookie_fetched_at = data, now
164
+ return "; ".join(f"{k}={v}" for k, v in extract_obj(data).items())
165
+
166
+ def _sap_header(cookie_header: str) -> dict:
167
+ origin = "https://lens.google.com"
168
+ sid = None
169
+ for c in cookie_header.split("; "):
170
+ if c.startswith("__Secure-3PAPISID=") or c.startswith("SAPISID="):
171
+ sid = c.split("=", 1)[1]
172
+ break
173
+ if not sid:
174
+ return {}
175
+ ts = int(time.time())
176
+ raw = f"{ts} {sid} {origin}"
177
+ sig = hashlib.sha1(raw.encode()).hexdigest()
178
+ return {
179
+ "X-Origin": origin,
180
+ "X-Goog-AuthUser": "0",
181
+ "Authorization": f"SAPISIDHASH {ts}_{sig}",
182
+ }
183
+
184
+ def _json_url(loc: str, tl: str) -> str:
185
+ from urllib.parse import urlparse, parse_qs
186
+
187
+ q = parse_qs(urlparse(loc).query)
188
+ return (
189
+ "https://lens.google.com/translatedimage?"
190
+ f"vsrid={q.get('vsrid', [None])[0]}&gsessionid={q.get('gsessionid', [None])[0]}"
191
+ f"&sl=auto&tl={tl}&sf=1.07&ib=1"
192
+ )
193
+
194
+ async def translate_lens(image_url: str, lang: str = "en") -> dict:
195
+ start_ts = time.time()
196
+ debug: Dict[str, Any] = {"steps": [], "errors": []}
197
+
198
+ ck = await _cookie_header()
199
+ hdr = {
200
+ "User-Agent": UA,
201
+ "Cookie": ck,
202
+ "Referer": "https://lens.google.com/",
203
+ **_sap_header(ck),
204
+ }
205
+
206
+ async with httpx.AsyncClient() as cli:
207
+ try:
208
+ o = urlparse(image_url)
209
+ referer = f"{o.scheme}://{o.netloc}/" if o.scheme and o.netloc else None
210
+ hdr_img = {"User-Agent": UA}
211
+ if referer:
212
+ hdr_img["Referer"] = referer
213
+ img_resp = await cli.get(image_url, headers=hdr_img, timeout=10)
214
+ img_resp.raise_for_status()
215
+ debug["steps"].append(f"fetched original image {image_url} status={img_resp.status_code}")
216
+ except httpx.HTTPStatusError as he:
217
+ code = he.response.status_code if he.response is not None else "NA"
218
+ debug["errors"].append(f"fetch image HTTP {code} {image_url}")
219
+ raise RuntimeError(f"fetch image HTTP {code}")
220
+ except httpx.TimeoutException:
221
+ debug["errors"].append(f"fetch image TIMEOUT {image_url}")
222
+ raise RuntimeError("fetch image TIMEOUT")
223
+ except Exception as e:
224
+ debug["errors"].append(f"fetch image ERROR {type(e).__name__} {image_url}")
225
+ raise RuntimeError(f"fetch image ERROR {type(e).__name__}")
226
+
227
+ files = {
228
+ "encoded_image": ("file.jpg", img_resp.content, "image/jpeg"),
229
+ "sbisrc": (None, "browser"),
230
+ "rt": (None, "j"),
231
+ }
232
+
233
+ up = await cli.post(
234
+ "https://lens.google.com/v3/upload",
235
+ files=files,
236
+ headers=hdr,
237
+ follow_redirects=False,
238
+ timeout=10,
239
+ )
240
+ debug["steps"].append(f"upload response status={up.status_code}")
241
+ if up.status_code not in (302, 303):
242
+ msg = f"Lens upload failed {up.status_code}"
243
+ debug["errors"].append(msg)
244
+ raise RuntimeError(msg)
245
+
246
+ loc = up.headers.get("location", "")
247
+ debug["steps"].append(f"got redirect location: {loc}")
248
+
249
+ json_url = _json_url(loc, lang)
250
+ debug["steps"].append(f"constructed json_url: {json_url}")
251
+
252
+ js = await cli.get(json_url, headers=hdr, timeout=5)
253
+ raw_body = js.text
254
+ debug["steps"].append("fetched translation JSON")
255
+
256
+ body = raw_body.lstrip(")]}'")
257
+ try:
258
+ info = json.loads(body)
259
+ except Exception as e:
260
+ debug["errors"].append(f"JSON parse failure: {e}; raw_body snippet: {body[:200]}")
261
+ raise
262
+
263
+ data_url = info.get("imageUrl", "")
264
+ extracted_data_url = ""
265
+ if data_url:
266
+ if data_url.startswith("data:image/"):
267
+ extracted_data_url = data_url
268
+ debug["steps"].append("imageUrl already data URL")
269
+ else:
270
+ try:
271
+ html = base64.b64decode(data_url).decode("utf-8", errors="ignore")
272
+ m = re.search(r"data:image/[a-zA-Z]+;base64,[A-Za-z0-9+/=]+", html)
273
+ if m:
274
+ extracted_data_url = m.group(0)
275
+ debug["steps"].append("extracted embedded data:image from base64 HTML")
276
+ else:
277
+ debug["steps"].append("no embedded data:image found inside decoded HTML")
278
+ except Exception as e:
279
+ debug["errors"].append(f"error decoding imageUrl: {e}")
280
+
281
+ if not extracted_data_url and (data_url.startswith("http://") or data_url.startswith("https://")):
282
+ try:
283
+ fallback_img = await cli.get(data_url, headers={"User-Agent": UA}, timeout=5)
284
+ fallback_img.raise_for_status()
285
+ b64 = base64.b64encode(fallback_img.content).decode("utf-8")
286
+ extracted_data_url = f"data:image/jpeg;base64,{b64}"
287
+ debug["steps"].append("fetched fallback image URL and encoded to data URL")
288
+ except Exception as e:
289
+ debug["errors"].append(f"fallback fetch of imageUrl failed: {e}")
290
+
291
+ translated_text = info.get("translatedTextFull", "") or info.get("translatedText", "")
292
+
293
+ duration = time.time() - start_ts
294
+ debug["duration_sec"] = duration
295
+
296
+ return {
297
+ "image": extracted_data_url,
298
+ "text": translated_text,
299
+ "loc": loc,
300
+ "json_url": json_url,
301
+ "raw_info": info,
302
+ "debug": debug,
303
+ }
app/lens_text_core.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, time, asyncio, base64, re, threading, hashlib, logging, shutil
3
+ from io import BytesIO
4
+ from typing import Any, Dict, List, Union
5
+ from urllib.parse import urlparse
6
+
7
+ import httpx
8
+ from PIL import Image
9
+
10
+ from selenium import webdriver
11
+ from selenium.webdriver.chrome.options import Options as ChromeOptions
12
+ from selenium.webdriver.chrome.service import Service as ChromeService
13
+ from selenium.webdriver.common.by import By
14
+ from selenium.webdriver.support.ui import WebDriverWait
15
+ from selenium.webdriver.support import expected_conditions as EC
16
+
17
+ CHROME_BINARY_PATH = os.getenv("CHROME_BINARY_PATH", "").strip()
18
+
19
+ LOGGER = logging.getLogger("lens_text_core")
20
+ if not LOGGER.handlers:
21
+ logging.basicConfig(
22
+ level=logging.INFO,
23
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
24
+ )
25
+
26
+ COOKIE_JSON_URL = os.getenv("COOKIE_JSON_URL", "")
27
+ UA = "Mozilla/5.0 (Lens Text OCR)"
28
+
29
+ CHROME_EXTRA_ARGS = os.getenv(
30
+ "CHROME_EXTRA_ARGS",
31
+ "--disable-gpu --no-sandbox --disable-dev-shm-usage "
32
+ "--window-size=1920,1080 --headless=new",
33
+ ).split()
34
+
35
+ _CACHE_TTL = 300
36
+ _IDLE_TIMEOUT = int(os.getenv("CHROME_IDLE_SECONDS", "60"))
37
+ _BROWSER_TTL = 900
38
+
39
+ _COMMON_CHROME_PATHS = [
40
+ # Linux
41
+ "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser",
42
+ "/snap/bin/chromium",
43
+ "/opt/google/chrome/google-chrome",
44
+ # macOS
45
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
46
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
47
+ # Windows
48
+ r"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
49
+ r"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
50
+ ]
51
+
52
+ def _find_chrome_binary() -> str:
53
+ if (env := os.getenv("CHROME_BINARY")):
54
+ return env
55
+
56
+ for cmd in ("google-chrome", "chromium-browser", "chromium", "chrome"):
57
+ path = shutil.which(cmd)
58
+ if path:
59
+ return path
60
+
61
+ for path in _COMMON_CHROME_PATHS:
62
+ if os.path.exists(path):
63
+ return path
64
+
65
+ raise RuntimeError(
66
+ "Chrome binary not found; set CHROME_BINARY env var or install Chrome/Chromium"
67
+ )
68
+
69
+ def _build_chrome(cookie_dict: Dict[str, str] | None = None):
70
+ bin_loc = _find_chrome_binary()
71
+ drv_path = os.getenv("CHROMEDRIVER", "/usr/bin/chromedriver")
72
+ opts = ChromeOptions()
73
+ opts.binary_location = bin_loc
74
+ for flag in CHROME_EXTRA_ARGS:
75
+ try:
76
+ opts.add_argument(flag)
77
+ except Exception:
78
+ pass
79
+ service = ChromeService(executable_path=drv_path)
80
+ drv = webdriver.Chrome(service=service, options=opts)
81
+
82
+ drv.execute_cdp_cmd("Network.enable", {})
83
+ if cookie_dict:
84
+ for name, val in cookie_dict.items():
85
+ try:
86
+ drv.execute_cdp_cmd("Network.setCookie", {
87
+ "name": name, "value": val,
88
+ "domain": ".google.com", "path": "/", "secure": True
89
+ })
90
+ except Exception:
91
+ pass
92
+ return drv
93
+
94
+ _cached_cookie, _cached_cookie_ts, _cookie_lock = None, 0.0, threading.Lock()
95
+ _global_driver, _driver_last_use, _driver_lock = None, 0.0, threading.Lock()
96
+
97
+ def _grab_cookies_with_browser() -> Dict[str, Any]:
98
+ drv = _build_chrome()
99
+ try:
100
+ drv.get("https://lens.google.com/")
101
+ jar = {
102
+ c["name"]: c["value"]
103
+ for c in drv.get_cookies()
104
+ if c.get("domain","").endswith(".google.com") or c.get("domain","").endswith("google.com")
105
+ }
106
+ return {"cookies": jar, "_source": "browser"}
107
+ finally:
108
+ try: drv.quit()
109
+ except Exception: pass
110
+
111
+ async def _cookie_header() -> str:
112
+ global _cached_cookie, _cached_cookie_ts
113
+ now = time.time()
114
+
115
+ with _cookie_lock:
116
+ if _cached_cookie:
117
+ ttl = _BROWSER_TTL if _cached_cookie.get("_source") == "browser" else _CACHE_TTL
118
+ if (now - _cached_cookie_ts) < ttl:
119
+ obj = _cached_cookie.get("cookies", _cached_cookie)
120
+ return "; ".join(f"{k}={v}" for k, v in obj.items())
121
+
122
+ if COOKIE_JSON_URL:
123
+ try:
124
+ async with httpx.AsyncClient(timeout=4) as cli:
125
+ resp = await cli.get(COOKIE_JSON_URL)
126
+ resp.raise_for_status()
127
+ data = resp.json()
128
+ with _cookie_lock:
129
+ data["_source"] = "remote"
130
+ _cached_cookie, _cached_cookie_ts = data, now
131
+ obj = data.get("cookies", data)
132
+ return "; ".join(f"{k}={v}" for k, v in obj.items())
133
+ except Exception as e:
134
+ LOGGER.warning("fetch COOKIE_JSON_URL failed: %s – fallback to browser", e)
135
+
136
+ loop = asyncio.get_running_loop()
137
+ data = await loop.run_in_executor(None, _grab_cookies_with_browser)
138
+
139
+ with _cookie_lock:
140
+ _cached_cookie, _cached_cookie_ts = data, now
141
+
142
+ obj = data.get("cookies", data)
143
+ return "; ".join(f"{k}={v}" for k, v in obj.items())
144
+
145
+ def _sap_header(cookie_hdr: str) -> Dict[str, str]:
146
+ origin = "https://lens.google.com"
147
+ sid = None
148
+ for part in cookie_hdr.split("; "):
149
+ if part.startswith("__Secure-3PAPISID=") or part.startswith("SAPISID="):
150
+ sid = part.split("=", 1)[1]
151
+ break
152
+ if not sid:
153
+ return {}
154
+ ts = int(time.time())
155
+ sig = hashlib.sha1(f"{ts} {sid} {origin}".encode()).hexdigest()
156
+ return {
157
+ "X-Origin": origin,
158
+ "X-Goog-AuthUser": "0",
159
+ "Authorization": f"SAPISIDHASH {ts}_{sig}",
160
+ }
161
+
162
+ def _is_alive(drv) -> bool:
163
+ try:
164
+ _ = drv.title
165
+ return True
166
+ except Exception:
167
+ return False
168
+
169
+ def _ensure_driver(cookie_dict: Dict[str, str]):
170
+ global _global_driver, _driver_last_use
171
+ with _driver_lock:
172
+ if _global_driver is None or not _is_alive(_global_driver):
173
+ try:
174
+ if _global_driver:
175
+ _global_driver.quit()
176
+ except Exception:
177
+ pass
178
+ _global_driver = _build_chrome(cookie_dict)
179
+ _driver_last_use = time.time()
180
+ return _global_driver
181
+
182
+ def _driver_reaper():
183
+ global _global_driver
184
+ while True:
185
+ time.sleep(1)
186
+ if _global_driver and (time.time() - _driver_last_use) > _IDLE_TIMEOUT:
187
+ LOGGER.info("♻️ quitting idle driver")
188
+ try: _global_driver.quit()
189
+ except Exception: pass
190
+ _global_driver = None
191
+
192
+ _reaper_started = False
193
+ def _ensure_reaper_started():
194
+ global _reaper_started
195
+ if _reaper_started:
196
+ return
197
+ try:
198
+ threading.Thread(target=_driver_reaper, daemon=True).start()
199
+ _reaper_started = True
200
+ LOGGER.debug("text driver reaper started")
201
+ except Exception as e:
202
+ LOGGER.warning("could not start text driver reaper: %s", e)
203
+
204
+ def _parse_calc_value(calc: str, dim: float) -> float:
205
+ m = re.search(r"calc\(([\d.]+)%\s*([+-])\s*([\d.]+)px\)", calc)
206
+ if not m: return 0.0
207
+ pct, op, off = float(m[1]), m[2], float(m[3])
208
+ base = dim * pct / 100.0
209
+ return base - off if op == "-" else base + off
210
+
211
+ def _extract_boxes(drv, w: int, h: int) -> List[Dict[str, Any]]:
212
+ WebDriverWait(drv, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.lv6PAb")))
213
+ nodes = drv.find_elements(By.XPATH, "//div[contains(@class,'lv6PAb') and @aria-label]")
214
+
215
+ out: List[Dict[str,Any]] = []
216
+ for n in nodes:
217
+ if not (n.get_attribute("data-line-index") or "").strip():
218
+ continue
219
+
220
+ text = (n.get_attribute("aria-label") or "").strip()
221
+ style = n.get_attribute("style") or ""
222
+ if not text or "calc(" not in style:
223
+ continue
224
+
225
+ kv = {k.strip(): v.strip()
226
+ for k,v in (p.split(":",1) for p in style.split(";") if ":" in p)}
227
+
228
+ top, left = _parse_calc_value(kv.get("top",""), h), _parse_calc_value(kv.get("left",""), w)
229
+ wid, hei = _parse_calc_value(kv.get("width",""), w), _parse_calc_value(kv.get("height",""),h)
230
+ rot_m = re.search(r"rotate\(([-\d.]+)deg\)", style); rot = float(rot_m[1]) if rot_m else 0.0
231
+
232
+ verts = [
233
+ {"x": int(left), "y": int(top)},
234
+ {"x": int(left+wid), "y": int(top)},
235
+ {"x": int(left+wid), "y": int(top+hei)},
236
+ {"x": int(left), "y": int(top+hei)},
237
+ ]
238
+ abs_style = f"top: {int(top)}px; left: {int(left)}px; width: {int(wid)}px; height: {int(hei)}px; transform: rotate({rot}deg);"
239
+
240
+ out.append({
241
+ "description": text,
242
+ "boundingPoly": {"vertices": verts},
243
+ "rotate": rot,
244
+ "style": abs_style,
245
+
246
+ "raw_style": style,
247
+ "top_str": kv.get("top",""),
248
+ "left_str": kv.get("left",""),
249
+ "width_str": kv.get("width",""),
250
+ "height_str": kv.get("height",""),
251
+ })
252
+ return out
253
+
254
+ def _merge_by_center_line(anns: List[Dict[str,Any]], m_x: int=10, m_y: int=15) -> List[Dict[str,Any]]:
255
+ for a in anns:
256
+ v = a["boundingPoly"]["vertices"]
257
+ xs, ys = [p["x"] for p in v], [p["y"] for p in v]
258
+ a["_l"], a["_r"], a["_t"], a["_b"] = min(xs), max(xs), min(ys), max(ys)
259
+ a["_cx"], a["_cy"] = (a["_l"]+a["_r"])/2, (a["_t"]+a["_b"])/2
260
+
261
+ parent = list(range(len(anns)))
262
+ def find(i):
263
+ while parent[i]!=i:
264
+ parent[i]=parent[parent[i]]
265
+ i=parent[i]
266
+ return i
267
+ def union(i,j):
268
+ ri,rj = find(i),find(j)
269
+ if ri!=rj: parent[rj]=ri
270
+
271
+ for i in range(len(anns)):
272
+ for j in range(i+1,len(anns)):
273
+ ai, aj = anns[i], anns[j]
274
+ if (abs(ai["_cx"]-aj["_cx"]) < m_x and
275
+ ai["_t"]-m_y < aj["_b"] and ai["_b"]+m_y > aj["_t"]):
276
+ union(i,j)
277
+
278
+ groups: Dict[int,List[Dict[str,Any]]] = {}
279
+ for idx,a in enumerate(anns):
280
+ groups.setdefault(find(idx), []).append(a)
281
+
282
+ merged: List[Dict[str,Any]] = []
283
+ for g in groups.values():
284
+ if len(g)==1:
285
+ a = g[0]
286
+ merged.append({
287
+ "description": a["description"],
288
+ "boundingPoly": a["boundingPoly"],
289
+ "rotate": a["rotate"],
290
+ "style": a["style"],
291
+ })
292
+ else:
293
+ txt = "\n".join(aa["description"] for aa in g)
294
+ l,r = min(aa["_l"] for aa in g), max(aa["_r"] for aa in g)
295
+ t,b = min(aa["_t"] for aa in g), max(aa["_b"] for aa in g)
296
+ merged.append({
297
+ "description": txt,
298
+ "boundingPoly": {"vertices":[
299
+ {"x":l,"y":t}, {"x":r,"y":t}, {"x":r,"y":b}, {"x":l,"y":b}]},
300
+ "rotate": 0.0,
301
+ "style": f"top: {t}px; left: {l}px; width: {r-l}px; height: {b-t}px; transform: rotate(0deg);",
302
+ })
303
+ return merged
304
+
305
+ async def translate_lens_text(src: Union[str, bytes, BytesIO]) -> Dict[str,Any]:
306
+ _ensure_reaper_started()
307
+ if isinstance(src, (bytes,bytearray)): img_bytes = bytes(src)
308
+ elif isinstance(src, BytesIO): img_bytes = src.getvalue()
309
+ elif isinstance(src, str):
310
+ if src.startswith("data:"): img_bytes = base64.b64decode(src.split(",",1)[1])
311
+ else:
312
+ async with httpx.AsyncClient() as cli:
313
+ o = urlparse(src)
314
+ referer = f"{o.scheme}://{o.netloc}/" if o.scheme and o.netloc else None
315
+ hdr_img = {"User-Agent": UA}
316
+ if referer: hdr_img["Referer"] = referer
317
+ try:
318
+ r = await cli.get(src, headers=hdr_img, timeout=10)
319
+ r.raise_for_status()
320
+ img_bytes = r.content
321
+ except httpx.HTTPStatusError as he:
322
+ code = he.response.status_code if he.response is not None else "NA"
323
+ raise RuntimeError(f"fetch image HTTP {code}")
324
+ except httpx.TimeoutException:
325
+ raise RuntimeError("fetch image TIMEOUT")
326
+ except Exception as e:
327
+ raise RuntimeError(f"fetch image ERROR {type(e).__name__}")
328
+ else: raise TypeError("unsupported src type")
329
+
330
+ from io import BytesIO as _B
331
+ with Image.open(_B(img_bytes)) as im:
332
+ w, h = im.size
333
+
334
+ ck = await _cookie_header()
335
+ hdr = {"User-Agent": UA, "Cookie": ck, "Referer":"https://lens.google.com/", **_sap_header(ck)}
336
+ async with httpx.AsyncClient(follow_redirects=False) as cli:
337
+ up = await cli.post("https://lens.google.com/v3/upload",
338
+ files={ "encoded_image": ("file.jpg", img_bytes, "image/jpeg"),
339
+ "sbisrc":(None,"browser"), "rt":(None,"j") },
340
+ headers=hdr, timeout=10)
341
+ if up.status_code not in (302,303):
342
+ raise RuntimeError(f"Lens upload failed: {up.status_code}")
343
+ loc = up.headers.get("location") or ""
344
+ if not loc: raise RuntimeError("no redirect location")
345
+
346
+ cookie_dict = {k: v for k, v in (p.split("=", 1) for p in ck.split("; ") if "=" in p)}
347
+
348
+ loop = asyncio.get_running_loop()
349
+ drv = await loop.run_in_executor(None, lambda: _ensure_driver(cookie_dict))
350
+
351
+ def _blocking() -> List[Dict[str, Any]]:
352
+ nonlocal drv
353
+ with _driver_lock:
354
+ try:
355
+ try:
356
+ drv.get(loc)
357
+ except:
358
+ try:
359
+ drv.quit()
360
+ except Exception:
361
+ pass
362
+ drv = _ensure_driver(cookie_dict)
363
+ drv.get(loc)
364
+ return _extract_boxes(drv, w, h)
365
+ finally:
366
+ pass
367
+
368
+ raw = await loop.run_in_executor(None, _blocking)
369
+
370
+ merged = _merge_by_center_line(raw)
371
+ fulltxt = " ".join(a["description"] for a in raw).strip()
372
+
373
+ return {
374
+ "textAnnotations": merged,
375
+ "rawTextAnnotations": raw,
376
+ "fullTextAnnotation": {"text": fulltxt},
377
+ "loc": loc,
378
+ }
379
+
380
+ async def prewarm_driver():
381
+ try:
382
+ cookie_hdr = await _cookie_header()
383
+ cookie_dict = {k: v for k, v in (p.split("=", 1) for p in cookie_hdr.split("; ") if "=" in p)}
384
+ _ = cookie_dict
385
+ LOGGER.info("prewarm_driver: cookies ready")
386
+ except Exception as e:
387
+ LOGGER.warning("prewarm_driver failed: %s", e)
app/main.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, uuid, asyncio, logging
2
+ from datetime import datetime, timedelta
3
+ from typing import Dict, Optional, List, Any
4
+
5
+ from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+ from pydantic import BaseModel, HttpUrl, root_validator, ValidationError
8
+ from fastapi.encoders import jsonable_encoder
9
+
10
+ from app.lens_images_core import translate_lens
11
+ from app.lens_text_core import translate_lens_text
12
+
13
+ PORT = int(os.getenv("PORT", 8080))
14
+ MAX_WORKERS = int(os.getenv("MAX_WORKERS", 8))
15
+ MAX_WORKERS_IMAGES = int(os.getenv("MAX_WORKERS_IMAGES", MAX_WORKERS))
16
+ MAX_WORKERS_TEXT = int(os.getenv("MAX_WORKERS_TEXT", 3))
17
+ RESULTS_TTL = int(os.getenv("RESULTS_TTL_SECONDS", 300))
18
+ MAX_B64_IMG_LEN = int(os.getenv("MAX_BASE64_IMAGE_LENGTH", 5_000_000))
19
+ JOB_DELAY_SEC = int(os.getenv("JOB_DELAY_SECONDS", 0.1))
20
+
21
+ logging.basicConfig(
22
+ level=logging.INFO,
23
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
24
+ )
25
+ log = logging.getLogger("ocr_ws")
26
+
27
+ ENABLE_BACKGROUND_WORKERS = os.getenv("ENABLE_BACKGROUND_WORKERS", "0").strip().lower() in ("1","true","yes","on")
28
+
29
+ workers_started: bool = False
30
+ _workers_lock = asyncio.Lock()
31
+
32
+ async def ensure_workers_started():
33
+ global workers_started
34
+ if workers_started:
35
+ return
36
+ async with _workers_lock:
37
+ if workers_started:
38
+ return
39
+ for _ in range(MAX_WORKERS_IMAGES):
40
+ asyncio.create_task(worker("lens_images", jobq_img))
41
+ for _ in range(MAX_WORKERS_TEXT):
42
+ asyncio.create_task(worker("lens_text", jobq_text))
43
+ workers_started = True
44
+ log.info("workers started on-demand")
45
+
46
+ app = FastAPI()
47
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"])
48
+
49
+ jobq_img: asyncio.Queue = asyncio.Queue()
50
+ jobq_text: asyncio.Queue = asyncio.Queue()
51
+
52
+ class Position(BaseModel):
53
+ top: float; left: float; width: float; height: float
54
+ viewport_width: int; viewport_height: int
55
+ scroll_x: float; scroll_y: float
56
+
57
+ class PipelineEvent(BaseModel):
58
+ stage: str; at: datetime; target: Optional[str] = None
59
+
60
+ class Context(BaseModel):
61
+ page_url: Optional[HttpUrl] = None
62
+ timestamp: Optional[datetime] = None
63
+
64
+ class Metadata(BaseModel):
65
+ image_id: str
66
+ original_image_url: Optional[HttpUrl] = None
67
+ position: Optional[Position] = None
68
+ pipeline: List[PipelineEvent] = []
69
+ ocr_image: Optional[str] = None
70
+ extra: Optional[Dict[str, Any]] = None
71
+
72
+ @root_validator(pre=True)
73
+ def _no_blob_urls(cls, v):
74
+ url = v.get("original_image_url")
75
+
76
+ if not url:
77
+ v["original_image_url"] = None
78
+ return v
79
+ if isinstance(url, str) and url.startswith("blob:"):
80
+ raise ValueError("original_image_url must be http(s)")
81
+ return v
82
+
83
+ class Job(BaseModel):
84
+ mode: str = "lens_images"
85
+ lang: str = "en"
86
+ type: str = "image"
87
+ src: Optional[HttpUrl] = None
88
+ menu: Optional[str] = None
89
+ context: Optional[Context] = None
90
+ metadata: Metadata
91
+
92
+ @root_validator(pre=True)
93
+ def _src_no_blob(cls, v):
94
+ s = v.get("src")
95
+ if not s:
96
+ v["src"] = None
97
+ return v
98
+ if isinstance(s, str) and s.startswith("blob:"):
99
+ raise ValueError("src must be http(s)")
100
+ return v
101
+
102
+ class WsMessage(BaseModel):
103
+ type: str
104
+ id: Optional[str] = None
105
+ payload: Optional[Job] = None
106
+
107
+ jobq: asyncio.Queue = asyncio.Queue()
108
+ pending_ws: Dict[str, WebSocket] = {}
109
+ results: Dict[str, dict] = {}
110
+
111
+ @app.api_route("/health", methods=["GET", "HEAD"])
112
+ async def health():
113
+ return {"ok": True, "timestamp": datetime.utcnow().isoformat()}
114
+
115
+ @app.post("/translate")
116
+ async def translate(job: Job):
117
+ await ensure_workers_started()
118
+ if job.mode not in ("lens_images", "lens_text"):
119
+ raise HTTPException(400, "unsupported mode")
120
+ jid = uuid.uuid4().hex
121
+ job.metadata.pipeline.append(PipelineEvent(stage="received_rest", at=datetime.utcnow()))
122
+
123
+ if job.mode == "lens_images":
124
+ await jobq_img.put((jid, job))
125
+ else:
126
+ await jobq_text.put((jid, job))
127
+ results[jid] = {"status": "queued", "_created_at": datetime.utcnow()}
128
+ return {"id": jid, "status": "queued"}
129
+
130
+
131
+ @app.get("/translate/{jid}")
132
+ async def poll(jid: str):
133
+ if jid not in results:
134
+ raise HTTPException(404)
135
+ payload = results[jid].copy(); payload.pop("_created_at", None)
136
+ return {"id": jid, **payload}
137
+
138
+ @app.websocket("/ws")
139
+ async def ws_endpoint(ws: WebSocket):
140
+ await ws.accept()
141
+ await ensure_workers_started()
142
+ try:
143
+ while True:
144
+ raw = await ws.receive_json()
145
+ try:
146
+ msg = WsMessage(**raw)
147
+ except ValidationError as ve:
148
+ await ws.send_json({"type": "error","detail": ve.errors()})
149
+ continue
150
+ match msg.type:
151
+ case "job":
152
+ jid = msg.id or uuid.uuid4().hex
153
+ pending_ws[jid] = ws
154
+ await ws.send_json(jsonable_encoder({"type": "ack", "id": jid}))
155
+
156
+ if msg.payload.mode == "lens_images":
157
+ await jobq_img.put((jid, msg.payload))
158
+ elif msg.payload.mode == "lens_text":
159
+ await jobq_text.put((jid, msg.payload))
160
+ else:
161
+ await ws.send_json({"type": "error","detail": "unsupported_mode"})
162
+ pending_ws.pop(jid, None)
163
+ continue
164
+ results[jid] = {"status": "queued", "_created_at": datetime.utcnow()}
165
+ case _:
166
+ await ws.send_json({"type": "error","detail": "unknown_type"})
167
+ except WebSocketDisconnect:
168
+ pass
169
+ finally:
170
+ for jid, sock in list(pending_ws.items()):
171
+ if sock is ws:
172
+ pending_ws.pop(jid, None)
173
+
174
+ async def worker(mode: str, q: asyncio.Queue):
175
+ while True:
176
+ jid, job = await q.get()
177
+ try:
178
+ job.metadata.pipeline.append(PipelineEvent(stage="worker_start", at=datetime.utcnow()))
179
+ if not job.src:
180
+ raise RuntimeError("src missing")
181
+
182
+ log.info("worker start %s mode=%s src=%s", jid, job.mode, job.src)
183
+ if mode == "lens_images":
184
+ res = await translate_lens(str(job.src), job.lang)
185
+ elif mode == "lens_text":
186
+ res = await translate_lens_text(str(job.src))
187
+ else:
188
+ raise RuntimeError(f"unsupported mode {mode}")
189
+
190
+ img_b64 = res.get("image")
191
+ if img_b64 and len(img_b64) > MAX_B64_IMG_LEN:
192
+ res.pop("image", None)
193
+ job.metadata.extra = job.metadata.extra or {}
194
+ job.metadata.extra.setdefault(job.mode, {})["dropped_ocr_image_due_to_size"] = True
195
+
196
+ job.metadata.pipeline.append(PipelineEvent(stage="translated", at=datetime.utcnow()))
197
+ payload = {**res, "metadata": job.metadata.dict()}
198
+ serial = jsonable_encoder({"type": "result", "id": jid, "result": payload})
199
+
200
+ ws = pending_ws.pop(jid, None)
201
+ if ws:
202
+ try:
203
+ await ws.send_json(serial)
204
+ log.info("sent WS result %s", jid)
205
+ except Exception:
206
+ pending_ws.pop(jid, None)
207
+
208
+ results[jid] = {"status": "done", "result": payload, "_created_at": datetime.utcnow()}
209
+ log.info("worker done %s mode=%s", jid, job.mode)
210
+ except Exception as e:
211
+ log.exception("worker error %s", jid, exc_info=e)
212
+ err_txt = (str(e) or e.__class__.__name__)
213
+ err_type = e.__class__.__name__
214
+ err = {"type": "error", "id": jid, "error": err_txt, "error_type": err_type}
215
+ ws = pending_ws.pop(jid, None)
216
+ if ws:
217
+ try: await ws.send_json(jsonable_encoder(err))
218
+ except Exception: pass
219
+ results[jid] = {"status": "error", "result": err_txt, "error_type": err_type, "_created_at": datetime.utcnow()}
220
+ finally:
221
+ q.task_done()
222
+ if JOB_DELAY_SEC > 0:
223
+ await asyncio.sleep(JOB_DELAY_SEC)
224
+
225
+ async def cleanup():
226
+ while True:
227
+ await asyncio.sleep(60)
228
+ cutoff = datetime.utcnow() - timedelta(seconds=RESULTS_TTL)
229
+ for jid in [k for k,v in results.items() if v.get("_created_at") < cutoff]:
230
+ results.pop(jid, None)
231
+
232
+ @app.on_event("startup")
233
+ async def startup():
234
+ if ENABLE_BACKGROUND_WORKERS:
235
+ for _ in range(MAX_WORKERS_IMAGES):
236
+ asyncio.create_task(worker("lens_images", jobq_img))
237
+ for _ in range(MAX_WORKERS_TEXT):
238
+ asyncio.create_task(worker("lens_text", jobq_text))
239
+ asyncio.create_task(cleanup())
240
+ log.info(
241
+ "startup OK – %d image workers, %d text workers, TTL=%ds (workers_enabled=%s)",
242
+ MAX_WORKERS_IMAGES, MAX_WORKERS_TEXT, RESULTS_TTL, ENABLE_BACKGROUND_WORKERS
243
+ )
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi==0.111.0
2
+ uvicorn[standard]==0.29.0
3
+ httpx==0.27.0
4
+ Pillow==10.4.0
5
+ selenium==4.20.0
6
+ pydantic==2.7.2