-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlauncher.py
More file actions
168 lines (145 loc) · 5.22 KB
/
launcher.py
File metadata and controls
168 lines (145 loc) · 5.22 KB
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
# launcher.py (robusto — chama ocrmypdf con varios fallbacks, engade vendors ao PATH,
# crea un TMP controlado para evitar problemas con antivirus/temp)
import os
import sys
from pathlib import Path
import runpy
import importlib
import traceback
try:
import sitecustomize # aplica axustes de Pillow (LOAD_TRUNCATED_IMAGES)
except Exception:
pass
try:
from importlib import metadata as importlib_metadata
except Exception:
importlib_metadata = None
try:
import pkg_resources
except Exception:
pkg_resources = None
def resource_path(*parts: str) -> Path:
return Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)).joinpath(*parts)
def add_vendor_dir_to_path(*parts):
p = resource_path(*parts)
if p.exists():
os.environ["PATH"] = str(p) + os.pathsep + os.environ.get("PATH", "")
def find_and_set_gs():
candidates = [
resource_path("vendors", "ghostscript", "bin", "gswin64c.exe"),
resource_path("vendors", "ghostscript", "gswin64c.exe"),
]
for p in candidates:
if p.exists():
os.environ["OCRMYPDF_GS"] = str(p)
break
def call_fn_flexible(fn, argv):
"""Tenta chamadas con nomes e formas diferentes. Retorna True se tivo éxito."""
# intenta con varios nomes/posicionais
attempts = [
lambda: fn(argv=argv),
lambda: fn(args=argv),
lambda: fn(argv),
lambda: fn(args),
lambda: fn(),
]
for attempt in attempts:
try:
attempt()
return True
except TypeError:
continue
# se non funcionou, devolvemos False
return False
def call_entrypoint_console_script(name: str, argv):
# procura entry-points console_scripts e tenta executalos
if importlib_metadata is not None:
try:
eps = importlib_metadata.entry_points()
if hasattr(eps, "select"):
found = eps.select(group="console_scripts", name=name)
else:
found = [e for e in eps.get("console_scripts", []) if e.name == name]
if found:
ep = found[0]
module_name, _, attr = ep.value.partition(":")
module = importlib.import_module(module_name)
func = getattr(module, attr) if attr else None
if callable(func):
return call_fn_flexible(func, argv)
except Exception:
pass
if 'pkg_resources' in globals() and pkg_resources is not None:
try:
for ep in pkg_resources.iter_entry_points(group="console_scripts", name=name):
func = ep.load()
if callable(func):
return call_fn_flexible(func, argv)
except Exception:
pass
return False
def prepare_tempdir():
# Creamos un tmp propio dentro do bundle (ou do cwd en modo desenvolvemento)
tmpdir = resource_path("tmp")
tmpdir.mkdir(parents=True, exist_ok=True)
# apuntamos as variables temporais para evitar tempOSs que o AV poda tocar
os.environ["TMP"] = str(tmpdir)
os.environ["TEMP"] = str(tmpdir)
os.environ["TMPDIR"] = str(tmpdir)
def main():
# 1) Engadir vendors/TESSERACT ao PATH
add_vendor_dir_to_path("vendors", "tesseract")
tessdata = resource_path("vendors", "tesseract", "tessdata")
if tessdata.exists():
os.environ["TESSDATA_PREFIX"] = str(tessdata)
# 1.5) Engadir pngquant e jbig2 ao PATH (se existen)
add_vendor_dir_to_path("vendors", "pngquant")
add_vendor_dir_to_path("vendors", "jbig2enc")
add_vendor_dir_to_path("vendors", "jbig2") # por se ten ese nome
add_vendor_dir_to_path("vendors", "qpdf")
# 2) Ghostscript
add_vendor_dir_to_path("vendors", "ghostscript", "bin")
find_and_set_gs()
# 3) Forzar UTF-8
os.environ.setdefault("PYTHONUTF8", "1")
# 4) Preparar tmp propio
prepare_tempdir()
argv = sys.argv[1:]
# 5) Intento directo __main__
tb1 = tb2 = tb3 = None
try:
mod = importlib.import_module("ocrmypdf.__main__")
for attr in ("main", "run", "cli"):
fn = getattr(mod, attr, None)
if callable(fn):
ok = call_fn_flexible(fn, argv)
if ok:
return
except Exception:
tb1 = traceback.format_exc()
# 6) Intentar entry-point console_script 'ocrmypdf'
try:
if call_entrypoint_console_script("ocrmypdf", argv):
return
except Exception:
tb2 = traceback.format_exc()
# 7) Fallback run_module
try:
runpy.run_module("ocrmypdf", run_name="__main__")
return
except SystemExit as se:
code = se.code if isinstance(se.code, int) else 0
sys.exit(code)
except Exception:
tb3 = traceback.format_exc()
# 8) Nada funcionou: imprimir detalles
sys.stderr.write("ERROR: non se puido invocar ocrmypdf via __main__, console_script, nin run_module.\n")
if tb1:
sys.stderr.write("Trace desde import ocrmypdf.__main__:\n" + tb1 + "\n")
if tb2:
sys.stderr.write("Trace desde intento de console_script:\n" + tb2 + "\n")
if tb3:
sys.stderr.write("Trace desde run_module:\n" + tb3 + "\n")
sys.exit(2)
if __name__ == "__main__":
main()