Skip to content

Commit 54dca2a

Browse files
Merge pull request lukas-blecher#187 from Freed-Wu/file
Fix `--file` and support expanding `~`
2 parents f479a12 + 7a7f669 commit 54dca2a

File tree

2 files changed

+63
-29
lines changed

2 files changed

+63
-29
lines changed

pix2tex/__main__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,18 @@ def main():
1010
parser.add_argument('--no-resize', action='store_true', help='Resize the image beforehand')
1111

1212
parser.add_argument('-s', '--show', action='store_true', help='Show the rendered predicted latex code (cli only)')
13-
parser.add_argument('-f', '--file', type=str, default=None, help='Predict LaTeX code from image file instead of clipboard (cli only)')
1413
parser.add_argument('-k', '--katex', action='store_true', help='Render the latex code in the browser (cli only)')
1514

1615
parser.add_argument('--gui', action='store_true', help='Use GUI (gui only)')
1716

17+
parser.add_argument('file', nargs='*', type=str, default=None, help='Predict LaTeX code from image file instead of clipboard (cli only)')
1818
arguments = parser.parse_args()
1919

2020
import os
2121
import sys
2222

2323
name = os.path.split(sys.argv[0])[-1]
24-
if arguments.gui or arguments.gnome or name in ['pix2tex_gui', 'latexocr']:
24+
if arguments.gui or name in ['pix2tex_gui', 'latexocr']:
2525
from .gui import main
2626
else:
2727
from .cli import main

pix2tex/cli.py

+61-27
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
from PIL import ImageGrab
44
from PIL import Image
55
import os
6+
from pathlib import Path
67
import sys
7-
from typing import Tuple
8+
from typing import List, Optional, Tuple
89
import atexit
910
from contextlib import suppress
1011
import logging
@@ -105,9 +106,9 @@ def __call__(self, img=None, resize=True) -> str:
105106
img = None
106107
if img is None:
107108
if self.last_pic is None:
108-
print('Provide an image.')
109109
return ''
110110
else:
111+
print('\nLast image is: ', end='')
111112
img = self.last_pic.copy()
112113
else:
113114
self.last_pic = img.copy()
@@ -177,6 +178,36 @@ def output_prediction(pred, args):
177178
webbrowser.open(url)
178179

179180

181+
def predict(model, file, arguments):
182+
img = None
183+
if file:
184+
try:
185+
img = Image.open(os.path.expanduser(file))
186+
except Exception as e:
187+
print(e, end='')
188+
else:
189+
try:
190+
img = ImageGrab.grabclipboard()
191+
except NotImplementedError as e:
192+
print(e, end='')
193+
pred = model(img)
194+
output_prediction(pred, arguments)
195+
196+
def check_file_path(paths:List[Path], wdir:Optional[Path]=None)->List[str]:
197+
files = []
198+
for path in paths:
199+
if type(path)==str:
200+
if path=='':
201+
continue
202+
path=Path(path)
203+
pathsi = ([path] if wdir is None else [path, wdir/path])
204+
for p in pathsi:
205+
if p.exists():
206+
files.append(str(p.resolve()))
207+
elif '*' in path.name:
208+
files.extend([str(pi.resolve()) for pi in p.parent.glob(p.name)])
209+
return list(set(files))
210+
180211
def main(arguments):
181212
path = user_data_dir('pix2tex')
182213
os.makedirs(path, exist_ok=True)
@@ -187,20 +218,31 @@ def main(arguments):
187218
with suppress(OSError):
188219
readline.read_history_file(history_file)
189220
atexit.register(readline.write_history_file, history_file)
221+
files = check_file_path(arguments.file)
222+
wdir = Path(os.getcwd())
190223
with in_model_path():
191224
model = LatexOCR(arguments)
192-
file = None
225+
if files:
226+
for file in check_file_path(arguments.file, wdir):
227+
print(file + ': ', end='')
228+
predict(model, file, arguments)
229+
model.last_pic = None
230+
with suppress(NameError):
231+
readline.add_history(file)
232+
exit()
233+
pat = re.compile(r't=([\.\d]+)')
193234
while True:
194235
try:
195-
instructions = input('Predict LaTeX code for image ("?"/"h" for help). ')
236+
instructions = input('Predict LaTeX code for image ("h" for help). ')
196237
except KeyboardInterrupt:
197238
# TODO: make the last line gray
198239
print("")
199240
continue
200241
except EOFError:
201242
break
202-
possible_file = instructions.strip()
203-
ins = possible_file.lower()
243+
file = instructions.strip()
244+
ins = file.lower()
245+
t = pat.match(ins)
204246
if ins == 'x':
205247
break
206248
elif ins in ['?', 'h', 'help']:
@@ -231,26 +273,18 @@ def main(arguments):
231273
setattr(arguments, ins, not getattr(arguments, ins, False))
232274
print('set %s to %s' % (ins, getattr(arguments, ins)))
233275
continue
234-
elif os.path.isfile(os.path.realpath(possible_file)):
235-
file = possible_file
236-
else:
237-
t = re.match(r't=([\.\d]+)', ins)
238-
if t is not None:
239-
t = t.groups()[0]
240-
model.args.temperature = float(t)+1e-8
241-
print('new temperature: T=%.3f' % model.args.temperature)
242-
continue
243-
try:
244-
img = None
245-
if file:
246-
img = Image.open(file)
276+
elif t is not None:
277+
t = t.groups()[0]
278+
model.args.temperature = float(t)+1e-8
279+
print('new temperature: T=%.3f' % model.args.temperature)
280+
continue
281+
files = check_file_path(file.split(' '), wdir)
282+
with suppress(KeyboardInterrupt):
283+
if files:
284+
for file in files:
285+
if len(files)>1:
286+
print(file + ': ', end='')
287+
predict(model, file, arguments)
247288
else:
248-
try:
249-
img = ImageGrab.grabclipboard()
250-
except:
251-
pass
252-
pred = model(img)
253-
output_prediction(pred, arguments)
254-
except KeyboardInterrupt:
255-
pass
289+
predict(model, file, arguments)
256290
file = None

0 commit comments

Comments
 (0)