plan291037 commited on
Commit
c437ebb
·
verified ·
1 Parent(s): 8f036c1

Delete app/lens_text_core.py

Browse files
Files changed (1) hide show
  1. app/lens_text_core.py +0 -387
app/lens_text_core.py DELETED
@@ -1,387 +0,0 @@
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)