Detect Tesseract language support folder. This function is used to enable OCR via Tesseract even if the language support folder is not specified directly or in environment variable TESSDATA_PREFIX. * If is set we return it directly. * Otherwise we return `os.env
(tessdata=None)
| 22350 | |
| 22351 | |
| 22352 | def get_tessdata(tessdata=None): |
| 22353 | """Detect Tesseract language support folder. |
| 22354 | |
| 22355 | This function is used to enable OCR via Tesseract even if the language |
| 22356 | support folder is not specified directly or in environment variable |
| 22357 | TESSDATA_PREFIX. |
| 22358 | |
| 22359 | * If <tessdata> is set we return it directly. |
| 22360 | |
| 22361 | * Otherwise we return `os.environ['TESSDATA_PREFIX']` if set. |
| 22362 | |
| 22363 | * Otherwise we search for a Tesseract installation and return its language |
| 22364 | support folder. |
| 22365 | |
| 22366 | * Otherwise we raise an exception. |
| 22367 | """ |
| 22368 | if tessdata: |
| 22369 | return tessdata |
| 22370 | tessdata = os.getenv("TESSDATA_PREFIX") |
| 22371 | if tessdata: # use environment variable if set |
| 22372 | return tessdata |
| 22373 | |
| 22374 | # Try to locate the tesseract-ocr installation. |
| 22375 | |
| 22376 | import subprocess |
| 22377 | |
| 22378 | cp = subprocess.run('tesseract --list-langs', shell=1, capture_output=1, check=0, text=True) |
| 22379 | if cp.returncode == 0: |
| 22380 | m = re.search('List of available languages in "(.+)"', cp.stdout) |
| 22381 | if m: |
| 22382 | tessdata = m.group(1) |
| 22383 | return tessdata |
| 22384 | |
| 22385 | # Windows systems: |
| 22386 | if sys.platform == "win32": |
| 22387 | cp = subprocess.run("where tesseract", shell=1, capture_output=1, check=0, text=True) |
| 22388 | response = cp.stdout.strip() |
| 22389 | if cp.returncode or not response: |
| 22390 | raise RuntimeError("No tessdata specified and Tesseract is not installed") |
| 22391 | dirname = os.path.dirname(response) # path of tesseract.exe |
| 22392 | tessdata = os.path.join(dirname, "tessdata") # language support |
| 22393 | if os.path.exists(tessdata): # all ok? |
| 22394 | return tessdata |
| 22395 | else: # should not happen! |
| 22396 | raise RuntimeError("No tessdata specified and Tesseract installation has no {tessdata} folder") |
| 22397 | |
| 22398 | # Unix-like systems: |
| 22399 | attempts = list() |
| 22400 | for path in 'tesseract-ocr', 'tesseract': |
| 22401 | cp = subprocess.run(f'whereis {path}', shell=1, capture_output=1, check=0, text=True) |
| 22402 | if cp.returncode == 0: |
| 22403 | response = cp.stdout.strip().split() |
| 22404 | if len(response) == 2: |
| 22405 | # search tessdata in folder structure |
| 22406 | dirname = response[1] # contains tesseract-ocr installation folder |
| 22407 | pattern = f"{dirname}/*/tessdata" |
| 22408 | attempts.append(pattern) |
| 22409 | tessdatas = glob.glob(pattern) |
no test coverage detected
searching dependent graphs…