Command commited on
Commit
eaf9ae6
·
1 Parent(s): f30e0ce

fix app.py

Browse files
Files changed (3) hide show
  1. app.py +37 -62
  2. run.py +0 -21
  3. streamlit.py +0 -32
app.py CHANGED
@@ -1,64 +1,39 @@
1
- # Adapted from https://github.com/kingyiusuen/image-to-latex/blob/main/api/app.py
2
-
3
- from http import HTTPStatus
4
- from fastapi import FastAPI, File, UploadFile, Form
5
  from PIL import Image
6
- from io import BytesIO
7
  from pix2tex.cli import LatexOCR
8
-
9
- model = None
10
- app = FastAPI(title='pix2tex API')
11
-
12
-
13
- def read_imagefile(file) -> Image.Image:
14
- image = Image.open(BytesIO(file))
15
- return image
16
-
17
-
18
- @app.on_event('startup')
19
- async def load_model():
20
- global model
21
- if model is None:
22
- model = LatexOCR()
23
-
24
-
25
- @app.get('/')
26
- def root():
27
- '''Health check.'''
28
- response = {
29
- 'message': HTTPStatus.OK.phrase,
30
- 'status-code': HTTPStatus.OK,
31
- 'data': {},
32
- }
33
- return response
34
-
35
-
36
- @app.post('/predict/')
37
- async def predict(file: UploadFile = File(...)) -> str:
38
- """Predict the Latex code from an image file.
39
-
40
- Args:
41
- file (UploadFile, optional): Image to predict. Defaults to File(...).
42
-
43
- Returns:
44
- str: Latex prediction
45
- """
46
- global model
47
- image = Image.open(file.file)
48
- return model(image)
49
-
50
-
51
- @app.post('/bytes/')
52
- async def predict_from_bytes(file: bytes = File(...)) -> str: # , size: str = Form(...)
53
- """Predict the Latex code from a byte array
54
-
55
- Args:
56
- file (bytes, optional): Image as byte array. Defaults to File(...).
57
-
58
- Returns:
59
- str: Latex prediction
60
- """
61
- global model
62
- #size = tuple(int(a) for a in size.split(','))
63
- image = Image.open(BytesIO(file))
64
- return model(image, resize=False)
 
1
+ import requests
 
 
 
2
  from PIL import Image
 
3
  from pix2tex.cli import LatexOCR
4
+ from PIL import Image
5
+ import streamlit
6
+
7
+ model = LatexOCR()
8
+
9
+
10
+ streamlit.set_page_config(page_title="LaTeX-OCR")
11
+ streamlit.title("LaTeX OCR")
12
+ streamlit.markdown(
13
+ "Convert images of equations to corresponding LaTeX code.\n\nThis is based on the `pix2tex` module. Check it out [![github](https://img.shields.io/badge/LaTeX--OCR-visit-a?style=social&logo=github)](https://github.com/lukas-blecher/LaTeX-OCR)"
14
+ )
15
+
16
+ uploaded_file = streamlit.file_uploader(
17
+ "Upload an image an equation",
18
+ type=["png", "jpg"],
19
+ )
20
+
21
+ if uploaded_file is not None:
22
+ image = Image.open(uploaded_file)
23
+ streamlit.image(image)
24
+ else:
25
+ streamlit.text("\n")
26
+
27
+ if streamlit.button("Convert"):
28
+ if uploaded_file is not None and image is not None:
29
+ with streamlit.spinner("Computing"):
30
+ image = Image.open(uploaded_file.getvalue())
31
+ try:
32
+ result = model(image)
33
+ streamlit.code(result, language="latex")
34
+ streamlit.markdown(f"$\\displaystyle {result}$")
35
+ except Exception as e:
36
+ streamlit.error(e)
37
+
38
+ else:
39
+ streamlit.error("Please upload an image.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
run.py DELETED
@@ -1,21 +0,0 @@
1
- from multiprocessing import Process
2
- import subprocess
3
- import os
4
-
5
-
6
- def start_api(path='.'):
7
- subprocess.call(['uvicorn', 'app:app', '--port', '8502'], cwd=path)
8
-
9
-
10
- def start_frontend(path='.'):
11
- subprocess.call(['streamlit', 'run', 'streamlit.py'], cwd=path)
12
-
13
-
14
- if __name__ == '__main__':
15
- path = os.path.realpath(os.path.dirname(__file__))
16
- api = Process(target=start_api, kwargs={'path': path})
17
- api.start()
18
- frontend = Process(target=start_frontend, kwargs={'path': path})
19
- frontend.start()
20
- api.join()
21
- frontend.join()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
streamlit.py DELETED
@@ -1,32 +0,0 @@
1
- import requests
2
- from PIL import Image
3
- import streamlit
4
-
5
- if __name__ == '__main__':
6
- streamlit.set_page_config(page_title='LaTeX-OCR')
7
- streamlit.title('LaTeX OCR')
8
- streamlit.markdown('Convert images of equations to corresponding LaTeX code.\n\nThis is based on the `pix2tex` module. Check it out [![github](https://img.shields.io/badge/LaTeX--OCR-visit-a?style=social&logo=github)](https://github.com/lukas-blecher/LaTeX-OCR)')
9
-
10
- uploaded_file = streamlit.file_uploader(
11
- 'Upload an image an equation',
12
- type=['png', 'jpg'],
13
- )
14
-
15
- if uploaded_file is not None:
16
- image = Image.open(uploaded_file)
17
- streamlit.image(image)
18
- else:
19
- streamlit.text('\n')
20
-
21
- if streamlit.button('Convert'):
22
- if uploaded_file is not None and image is not None:
23
- with streamlit.spinner('Computing'):
24
- response = requests.post('http://127.0.0.1:8502/predict/', files={'file': uploaded_file.getvalue()})
25
- if response.ok:
26
- latex_code = response.json()
27
- streamlit.code(latex_code, language='latex')
28
- streamlit.markdown(f'$\\displaystyle {latex_code}$')
29
- else:
30
- streamlit.error(response.text)
31
- else:
32
- streamlit.error('Please upload an image.')