mohsayed commited on
Commit
7acf2e3
·
1 Parent(s): 2028a71
Files changed (2) hide show
  1. app.py +202 -0
  2. requirements.txt +26 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import requests
3
+ import streamlit as st
4
+ import pandas as pd
5
+ import numpy as np
6
+ from urllib.request import urlretrieve ,urlopen
7
+ import os
8
+ import torch
9
+ from distutils.dir_util import copy_tree
10
+ import tempfile
11
+ import zipfile
12
+ import subprocess
13
+ import mmcv
14
+ from mmcv import Config
15
+ import sys
16
+ from shapely.geometry import Polygon
17
+
18
+
19
+ import shutil
20
+ import ssl
21
+
22
+ import urllib.request
23
+ from pathlib import Path
24
+
25
+ import cv2
26
+ from PIL import Image
27
+ ##########
28
+ @st.cache(allow_output_mutation=True)
29
+ def loading_resources():
30
+ dl_url = os.environ['dl_url']
31
+ if 'utils2.py' not in os.listdir('./'):
32
+ urlretrieve(dl_url, 'appdata.zip')
33
+ with zipfile.ZipFile("appdata.zip","r") as zip_ref:
34
+ zip_ref.extractall("./")
35
+ loading_resources()
36
+
37
+ import utilss
38
+ from utils2 import *
39
+ if 'model_inference' not in sys.modules:
40
+ from mmocr.apis import init_detector ,model_inference
41
+ else:
42
+ model_inference = sys.modules['model_inference']
43
+ init_detector = sys.modules['init_detector']
44
+
45
+ ########## utils
46
+
47
+ def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
48
+ dim = None
49
+ (h, w) = image.shape[:2]
50
+ if width is None and height is None:
51
+ return image
52
+
53
+ if width is None:
54
+ r = height / float(h)
55
+ dim = (int(w * r), height)
56
+ else:
57
+ r = width / float(w)
58
+ dim = (width, int(h * r))
59
+ resized = cv2.resize(image, dim, interpolation = inter)
60
+ return resized
61
+ def download_file(url, local_filename):
62
+ with requests.get(url, stream=True) as r:
63
+ with open(local_filename, 'wb') as f:
64
+ shutil.copyfileobj(r.raw, f)
65
+
66
+ return local_filename
67
+ def load_and_preprocess_img(img_path, bbox=None):
68
+ img = Image.open(img_path).convert('RGB')
69
+ img = np.array(img).astype(np.uint8)
70
+ return img
71
+
72
+
73
+ # @st.cache()
74
+ def predictim(im , model):
75
+ if 'model_inference' not in sys.modules:
76
+ # if not model_inference:
77
+ from mmocr.apis import model_inference
78
+ result = model_inference(model,im )
79
+ # result[]
80
+ return result
81
+ # return result
82
+ # minfer=None
83
+ # minit=None
84
+ @st.cache(allow_output_mutation=True)
85
+ def loading_model():
86
+ # global minfer
87
+ # global minit
88
+
89
+ from mmdet.apis import set_random_seed
90
+ set_random_seed(0, deterministic=False)
91
+ cfg = Config.fromfile('./cfgsn.py')
92
+ checkpoint = "./200s.pth"
93
+ model1 = init_detector(cfg, checkpoint, device="cpu")
94
+ if model1.cfg.data.test['type'] == 'ConcatDataset':
95
+ model1.cfg.data.test.pipeline = model1.cfg.data.test['datasets'][0].pipeline
96
+ return model1
97
+ model = loading_model()
98
+
99
+
100
+
101
+ def main():
102
+ st.sidebar.info('Images are deleted instantly')
103
+ form0 =st.sidebar.form("my_form0")
104
+
105
+ f = form0.file_uploader("Upload an Image", type=['png', 'jpg', 'jpeg', 'tiff', 'gif'])
106
+ btnpredicrupload = form0.form_submit_button("PREDICT")
107
+
108
+
109
+ st.sidebar.write(" ------ ")
110
+ form =st.sidebar.form("my_form")
111
+ photos = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg','6.jpg',]
112
+ option = form.selectbox('Or choose a sample image', photos)
113
+ submitted = form.form_submit_button("PREDICT")
114
+
115
+ st.sidebar.write(" ------ ")
116
+ st.sidebar.info('Options')
117
+ fcolor = st.sidebar.selectbox('boundary color', ['red','green','blue'])
118
+ extra_postprocess = st.sidebar.checkbox('perform extra postprocessing',value=True)
119
+ # do_thresh_box = st.sidebar.checkbox('adaptive threshold')
120
+
121
+ if btnpredicrupload and f is not None:
122
+ tfile = tempfile.NamedTemporaryFile(delete=True)
123
+ tfile.write(f.read())
124
+ imgpath=tfile.name
125
+ run_app(imgpath ,fcolor,extra_post=extra_postprocess)
126
+ if submitted:
127
+ st.empty()
128
+ directory ='./imgs/'
129
+ pic = os.path.join(directory, option)
130
+ imgpath=directory+option
131
+ run_app(imgpath ,fcolor,extra_post=extra_postprocess)
132
+ # inp = st.text_input('t2','')
133
+ # if st.button('run'):
134
+ # subprocess.run(inp.split(' '))
135
+
136
+
137
+ # def run_app(imgpath,do_thresh,fcolor):
138
+ def run_app(imgpath,fcolor,**kwargs):
139
+ d0 =dict(red=[255,0,0] ,green=[0,255,0] ,blue=[0,0,255] )
140
+ fcolor = d0[fcolor]
141
+ # st.sidebar.write(imgpath)
142
+ # r = np.random.randint(1e3,1e7)
143
+ tfile = tempfile.NamedTemporaryFile(delete=True,suffix='.jpg')
144
+ dst = tfile.name
145
+ # tfile = open()
146
+ img = load_and_preprocess_img(imgpath)
147
+ # img = utilss.resize_with_pad(img,800,800)
148
+ # if do_thresh:
149
+ # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
150
+ # threshim = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 51, 20)
151
+ # img= cv2.cvtColor(threshim, cv2.COLOR_GRAY2RGB)
152
+
153
+ cv2.imwrite(dst,cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
154
+ # imgo = image_resize(img , width = 640)
155
+ st.write('input:')
156
+ st.image(img, caption = "Selected Input" , width =640)
157
+
158
+ # if st.button('predict2'):
159
+
160
+ # try:
161
+ # except: print('errr--------------')
162
+ ''
163
+ ##################
164
+ preds,img_metas,downsample_ratio = model_inference(model,dst )
165
+ ff= fixer(img,preds,img_metas,downsample_ratio)
166
+ polys= ff.polysfin3
167
+ if kwargs['extra_post']:
168
+ polys =find_polys4(ff)
169
+
170
+
171
+ # with open('./0.json','r') as f:
172
+ # res = json.load(f)
173
+ ################
174
+ mm = utilss.draw_conts(img,[poly2cont(p) for p in polys],fcolor)
175
+ ## mm=image_resize(mm, width = 640)
176
+ #######
177
+ # mm=preds[1]*preds[0]
178
+ # mm=cv2.cvtColor(mm, cv2.COLOR_GRAY2RGB)
179
+ st.image(mm,caption='output image' , width = 640)
180
+ # del polys
181
+ del ff
182
+ del mm
183
+ del preds
184
+ del polys
185
+ del img
186
+ del img_metas
187
+ # os.remove(dst)
188
+ # x = predictim(img,model)
189
+ # st.write(x)
190
+
191
+ main()
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
requirements.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --find-links https://download.pytorch.org/whl/torch_stable.html
2
+ torch==1.12.0+cu113
3
+ torchvision==0.13.0+cu113
4
+
5
+ #--find-links https://download.openmmlab.com/mmcv/dist/cpu/torch1.12.0/index.html
6
+ --find-links https://download.openmmlab.com/mmcv/dist/cu113/torch1.12.0/index.html
7
+ mmcv-full==1.6.0
8
+ mmdet
9
+
10
+ numpy
11
+ pyclipper
12
+
13
+ opencv-python-headless==4.6.0.66
14
+ pycocotools
15
+ rapidfuzz
16
+ scikit-image
17
+ six
18
+ terminaltables
19
+ matplotlib
20
+ numba>=0.45.1
21
+ lanms-neo==1.0.2
22
+ imgaug
23
+ lmdb
24
+ matplotlib
25
+ easydict
26
+ sklearn