ardakshalkar commited on
Commit
d7deef5
1 Parent(s): bdd1d0b
.dockerignore ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Include any files or directories that you don't want to be copied to your
2
+ # container here (e.g., local build artifacts, temporary files, etc.).
3
+ #
4
+ # For more help, visit the .dockerignore file reference guide at
5
+ # https://docs.docker.com/go/build-context-dockerignore/
6
+
7
+ **/.DS_Store
8
+ **/__pycache__
9
+ **/.venv
10
+ **/.classpath
11
+ **/.dockerignore
12
+ **/.env
13
+ **/.git
14
+ **/.gitignore
15
+ **/.project
16
+ **/.settings
17
+ **/.toolstarget
18
+ **/.vs
19
+ **/.vscode
20
+ **/*.*proj.user
21
+ **/*.dbmdl
22
+ **/*.jfm
23
+ **/bin
24
+ **/charts
25
+ **/docker-compose*
26
+ **/compose*
27
+ **/Dockerfile*
28
+ **/node_modules
29
+ **/npm-debug.log
30
+ **/obj
31
+ **/secrets.dev.yaml
32
+ **/values.dev.yaml
33
+ LICENSE
34
+ README.md
Dockerfile ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+
3
+ # Comments are provided throughout this file to help you get started.
4
+ # If you need more help, visit the Dockerfile reference guide at
5
+ # https://docs.docker.com/go/dockerfile-reference/
6
+
7
+ ARG PYTHON_VERSION=3.11.5
8
+ FROM python:${PYTHON_VERSION}-slim as base
9
+
10
+ # Prevents Python from writing pyc files.
11
+ ENV PYTHONDONTWRITEBYTECODE=1
12
+
13
+ # Keeps Python from buffering stdout and stderr to avoid situations where
14
+ # the application crashes without emitting any logs due to buffering.
15
+ ENV PYTHONUNBUFFERED=1
16
+
17
+ WORKDIR /app
18
+
19
+ # Create a non-privileged user that the app will run under.
20
+ # See https://docs.docker.com/go/dockerfile-user-best-practices/
21
+ ARG UID=10001
22
+ RUN adduser \
23
+ --disabled-password \
24
+ --gecos "" \
25
+ --home "/nonexistent" \
26
+ --shell "/sbin/nologin" \
27
+ --no-create-home \
28
+ --uid "${UID}" \
29
+ appuser
30
+
31
+ # Download dependencies as a separate step to take advantage of Docker's caching.
32
+ # Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
33
+ # Leverage a bind mount to requirements.txt to avoid having to copy them into
34
+ # into this layer.
35
+ RUN --mount=type=cache,target=/root/.cache/pip \
36
+ --mount=type=bind,source=requirements.txt,target=requirements.txt \
37
+ python -m pip install -r requirements.txt
38
+
39
+ # Switch to the non-privileged user to run the application.
40
+ USER appuser
41
+
42
+ # Copy the source code into the container.
43
+ COPY . .
44
+
45
+ # Expose the port that the application listens on.
46
+ EXPOSE 8000
47
+
48
+ # Run the application.
49
+ CMD streamlit run app.py
README.Docker.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Building and running your application
2
+
3
+ When you're ready, start your application by running:
4
+ `docker compose up --build`.
5
+
6
+ Your application will be available at http://localhost:8000.
7
+
8
+ ### Deploying your application to the cloud
9
+
10
+ First, build your image, e.g.: `docker build -t myapp .`.
11
+ If your cloud uses a different CPU architecture than your development
12
+ machine (e.g., you are on a Mac M1 and your cloud provider is amd64),
13
+ you'll want to build the image for that platform, e.g.:
14
+ `docker build --platform=linux/amd64 -t myapp .`.
15
+
16
+ Then, push it to your registry, e.g. `docker push myregistry.com/myapp`.
17
+
18
+ Consult Docker's [getting started](https://docs.docker.com/go/get-started-sharing/)
19
+ docs for more detail on building and pushing.
20
+
21
+ ### References
22
+ * [Docker's Python guide](https://docs.docker.com/language/python/)
app.css ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ /* CSS */
3
+ .button {
4
+ appearance: button;
5
+ line-height: 44px;
6
+ text-decoration: none;
7
+ color:white !important;
8
+ backface-visibility: hidden;
9
+ border-color: #405cf5 !important;
10
+ background-color: white;
11
+ color:#405cf5 !important;
12
+ border-radius: 6px;
13
+ border-width: 0;
14
+ box-shadow: rgba(50, 50, 93, .1) 0 0 0 1px inset,rgba(50, 50, 93, .1) 0 2px 5px 0,rgba(0, 0, 0, .07) 0 1px 1px 0;
15
+ box-sizing: border-box;
16
+ color: #fff;
17
+ cursor: pointer;
18
+ font-family: -apple-system,system-ui,"Segoe UI",Roboto,"Helvetica Neue",Ubuntu,sans-serif;
19
+ font-size: 100%;
20
+ height: 44px;
21
+ /*line-height: 1.15;*/
22
+ margin: 12px 0 0;
23
+ outline: none;
24
+ overflow: hidden;
25
+ padding: 0 25px;
26
+ position: relative;
27
+ text-align: center;
28
+ text-transform: none;
29
+ transform: translateZ(0);
30
+ transition: all .2s,box-shadow .08s ease-in;
31
+ user-select: none;
32
+ -webkit-user-select: none;
33
+ touch-action: manipulation;
34
+ font-weight: bold;
35
+ margin:5px;
36
+ }
37
+
38
+ .button:disabled {
39
+ cursor: default;
40
+ }
41
+
42
+ .button:hover {
43
+ text-decoration: none;
44
+ box-shadow: rgba(50, 50, 93, .1) 0 0 0 1px inset, rgba(50, 50, 93, .2) 0 6px 15px 0, rgba(0, 0, 0, .1) 0 2px 2px 0, rgba(50, 151, 211, .3) 0 0 0 4px;
45
+ }
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ from PIL import Image
4
+ import os
5
+ import easyocr
6
+ import numpy as np
7
+ import fitz # PyMuPDF
8
+ import io
9
+ from pdf2image import convert_from_bytes
10
+ from st_btn_group import st_btn_group
11
+ from streamlit_option_menu import option_menu
12
+ import docx
13
+ from docx.shared import Pt
14
+ from io import BytesIO
15
+ #import streamlit.components.v1 as components
16
+ import base64
17
+
18
+ #def downloadTxt():
19
+ def generateTxtLink(result):
20
+ result_txt = ""
21
+ print(result)
22
+ for para in result:
23
+ result_txt += para[1]+"\n"
24
+ result_b64 = base64.b64encode(result_txt.encode()).decode('utf-8')
25
+ result_txt_link = "<a class='button' href='data:text/plain;base64,"+result_b64+"' download='document.txt'>TXT</a>"
26
+ return result_txt_link
27
+
28
+ def generateMultiPageTxtLink(result):
29
+ result_txt = ""
30
+ print(result)
31
+ for para in result:
32
+ result_txt += para+"\n"
33
+ result_b64 = base64.b64encode(result_txt.encode()).decode('utf-8')
34
+ result_txt_link = "<a class='button' href='data:text/plain;base64,"+result_b64+"' download='document.txt'>TXT</a>"
35
+ return result_txt_link
36
+
37
+ def generateDocLink(result):
38
+ doc = docx.Document()
39
+ for para in result:
40
+ doc.add_paragraph(para[1])
41
+
42
+ target_stream = BytesIO()
43
+ result_doc = doc.save(target_stream)
44
+ base64_doc = base64.b64encode(target_stream.getvalue()).decode('utf-8')
45
+ stlyeCss = ""
46
+ doc_link = "<a class='button' href='data:application/pdf;base64,"+base64_doc+"' download='document.docx'>DOCX</a>"
47
+ return doc_link
48
+
49
+ def generateMultiPageDocLink(pages_result):
50
+ doc = docx.Document()
51
+ #print(pages_result)
52
+ for page in pages_result:
53
+ page_split = page.split("\n")
54
+ for para in page_split:
55
+ doc.add_paragraph(para)
56
+ doc.add_page_break()
57
+ target_stream = BytesIO()
58
+ result_doc = doc.save(target_stream)
59
+ base64_doc = base64.b64encode(target_stream.getvalue()).decode('utf-8')
60
+ doc_link = "<a class='button' href='data:application/pdf;base64,"+base64_doc+"' download='document.docx'>DOCX</a>"
61
+ return doc_link
62
+
63
+ def generateButtonGroup(result):
64
+ txtLink = generateTxtLink(result)
65
+ docLink = generateDocLink(result)
66
+ return txtLink+"\n"+docLink
67
+
68
+ def generateButtonGroupForPDF(pages_result):
69
+ #result = "\n\n".join(pages_result)
70
+ txtLink = generateMultiPageTxtLink(pages_result)
71
+ docLink = generateMultiPageDocLink(pages_result)
72
+ return txtLink+"\n"+docLink
73
+
74
+ def local_css(file_name):
75
+ with open(file_name) as f:
76
+ st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
77
+
78
+
79
+ models_dir = "./models"
80
+ output_dir = "./output"
81
+ dirs = [models_dir, output_dir]
82
+ for d in dirs:
83
+ if not os.path.exists(output_dir):
84
+ os.makedirs(output_dir)
85
+
86
+ font_path = models_dir + "/Ubuntu-Regular.ttf"
87
+ reader = easyocr.Reader(
88
+ ['en'],
89
+ gpu=True,
90
+ recog_network='best_norm_ED',
91
+ detect_network="craft",
92
+ user_network_directory=models_dir,
93
+ model_storage_directory=models_dir,
94
+ ) # this needs to run only once to load the model into memory
95
+
96
+
97
+
98
+
99
+ # main title
100
+ st.set_page_config(layout="wide",page_title="Қазақша OCR, суреттегі текстті тану")
101
+ local_css("app.css")
102
+ #st.markdown("<a class='button' href='lenta.ru'>DOCX жүктеп ал</a>",unsafe_allow_html=True)
103
+ st.title("Сурет немесе пдф файлдан текст алу")
104
+ # subtitle
105
+ #st.markdown("## Qazaq OCR")
106
+
107
+ uploaded_file = st.file_uploader("Өз файлыңызды осында жүктеңіз ('png', 'jpeg', 'jpg', 'pdf')",help="aaa", type=['png', 'jpeg', 'jpg', 'pdf'])
108
+
109
+ col1, col2 = st.columns(2)
110
+
111
+ #def process_page(page):
112
+ # image_matrix = fitz.Matrix(fitz.Identity)
113
+ # pixmap = page.get_pixmap(matrix=image_matrix, dpi=300)
114
+ # image_data = pixmap.samples# This is a bytes object
115
+ # image = Image.from("RGB",(pixmap.width, pixmap.height),image_data)
116
+ # image = Image.from("RGB", (pixmap.width, pixmap.height), image_data)
117
+ # result = reader.readtext(np.array(image),paragraph=True)
118
+ # return image, result
119
+ import time
120
+
121
+ max_page = 3
122
+ def recognize_page_image(image):
123
+ start = time.time()
124
+ result = [[0,"Sample 1"],[1,"Sample 2"]]
125
+ result = reader.readtext(np.array(image), paragraph=True)
126
+ end = time.time()
127
+ return result,(end-start)
128
+
129
+
130
+ def process_pdf(uploaded_file):
131
+ pdf_document = fitz.open(temp_pdf_file)
132
+ total_pages = len(pdf_document)
133
+ progress_bar = col2.progress(0, text="Жүктеліп жатыр")
134
+ button_group = col2.container()
135
+ pages = range(min(max_page,total_pages))
136
+ tabs = col1.tabs([f"Бет {page+1}" for page in pages])
137
+ pages_result = []
138
+ for count, page_num in enumerate(range(min(total_pages,max_page))):
139
+ page = pdf_document.load_page(page_num)
140
+ image_matrix = fitz.Matrix(fitz.Identity)
141
+ pixmap = page.get_pixmap(matrix=image_matrix, dpi=300)
142
+ image_data = pixmap.samples # This is a bytes object
143
+ image = Image.frombytes("RGB", (pixmap.width, pixmap.height), image_data)
144
+ imageSmaller = image.resize((int(pixmap.width/10), int(pixmap.height/10)))
145
+ tabs[count].image(imageSmaller)
146
+ #buffered = BytesIO()
147
+ #imageSmaller.save(buffered,format="JPEG")
148
+ #col1.write(f'<h2>Бет {page_num + 1}/{total_pages}</h2>',unsafe_allow_html=True)
149
+ #col1.write(f'<img src="data:image/png;base64, {base64.b64encode(buffered.getvalue()).decode("utf-8")}"/>',unsafe_allow_html=True)
150
+ #col1.subheader(f'Бет {page_num + 1}/{total_pages}')
151
+ #col1.image(imageSmaller, caption=f'Бет {page_num + 1}')
152
+ result,time_elapsed = recognize_page_image(image)
153
+ expander = col2.expander(f'{result[0][1][:100]} ... **:orange[{time_elapsed:.3f} секундта таңылды]**')
154
+ expander.write(f'{result[0][1]}')
155
+ result_text = "\n\n".join([item[1] for item in result])
156
+ pages_result.append(result_text)
157
+ #col2.markdown(result_text)
158
+ progress_bar.progress((count + 1) / min(total_pages,max_page),text=f'Жүктеліп жатыр {count+1}/{min(total_pages,max_page)}')
159
+
160
+ button_group_html = generateButtonGroupForPDF(pages_result)
161
+ button_group.write(button_group_html,unsafe_allow_html=True)
162
+ #col1.write("</div>",unsafe_allow_html=True)
163
+ progress_bar.progress(0.99,text=f'{min(total_pages,max_page)} бет жүктелді')
164
+
165
+
166
+
167
+ if uploaded_file is not None:
168
+ if uploaded_file.type == "application/pdf":
169
+ placeholder = col2.empty()
170
+ with placeholder, st.spinner('PDF өңделуде ...'):
171
+ temp_pdf_file = "./temp_pdf_file.pdf"
172
+ with open(temp_pdf_file, "wb") as f:
173
+ f.write(uploaded_file.read())
174
+ process_pdf(uploaded_file)
175
+ else:
176
+ placeholder = col2.empty()
177
+ with placeholder,st.spinner('Сурет өңделуде ...'):
178
+ image = Image.open(uploaded_file)
179
+ #with open(os.path.join("tempDir",image_file))
180
+ col1.image(image)
181
+ result = reader.readtext(np.array(image), paragraph=True)
182
+ result_text = "\n\n".join([item[1] for item in result])
183
+ button_group_html = generateButtonGroup(result)
184
+ col2.write(button_group_html, unsafe_allow_html=True)
185
+ col2.markdown(result_text)
186
+
compose.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Comments are provided throughout this file to help you get started.
2
+ # If you need more help, visit the Docker compose reference guide at
3
+ # https://docs.docker.com/go/compose-spec-reference/
4
+
5
+ # Here the instructions define your application as a service called "server".
6
+ # This service is built from the Dockerfile in the current directory.
7
+ # You can add other services your application may depend on here, such as a
8
+ # database or a cache. For examples, see the Awesome Compose repository:
9
+ # https://github.com/docker/awesome-compose
10
+ services:
11
+ server:
12
+ build:
13
+ context: .
14
+ ports:
15
+ - 8000:8000
16
+
17
+ # The commented out section below is an example of how to define a PostgreSQL
18
+ # database that your application can use. `depends_on` tells Docker Compose to
19
+ # start the database before your application. The `db-data` volume persists the
20
+ # database data between container restarts. The `db-password` secret is used
21
+ # to set the database password. You must create `db/password.txt` and add
22
+ # a password of your choosing to it before running `docker compose up`.
23
+ # depends_on:
24
+ # db:
25
+ # condition: service_healthy
26
+ # db:
27
+ # image: postgres
28
+ # restart: always
29
+ # user: postgres
30
+ # secrets:
31
+ # - db-password
32
+ # volumes:
33
+ # - db-data:/var/lib/postgresql/data
34
+ # environment:
35
+ # - POSTGRES_DB=example
36
+ # - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
37
+ # expose:
38
+ # - 5432
39
+ # healthcheck:
40
+ # test: [ "CMD", "pg_isready" ]
41
+ # interval: 10s
42
+ # timeout: 5s
43
+ # retries: 5
44
+ # volumes:
45
+ # db-data:
46
+ # secrets:
47
+ # db-password:
48
+ # file: db/password.txt
49
+
custom_shape.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+ def warp_perspective(image, points):
7
+ # Input and output dimensions
8
+ w, h = 300, 400 # You can adjust this based on the desired output size
9
+ input_pts = np.array(points, dtype=np.float32)
10
+ output_pts = np.array([[0, 0], [w, 0], [w, h], [0, h]], dtype=np.float32)
11
+
12
+ # Compute perspective matrix and warp the image
13
+ matrix = cv2.getPerspectiveTransform(input_pts, output_pts)
14
+ warped_img = cv2.warpPerspective(image, matrix, (w, h))
15
+
16
+ return warped_img
17
+
18
+ st.title("Custom Shape Cropping & Perspective Correction")
19
+
20
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
21
+
22
+ # Provide a placeholder for the user to input 4 vertices
23
+ points = []
24
+ for i in range(4):
25
+ coords = st.text_input(f"Enter point {i+1} (format: x,y)", "")
26
+ x, y = map(int, coords.split(',')) if ',' in coords else (0, 0)
27
+ points.append([x, y])
28
+
29
+ if uploaded_file and len(points) == 4:
30
+ image = Image.open(uploaded_file).convert('RGB')
31
+ image_np = np.array(image)
32
+
33
+ corrected_image = warp_perspective(image_np, points)
34
+
35
+ st.image(corrected_image, caption='Corrected Image.', channels="BGR", use_column_width=True)
kz_ocr_easy.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ from tqdm import tqdm
6
+ import os
7
+
8
+ import easyocr
9
+
10
+ models_dir = "./models"
11
+ images_dir = "./images"
12
+ output_dir = "./output"
13
+ dirs = [models_dir, images_dir, output_dir]
14
+ for d in dirs:
15
+ if not os.path.exists(output_dir):
16
+ os.makedirs(output_dir)
17
+
18
+ """
19
+ Upload easy OCR model files with the same name and font file named Ubuntu-Regular.ttf, examples:
20
+ best_norm_ED.pth
21
+ best_norm_ED.py
22
+ best_norm_ED.yaml
23
+ Ubuntu-Regular.ttf
24
+
25
+ to models directory
26
+
27
+ Upload image files you want to test, examples:
28
+ kz_book_simple.jpeg
29
+ kz_blur.jpg
30
+ kz_book_complex.jpg
31
+
32
+ to images directory
33
+ """
34
+
35
+ font_path = models_dir + "/Ubuntu-Regular.ttf"
36
+
37
+ reader = easyocr.Reader(
38
+ ['en'],
39
+ gpu=True,
40
+ recog_network='best_norm_ED',
41
+ detect_network="craft",
42
+ user_network_directory=models_dir,
43
+ model_storage_directory=models_dir,
44
+ ) # this needs to run only once to load the model into memory
45
+
46
+ image_extensions = (".jpg", ".jpeg", ".png")
47
+
48
+ for image_name in tqdm(os.listdir(images_dir)):
49
+ if not image_name.lower().endswith(image_extensions):
50
+ print(f'unsupported file {image_name}')
51
+ continue
52
+ image_path = f'{images_dir}/{image_name}'
53
+ print(image_path)
54
+ # Read image as numpy array
55
+ image = cv2.imread(image_path)
56
+
57
+ # Rotate the image by 270 degrees
58
+ # image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
59
+
60
+ # Convert the image from BGR to RGB (because OpenCV loads images in BGR format)
61
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
62
+ results = reader.readtext(image=image)
63
+
64
+ # Load custom font
65
+ font = ImageFont.truetype(font_path, 32)
66
+
67
+ # Display the results
68
+ for (bbox, text, prob) in results:
69
+ # Get the bounding box coordinates
70
+ (top_left, top_right, bottom_right, bottom_left) = bbox
71
+ top_left = (int(top_left[0]), int(top_left[1]))
72
+ bottom_right = (int(bottom_right[0]), int(bottom_right[1]))
73
+
74
+ # Draw the bounding box on the image
75
+ cv2.rectangle(image, top_left, bottom_right, (0, 255, 0), 2)
76
+
77
+ # Convert the OpenCV image to a PIL image, draw the text, then convert back to an OpenCV image
78
+ image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
79
+ draw = ImageDraw.Draw(image_pil)
80
+ draw.text((top_left[0], top_left[1] - 40), text, font=font, fill=(0, 0, 255))
81
+ image = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
82
+
83
+ # Save image
84
+ cv2.imwrite( f'{output_dir}/{image_name}', image)
85
+
86
+ # reader.readtext(image = image, paragraph=True)
87
+
88
+
models/Ubuntu-Regular.ttf ADDED
Binary file (352 kB). View file
 
models/__pycache__/best_norm_ED.cpython-311.pyc ADDED
Binary file (40.8 kB). View file
 
models/best_norm_ED.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd58f2bb4ac8afece8d5e6a988c390ec5586152b214aa0906127ccfbdcc71961
3
+ size 15217067
models/best_norm_ED.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7
+
8
+
9
+ class TPS_SpatialTransformerNetwork(nn.Module):
10
+ """ Rectification Network of RARE, namely TPS based STN """
11
+
12
+ def __init__(self, F, I_size, I_r_size, I_channel_num=1):
13
+ """ Based on RARE TPS
14
+ input:
15
+ batch_I: Batch Input Image [batch_size x I_channel_num x I_height x I_width]
16
+ I_size : (height, width) of the input image I
17
+ I_r_size : (height, width) of the rectified image I_r
18
+ I_channel_num : the number of channels of the input image I
19
+ output:
20
+ batch_I_r: rectified image [batch_size x I_channel_num x I_r_height x I_r_width]
21
+ """
22
+ super(TPS_SpatialTransformerNetwork, self).__init__()
23
+ self.F = F
24
+ self.I_size = I_size
25
+ self.I_r_size = I_r_size # = (I_r_height, I_r_width)
26
+ self.I_channel_num = I_channel_num
27
+ self.LocalizationNetwork = LocalizationNetwork(self.F, self.I_channel_num)
28
+ self.GridGenerator = GridGenerator(self.F, self.I_r_size)
29
+
30
+ def forward(self, batch_I):
31
+ batch_C_prime = self.LocalizationNetwork(batch_I) # batch_size x K x 2
32
+ build_P_prime = self.GridGenerator.build_P_prime(batch_C_prime) # batch_size x n (= I_r_width x I_r_height) x 2
33
+ build_P_prime_reshape = build_P_prime.reshape([build_P_prime.size(0), self.I_r_size[0], self.I_r_size[1], 2])
34
+ batch_I_r = F.grid_sample(batch_I, build_P_prime_reshape, padding_mode='border')
35
+
36
+ return batch_I_r
37
+
38
+
39
+ class LocalizationNetwork(nn.Module):
40
+ """ Localization Network of RARE, which predicts C' (K x 2) from I (I_width x I_height) """
41
+
42
+ def __init__(self, F, I_channel_num):
43
+ super(LocalizationNetwork, self).__init__()
44
+ self.F = F
45
+ self.I_channel_num = I_channel_num
46
+ self.conv = nn.Sequential(
47
+ nn.Conv2d(in_channels=self.I_channel_num, out_channels=64, kernel_size=3, stride=1, padding=1,
48
+ bias=False), nn.BatchNorm2d(64), nn.ReLU(True),
49
+ nn.MaxPool2d(2, 2), # batch_size x 64 x I_height/2 x I_width/2
50
+ nn.Conv2d(64, 128, 3, 1, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(True),
51
+ nn.MaxPool2d(2, 2), # batch_size x 128 x I_height/4 x I_width/4
52
+ nn.Conv2d(128, 256, 3, 1, 1, bias=False), nn.BatchNorm2d(256), nn.ReLU(True),
53
+ nn.MaxPool2d(2, 2), # batch_size x 256 x I_height/8 x I_width/8
54
+ nn.Conv2d(256, 512, 3, 1, 1, bias=False), nn.BatchNorm2d(512), nn.ReLU(True),
55
+ nn.AdaptiveAvgPool2d(1) # batch_size x 512
56
+ )
57
+
58
+ self.localization_fc1 = nn.Sequential(nn.Linear(512, 256), nn.ReLU(True))
59
+ self.localization_fc2 = nn.Linear(256, self.F * 2)
60
+
61
+ # Init fc2 in LocalizationNetwork
62
+ self.localization_fc2.weight.data.fill_(0)
63
+ """ see RARE paper Fig. 6 (a) """
64
+ ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))
65
+ ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2))
66
+ ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2))
67
+ ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
68
+ ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
69
+ initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)
70
+ self.localization_fc2.bias.data = torch.from_numpy(initial_bias).float().view(-1)
71
+
72
+ def forward(self, batch_I):
73
+ """
74
+ input: batch_I : Batch Input Image [batch_size x I_channel_num x I_height x I_width]
75
+ output: batch_C_prime : Predicted coordinates of fiducial points for input batch [batch_size x F x 2]
76
+ """
77
+ batch_size = batch_I.size(0)
78
+ features = self.conv(batch_I).view(batch_size, -1)
79
+ batch_C_prime = self.localization_fc2(self.localization_fc1(features)).view(batch_size, self.F, 2)
80
+ return batch_C_prime
81
+
82
+
83
+ class GridGenerator(nn.Module):
84
+ """ Grid Generator of RARE, which produces P_prime by multiplying T with P """
85
+
86
+ def __init__(self, F, I_r_size):
87
+ """ Generate P_hat and inv_delta_C for later """
88
+ super(GridGenerator, self).__init__()
89
+ self.eps = 1e-6
90
+ self.I_r_height, self.I_r_width = I_r_size
91
+ self.F = F
92
+ self.C = self._build_C(self.F) # F x 2
93
+ self.P = self._build_P(self.I_r_width, self.I_r_height)
94
+ ## for multi-gpu, you need register buffer
95
+ self.register_buffer("inv_delta_C", torch.tensor(self._build_inv_delta_C(self.F, self.C)).float()) # F+3 x F+3
96
+ self.register_buffer("P_hat", torch.tensor(self._build_P_hat(self.F, self.C, self.P)).float()) # n x F+3
97
+ ## for fine-tuning with different image width, you may use below instead of self.register_buffer
98
+ # self.inv_delta_C = torch.tensor(self._build_inv_delta_C(self.F, self.C)).float().cuda() # F+3 x F+3
99
+ # self.P_hat = torch.tensor(self._build_P_hat(self.F, self.C, self.P)).float().cuda() # n x F+3
100
+
101
+ def _build_C(self, F):
102
+ """ Return coordinates of fiducial points in I_r; C """
103
+ ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))
104
+ ctrl_pts_y_top = -1 * np.ones(int(F / 2))
105
+ ctrl_pts_y_bottom = np.ones(int(F / 2))
106
+ ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
107
+ ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
108
+ C = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)
109
+ return C # F x 2
110
+
111
+ def _build_inv_delta_C(self, F, C):
112
+ """ Return inv_delta_C which is needed to calculate T """
113
+ hat_C = np.zeros((F, F), dtype=float) # F x F
114
+ for i in range(0, F):
115
+ for j in range(i, F):
116
+ r = np.linalg.norm(C[i] - C[j])
117
+ hat_C[i, j] = r
118
+ hat_C[j, i] = r
119
+ np.fill_diagonal(hat_C, 1)
120
+ hat_C = (hat_C ** 2) * np.log(hat_C)
121
+ # print(C.shape, hat_C.shape)
122
+ delta_C = np.concatenate( # F+3 x F+3
123
+ [
124
+ np.concatenate([np.ones((F, 1)), C, hat_C], axis=1), # F x F+3
125
+ np.concatenate([np.zeros((2, 3)), np.transpose(C)], axis=1), # 2 x F+3
126
+ np.concatenate([np.zeros((1, 3)), np.ones((1, F))], axis=1) # 1 x F+3
127
+ ],
128
+ axis=0
129
+ )
130
+ inv_delta_C = np.linalg.inv(delta_C)
131
+ return inv_delta_C # F+3 x F+3
132
+
133
+ def _build_P(self, I_r_width, I_r_height):
134
+ I_r_grid_x = (np.arange(-I_r_width, I_r_width, 2) + 1.0) / I_r_width # self.I_r_width
135
+ I_r_grid_y = (np.arange(-I_r_height, I_r_height, 2) + 1.0) / I_r_height # self.I_r_height
136
+ P = np.stack( # self.I_r_width x self.I_r_height x 2
137
+ np.meshgrid(I_r_grid_x, I_r_grid_y),
138
+ axis=2
139
+ )
140
+ return P.reshape([-1, 2]) # n (= self.I_r_width x self.I_r_height) x 2
141
+
142
+ def _build_P_hat(self, F, C, P):
143
+ n = P.shape[0] # n (= self.I_r_width x self.I_r_height)
144
+ P_tile = np.tile(np.expand_dims(P, axis=1), (1, F, 1)) # n x 2 -> n x 1 x 2 -> n x F x 2
145
+ C_tile = np.expand_dims(C, axis=0) # 1 x F x 2
146
+ P_diff = P_tile - C_tile # n x F x 2
147
+ rbf_norm = np.linalg.norm(P_diff, ord=2, axis=2, keepdims=False) # n x F
148
+ rbf = np.multiply(np.square(rbf_norm), np.log(rbf_norm + self.eps)) # n x F
149
+ P_hat = np.concatenate([np.ones((n, 1)), P, rbf], axis=1)
150
+ return P_hat # n x F+3
151
+
152
+ def build_P_prime(self, batch_C_prime):
153
+ """ Generate Grid from batch_C_prime [batch_size x F x 2] """
154
+ batch_size = batch_C_prime.size(0)
155
+ batch_inv_delta_C = self.inv_delta_C.repeat(batch_size, 1, 1)
156
+ batch_P_hat = self.P_hat.repeat(batch_size, 1, 1)
157
+ batch_C_prime_with_zeros = torch.cat((batch_C_prime, torch.zeros(
158
+ batch_size, 3, 2).float().to(device)), dim=1) # batch_size x F+3 x 2
159
+ batch_T = torch.bmm(batch_inv_delta_C, batch_C_prime_with_zeros) # batch_size x F+3 x 2
160
+ batch_P_prime = torch.bmm(batch_P_hat, batch_T) # batch_size x n x 2
161
+ return batch_P_prime # batch_size x n x 2
162
+
163
+
164
+ class VGG_FeatureExtractor(nn.Module):
165
+ """ FeatureExtractor of CRNN (https://arxiv.org/pdf/1507.05717.pdf) """
166
+
167
+ def __init__(self, input_channel, output_channel=512):
168
+ super(VGG_FeatureExtractor, self).__init__()
169
+ self.output_channel = [int(output_channel / 8), int(output_channel / 4),
170
+ int(output_channel / 2), output_channel] # [64, 128, 256, 512]
171
+ self.ConvNet = nn.Sequential(
172
+ nn.Conv2d(input_channel, self.output_channel[0], 3, 1, 1), nn.ReLU(True),
173
+ nn.MaxPool2d(2, 2), # 64x16x50
174
+ nn.Conv2d(self.output_channel[0], self.output_channel[1], 3, 1, 1), nn.ReLU(True),
175
+ nn.MaxPool2d(2, 2), # 128x8x25
176
+ nn.Conv2d(self.output_channel[1], self.output_channel[2], 3, 1, 1), nn.ReLU(True), # 256x8x25
177
+ nn.Conv2d(self.output_channel[2], self.output_channel[2], 3, 1, 1), nn.ReLU(True),
178
+ nn.MaxPool2d((2, 1), (2, 1)), # 256x4x25
179
+ nn.Conv2d(self.output_channel[2], self.output_channel[3], 3, 1, 1, bias=False),
180
+ nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True), # 512x4x25
181
+ nn.Conv2d(self.output_channel[3], self.output_channel[3], 3, 1, 1, bias=False),
182
+ nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True),
183
+ nn.MaxPool2d((2, 1), (2, 1)), # 512x2x25
184
+ nn.Conv2d(self.output_channel[3], self.output_channel[3], 2, 1, 0), nn.ReLU(True)) # 512x1x24
185
+
186
+ def forward(self, input):
187
+ return self.ConvNet(input)
188
+
189
+
190
+ class RCNN_FeatureExtractor(nn.Module):
191
+ """ FeatureExtractor of GRCNN (https://papers.nips.cc/paper/6637-gated-recurrent-convolution-neural-network-for-ocr.pdf) """
192
+
193
+ def __init__(self, input_channel, output_channel=512):
194
+ super(RCNN_FeatureExtractor, self).__init__()
195
+ self.output_channel = [int(output_channel / 8), int(output_channel / 4),
196
+ int(output_channel / 2), output_channel] # [64, 128, 256, 512]
197
+ self.ConvNet = nn.Sequential(
198
+ nn.Conv2d(input_channel, self.output_channel[0], 3, 1, 1), nn.ReLU(True),
199
+ nn.MaxPool2d(2, 2), # 64 x 16 x 50
200
+ GRCL(self.output_channel[0], self.output_channel[0], num_iteration=5, kernel_size=3, pad=1),
201
+ nn.MaxPool2d(2, 2), # 64 x 8 x 25
202
+ GRCL(self.output_channel[0], self.output_channel[1], num_iteration=5, kernel_size=3, pad=1),
203
+ nn.MaxPool2d(2, (2, 1), (0, 1)), # 128 x 4 x 26
204
+ GRCL(self.output_channel[1], self.output_channel[2], num_iteration=5, kernel_size=3, pad=1),
205
+ nn.MaxPool2d(2, (2, 1), (0, 1)), # 256 x 2 x 27
206
+ nn.Conv2d(self.output_channel[2], self.output_channel[3], 2, 1, 0, bias=False),
207
+ nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True)) # 512 x 1 x 26
208
+
209
+ def forward(self, input):
210
+ return self.ConvNet(input)
211
+
212
+
213
+ class ResNet_FeatureExtractor(nn.Module):
214
+ """ FeatureExtractor of FAN (http://openaccess.thecvf.com/content_ICCV_2017/papers/Cheng_Focusing_Attention_Towards_ICCV_2017_paper.pdf) """
215
+
216
+ def __init__(self, input_channel, output_channel=512):
217
+ super(ResNet_FeatureExtractor, self).__init__()
218
+ self.ConvNet = ResNet(input_channel, output_channel, BasicBlock, [1, 2, 5, 3])
219
+
220
+ def forward(self, input):
221
+ return self.ConvNet(input)
222
+
223
+
224
+ # For Gated RCNN
225
+ class GRCL(nn.Module):
226
+
227
+ def __init__(self, input_channel, output_channel, num_iteration, kernel_size, pad):
228
+ super(GRCL, self).__init__()
229
+ self.wgf_u = nn.Conv2d(input_channel, output_channel, 1, 1, 0, bias=False)
230
+ self.wgr_x = nn.Conv2d(output_channel, output_channel, 1, 1, 0, bias=False)
231
+ self.wf_u = nn.Conv2d(input_channel, output_channel, kernel_size, 1, pad, bias=False)
232
+ self.wr_x = nn.Conv2d(output_channel, output_channel, kernel_size, 1, pad, bias=False)
233
+
234
+ self.BN_x_init = nn.BatchNorm2d(output_channel)
235
+
236
+ self.num_iteration = num_iteration
237
+ self.GRCL = [GRCL_unit(output_channel) for _ in range(num_iteration)]
238
+ self.GRCL = nn.Sequential(*self.GRCL)
239
+
240
+ def forward(self, input):
241
+ """ The input of GRCL is consistant over time t, which is denoted by u(0)
242
+ thus wgf_u / wf_u is also consistant over time t.
243
+ """
244
+ wgf_u = self.wgf_u(input)
245
+ wf_u = self.wf_u(input)
246
+ x = F.relu(self.BN_x_init(wf_u))
247
+
248
+ for i in range(self.num_iteration):
249
+ x = self.GRCL[i](wgf_u, self.wgr_x(x), wf_u, self.wr_x(x))
250
+
251
+ return x
252
+
253
+
254
+ class GRCL_unit(nn.Module):
255
+
256
+ def __init__(self, output_channel):
257
+ super(GRCL_unit, self).__init__()
258
+ self.BN_gfu = nn.BatchNorm2d(output_channel)
259
+ self.BN_grx = nn.BatchNorm2d(output_channel)
260
+ self.BN_fu = nn.BatchNorm2d(output_channel)
261
+ self.BN_rx = nn.BatchNorm2d(output_channel)
262
+ self.BN_Gx = nn.BatchNorm2d(output_channel)
263
+
264
+ def forward(self, wgf_u, wgr_x, wf_u, wr_x):
265
+ G_first_term = self.BN_gfu(wgf_u)
266
+ G_second_term = self.BN_grx(wgr_x)
267
+ G = F.sigmoid(G_first_term + G_second_term)
268
+
269
+ x_first_term = self.BN_fu(wf_u)
270
+ x_second_term = self.BN_Gx(self.BN_rx(wr_x) * G)
271
+ x = F.relu(x_first_term + x_second_term)
272
+
273
+ return x
274
+
275
+
276
+ class BasicBlock(nn.Module):
277
+ expansion = 1
278
+
279
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
280
+ super(BasicBlock, self).__init__()
281
+ self.conv1 = self._conv3x3(inplanes, planes)
282
+ self.bn1 = nn.BatchNorm2d(planes)
283
+ self.conv2 = self._conv3x3(planes, planes)
284
+ self.bn2 = nn.BatchNorm2d(planes)
285
+ self.relu = nn.ReLU(inplace=True)
286
+ self.downsample = downsample
287
+ self.stride = stride
288
+
289
+ def _conv3x3(self, in_planes, out_planes, stride=1):
290
+ "3x3 convolution with padding"
291
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
292
+ padding=1, bias=False)
293
+
294
+ def forward(self, x):
295
+ residual = x
296
+
297
+ out = self.conv1(x)
298
+ out = self.bn1(out)
299
+ out = self.relu(out)
300
+
301
+ out = self.conv2(out)
302
+ out = self.bn2(out)
303
+
304
+ if self.downsample is not None:
305
+ residual = self.downsample(x)
306
+ out += residual
307
+ out = self.relu(out)
308
+
309
+ return out
310
+
311
+
312
+ class ResNet(nn.Module):
313
+
314
+ def __init__(self, input_channel, output_channel, block, layers):
315
+ super(ResNet, self).__init__()
316
+
317
+ self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel]
318
+
319
+ self.inplanes = int(output_channel / 8)
320
+ self.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 16),
321
+ kernel_size=3, stride=1, padding=1, bias=False)
322
+ self.bn0_1 = nn.BatchNorm2d(int(output_channel / 16))
323
+ self.conv0_2 = nn.Conv2d(int(output_channel / 16), self.inplanes,
324
+ kernel_size=3, stride=1, padding=1, bias=False)
325
+ self.bn0_2 = nn.BatchNorm2d(self.inplanes)
326
+ self.relu = nn.ReLU(inplace=True)
327
+
328
+ self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
329
+ self.layer1 = self._make_layer(block, self.output_channel_block[0], layers[0])
330
+ self.conv1 = nn.Conv2d(self.output_channel_block[0], self.output_channel_block[
331
+ 0], kernel_size=3, stride=1, padding=1, bias=False)
332
+ self.bn1 = nn.BatchNorm2d(self.output_channel_block[0])
333
+
334
+ self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
335
+ self.layer2 = self._make_layer(block, self.output_channel_block[1], layers[1], stride=1)
336
+ self.conv2 = nn.Conv2d(self.output_channel_block[1], self.output_channel_block[
337
+ 1], kernel_size=3, stride=1, padding=1, bias=False)
338
+ self.bn2 = nn.BatchNorm2d(self.output_channel_block[1])
339
+
340
+ self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=(2, 1), padding=(0, 1))
341
+ self.layer3 = self._make_layer(block, self.output_channel_block[2], layers[2], stride=1)
342
+ self.conv3 = nn.Conv2d(self.output_channel_block[2], self.output_channel_block[
343
+ 2], kernel_size=3, stride=1, padding=1, bias=False)
344
+ self.bn3 = nn.BatchNorm2d(self.output_channel_block[2])
345
+
346
+ self.layer4 = self._make_layer(block, self.output_channel_block[3], layers[3], stride=1)
347
+ self.conv4_1 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[
348
+ 3], kernel_size=2, stride=(2, 1), padding=(0, 1), bias=False)
349
+ self.bn4_1 = nn.BatchNorm2d(self.output_channel_block[3])
350
+ self.conv4_2 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[
351
+ 3], kernel_size=2, stride=1, padding=0, bias=False)
352
+ self.bn4_2 = nn.BatchNorm2d(self.output_channel_block[3])
353
+
354
+ def _make_layer(self, block, planes, blocks, stride=1):
355
+ downsample = None
356
+ if stride != 1 or self.inplanes != planes * block.expansion:
357
+ downsample = nn.Sequential(
358
+ nn.Conv2d(self.inplanes, planes * block.expansion,
359
+ kernel_size=1, stride=stride, bias=False),
360
+ nn.BatchNorm2d(planes * block.expansion),
361
+ )
362
+
363
+ layers = []
364
+ layers.append(block(self.inplanes, planes, stride, downsample))
365
+ self.inplanes = planes * block.expansion
366
+ for i in range(1, blocks):
367
+ layers.append(block(self.inplanes, planes))
368
+
369
+ return nn.Sequential(*layers)
370
+
371
+ def forward(self, x):
372
+ x = self.conv0_1(x)
373
+ x = self.bn0_1(x)
374
+ x = self.relu(x)
375
+ x = self.conv0_2(x)
376
+ x = self.bn0_2(x)
377
+ x = self.relu(x)
378
+
379
+ x = self.maxpool1(x)
380
+ x = self.layer1(x)
381
+ x = self.conv1(x)
382
+ x = self.bn1(x)
383
+ x = self.relu(x)
384
+
385
+ x = self.maxpool2(x)
386
+ x = self.layer2(x)
387
+ x = self.conv2(x)
388
+ x = self.bn2(x)
389
+ x = self.relu(x)
390
+
391
+ x = self.maxpool3(x)
392
+ x = self.layer3(x)
393
+ x = self.conv3(x)
394
+ x = self.bn3(x)
395
+ x = self.relu(x)
396
+
397
+ x = self.layer4(x)
398
+ x = self.conv4_1(x)
399
+ x = self.bn4_1(x)
400
+ x = self.relu(x)
401
+ x = self.conv4_2(x)
402
+ x = self.bn4_2(x)
403
+ x = self.relu(x)
404
+
405
+ return x
406
+
407
+
408
+ class BidirectionalLSTM(nn.Module):
409
+
410
+ def __init__(self, input_size, hidden_size, output_size):
411
+ super(BidirectionalLSTM, self).__init__()
412
+ self.rnn = nn.LSTM(input_size, hidden_size, bidirectional=True, batch_first=True)
413
+ self.linear = nn.Linear(hidden_size * 2, output_size)
414
+
415
+ def forward(self, input):
416
+ """
417
+ input : visual feature [batch_size x T x input_size]
418
+ output : contextual feature [batch_size x T x output_size]
419
+ """
420
+ try:
421
+ self.rnn.flatten_parameters()
422
+ except:
423
+ pass
424
+ recurrent, _ = self.rnn(input) # batch_size x T x input_size -> batch_size x T x (2*hidden_size)
425
+ output = self.linear(recurrent) # batch_size x T x output_size
426
+ return output
427
+
428
+
429
+ class Attention(nn.Module):
430
+
431
+ def __init__(self, input_size, hidden_size, num_classes):
432
+ super(Attention, self).__init__()
433
+ self.attention_cell = AttentionCell(input_size, hidden_size, num_classes)
434
+ self.hidden_size = hidden_size
435
+ self.num_classes = num_classes
436
+ self.generator = nn.Linear(hidden_size, num_classes)
437
+
438
+ def _char_to_onehot(self, input_char, onehot_dim=38):
439
+ input_char = input_char.unsqueeze(1)
440
+ batch_size = input_char.size(0)
441
+ one_hot = torch.FloatTensor(batch_size, onehot_dim).zero_().to(device)
442
+ one_hot = one_hot.scatter_(1, input_char, 1)
443
+ return one_hot
444
+
445
+ def forward(self, batch_H, text, is_train=True, batch_max_length=25):
446
+ """
447
+ input:
448
+ batch_H : contextual_feature H = hidden state of encoder. [batch_size x num_steps x num_classes]
449
+ text : the text-index of each image. [batch_size x (max_length+1)]. +1 for [GO] token. text[:, 0] = [GO].
450
+ output: probability distribution at each step [batch_size x num_steps x num_classes]
451
+ """
452
+ batch_size = batch_H.size(0)
453
+ num_steps = batch_max_length + 1 # +1 for [s] at end of sentence.
454
+
455
+ output_hiddens = torch.FloatTensor(batch_size, num_steps, self.hidden_size).fill_(0).to(device)
456
+ hidden = (torch.FloatTensor(batch_size, self.hidden_size).fill_(0).to(device),
457
+ torch.FloatTensor(batch_size, self.hidden_size).fill_(0).to(device))
458
+
459
+ if is_train:
460
+ for i in range(num_steps):
461
+ # one-hot vectors for a i-th char. in a batch
462
+ char_onehots = self._char_to_onehot(text[:, i], onehot_dim=self.num_classes)
463
+ # hidden : decoder's hidden s_{t-1}, batch_H : encoder's hidden H, char_onehots : one-hot(y_{t-1})
464
+ hidden, alpha = self.attention_cell(hidden, batch_H, char_onehots)
465
+ output_hiddens[:, i, :] = hidden[0] # LSTM hidden index (0: hidden, 1: Cell)
466
+ probs = self.generator(output_hiddens)
467
+
468
+ else:
469
+ targets = torch.LongTensor(batch_size).fill_(0).to(device) # [GO] token
470
+ probs = torch.FloatTensor(batch_size, num_steps, self.num_classes).fill_(0).to(device)
471
+
472
+ for i in range(num_steps):
473
+ char_onehots = self._char_to_onehot(targets, onehot_dim=self.num_classes)
474
+ hidden, alpha = self.attention_cell(hidden, batch_H, char_onehots)
475
+ probs_step = self.generator(hidden[0])
476
+ probs[:, i, :] = probs_step
477
+ _, next_input = probs_step.max(1)
478
+ targets = next_input
479
+
480
+ return probs # batch_size x num_steps x num_classes
481
+
482
+
483
+ class AttentionCell(nn.Module):
484
+
485
+ def __init__(self, input_size, hidden_size, num_embeddings):
486
+ super(AttentionCell, self).__init__()
487
+ self.i2h = nn.Linear(input_size, hidden_size, bias=False)
488
+ self.h2h = nn.Linear(hidden_size, hidden_size) # either i2i or h2h should have bias
489
+ self.score = nn.Linear(hidden_size, 1, bias=False)
490
+ self.rnn = nn.LSTMCell(input_size + num_embeddings, hidden_size)
491
+ self.hidden_size = hidden_size
492
+
493
+ def forward(self, prev_hidden, batch_H, char_onehots):
494
+ # [batch_size x num_encoder_step x num_channel] -> [batch_size x num_encoder_step x hidden_size]
495
+ batch_H_proj = self.i2h(batch_H)
496
+ prev_hidden_proj = self.h2h(prev_hidden[0]).unsqueeze(1)
497
+ e = self.score(torch.tanh(batch_H_proj + prev_hidden_proj)) # batch_size x num_encoder_step * 1
498
+
499
+ alpha = F.softmax(e, dim=1)
500
+ context = torch.bmm(alpha.permute(0, 2, 1), batch_H).squeeze(1) # batch_size x num_channel
501
+ concat_context = torch.cat([context, char_onehots], 1) # batch_size x (num_channel + num_embedding)
502
+ cur_hidden = self.rnn(concat_context, prev_hidden)
503
+ return cur_hidden, alpha
504
+
505
+
506
+ class Model(nn.Module):
507
+
508
+ def __init__(self, input_channel, output_channel, hidden_size, num_class):
509
+ super(Model, self).__init__()
510
+
511
+
512
+ """ FeatureExtraction """
513
+ self.FeatureExtraction = VGG_FeatureExtractor(input_channel, output_channel)
514
+ self.FeatureExtraction_output = output_channel # int(imgH/16-1) * 512
515
+ self.AdaptiveAvgPool = nn.AdaptiveAvgPool2d((None, 1)) # Transform final (imgH/16-1) -> 1
516
+
517
+ """ Sequence modeling"""
518
+ self.SequenceModeling = nn.Sequential(
519
+ BidirectionalLSTM(self.FeatureExtraction_output, hidden_size, hidden_size),
520
+ BidirectionalLSTM(hidden_size, hidden_size, hidden_size))
521
+ self.SequenceModeling_output = hidden_size
522
+
523
+
524
+ self.Prediction = nn.Linear(self.SequenceModeling_output, num_class)
525
+
526
+ def forward(self, input, text):
527
+
528
+ """ Feature extraction stage """
529
+ visual_feature = self.FeatureExtraction(input)
530
+ visual_feature = self.AdaptiveAvgPool(visual_feature.permute(0, 3, 1, 2)) # [b, c, h, w] -> [b, w, c, h]
531
+ visual_feature = visual_feature.squeeze(3)
532
+
533
+ """ Sequence modeling stage """
534
+ contextual_feature = self.SequenceModeling(visual_feature)
535
+
536
+ prediction = self.Prediction(contextual_feature.contiguous())
537
+
538
+ return prediction
models/best_norm_ED.yaml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ number: '0123456789'
2
+ symbol: "!?.,:;'#()<>+-/*=%$»« "
3
+ lang_char: 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯЁабвгдежзийклмнопрстуфхцчшщъыьэюяёӘҒҚҢӨҰҮІҺәғқңөұүіһABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
4
+ experiment_name: 'kz_synthtiger_v7'
5
+ train_data: '../../synthtiger_kz/results/train_v7'
6
+ valid_data: '../../synthtiger_kz/results/test_v7'
7
+ manualSeed: 1111
8
+ workers: 6
9
+ batch_size: 96 #32
10
+ num_iter: 100000
11
+ valInterval: 1000
12
+ saved_model: '' #'saved_models/en_filtered/iter_300000.pth'
13
+ FT: False
14
+ optim: False # default is Adadelta
15
+ lr: 1.
16
+ beta1: 0.9
17
+ rho: 0.95
18
+ eps: 0.00000001
19
+ grad_clip: 5
20
+ #Data processing
21
+ select_data: 'images' # this is dataset folder in train_data
22
+ batch_ratio: '1'
23
+ total_data_usage_ratio: 1.0
24
+ batch_max_length: 34
25
+ imgH: 64
26
+ imgW: 600
27
+ rgb: False
28
+ sensitive: True
29
+ PAD: True
30
+ contrast_adjust: 0.0
31
+ data_filtering_off: False
32
+ # Model Architecture
33
+ Transformation: 'None'
34
+ FeatureExtraction: 'VGG'
35
+ SequenceModeling: 'BiLSTM'
36
+ Prediction: 'CTC'
37
+ num_fiducial: 20
38
+ input_channel: 1
39
+ output_channel: 256
40
+ hidden_size: 256
41
+ decode: 'greedy'
42
+ new_prediction: False
43
+ freeze_FeatureFxtraction: False
44
+ freeze_SequenceModeling: False
45
+
46
+ network_params:
47
+ input_channel: 1
48
+ output_channel: 256
49
+ hidden_size: 256
50
+ lang_list:
51
+ - 'en'
52
+ character_list: 0123456789!?.,:;'#()<>+-/*=%$»« АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯЁабвгдежзийклмнопрстуфхцчшщъыьэюяёӘҒҚҢӨҰҮІҺәғқңөұүіһABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
models/craft_mlt_25k.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a5efbfb48b4081100544e75e1e2b57f8de3d84f213004b14b85fd4b3748db17
3
+ size 83152330
requirements.txt ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ altair~=5.1.2
2
+ appnope~=0.1.3
3
+ asttokens~=2.4.0
4
+ attrs~=23.1.0
5
+ backcall~=0.2.0
6
+ backports.functools-lru-cache~=1.6.5
7
+ blinker~=1.6.3
8
+ Brotli~=1.1.0
9
+ cachetools~=5.3.1
10
+ certifi~=2023.7.22
11
+ charset-normalizer~=3.3.0
12
+ click~=8.1.7
13
+ colorama~=0.4.6
14
+ comm~=0.1.4
15
+ debugpy~=1.8.0
16
+ decorator~=5.1.1
17
+ easyocr~=1.7.1
18
+ exceptiongroup~=1.1.3
19
+ executing~=1.2.0
20
+ filelock~=3.12.4
21
+ gitdb~=4.0.10
22
+ GitPython~=3.1.37
23
+ gmpy2~=2.1.2
24
+ idna~=3.4
25
+ imagecodecs~=2023.9.18
26
+ imageio~=2.31.5
27
+ importlib-metadata~=6.8.0
28
+ importlib-resources~=6.1.0
29
+ ipykernel~=6.25.2
30
+ ipython~=8.16.1
31
+ ipywidgets~=8.1.1
32
+ jedi~=0.19.1
33
+ Jinja2~=3.1.2
34
+ jsonschema~=4.19.1
35
+ jsonschema-specifications~=2023.7.1
36
+ jupyter_client~=8.3.1
37
+ jupyter_core~=5.3.2
38
+ jupyterlab-widgets~=3.0.9
39
+ lazy_loader~=0.3
40
+ markdown-it-py~=3.0.0
41
+ MarkupSafe~=2.1.3
42
+ matplotlib-inline~=0.1.6
43
+ mdurl~=0.1.0
44
+ mpmath~=1.3.0
45
+ nest-asyncio~=1.5.6
46
+ networkx~=3.1
47
+ numpy~=1.26.0
48
+ opencv-python~=4.8.1
49
+ packaging~=23.2
50
+ pandas~=2.1.1
51
+ parso~=0.8.3
52
+ pexpect~=4.8.0
53
+ pickleshare~=0.7.5
54
+ Pillow~=10.0.1
55
+ pip~=23.2.1
56
+ pkgutil_resolve_name~=1.3.10
57
+ platformdirs~=3.11.0
58
+ prompt-toolkit~=3.0.39
59
+ protobuf~=4.23.4
60
+ psutil~=5.9.5
61
+ ptyprocess~=0.7.0
62
+ pure-eval~=0.2.2
63
+ pyarrow~=13.0.0
64
+ pyclipper~=1.3.0.post5
65
+ pydeck~=0.8.0b4
66
+ Pygments~=2.16.1
67
+ PySocks~=1.7.1
68
+ python-bidi~=0.4.2
69
+ python-dateutil~=2.8.2
70
+ pytz~=2023.3.post1
71
+ PyWavelets~=1.4.1
72
+ PyYAML~=6.0.1
73
+ pyzmq~=25.1.1
74
+ referencing~=0.30.2
75
+ requests~=2.31.0
76
+ rich~=13.6.0
77
+ rpds-py~=0.10.4
78
+ scikit-image~=0.22.0
79
+ scipy~=1.11.3
80
+ setuptools~=68.2.2
81
+ shapely~=2.0.1
82
+ six~=1.16.0
83
+ smmap~=3.0.5
84
+ stack-data~=0.6.2
85
+ streamlit~=1.27.2
86
+ sympy~=1.12
87
+ tenacity~=8.2.3
88
+ tifffile~=2023.9.26
89
+ toml~=0.10.2
90
+ toolz~=0.12.0
91
+ torch~=2.0.0.post2
92
+ torchvision~=0.15.2a0
93
+ tornado~=6.3.3
94
+ tqdm~=4.66.1
95
+ traitlets~=5.11.2
96
+ typing_extensions~=4.8.0
97
+ tzdata~=2023.3
98
+ tzlocal~=5.1
99
+ urllib3~=2.0.6
100
+ validators~=0.22.0
101
+ watchdog~=3.0.0
102
+ wcwidth~=0.2.8
103
+ wheel~=0.41.2
104
+ widgetsnbextension~=4.0.9
105
+ zipp~=3.17.0
106
+ pdf2image~=1.16.3
107
+ pdfplumber
108
+ PyMuPDF
upload_image.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import streamlit as st
4
+ import easyocr
5
+ import PIL
6
+ from PIL import Image, ImageDraw
7
+ from matplotlib import pyplot as plt
8
+
9
+
10
+ # main title
11
+ st.set_page_config(layout="wide")
12
+ st.title("Get text from image with EasyOCR")
13
+ # subtitle
14
+ st.markdown("## EasyOCRR with Streamlit")
15
+ col1, col2 = st.columns(2)
16
+ uploaded_file = col1.file_uploader("Upload your file here ",type=['png','jpeg','jpg'])
17
+ if uploaded_file is not None:
18
+ col1.image(uploaded_file) #display
19
+ #print("GOGO ",type(uploaded_file))
20
+ image = Image.open(uploaded_file)
21
+ reader = easyocr.Reader(['tr','en'], gpu=False)
22
+ result = reader.readtext(np.array(image),paragraph=True) # turn image to numpy array
23
+ #print(len(result))
24
+ result_text = "\n\n".join([item[1] for item in result])
25
+ col2.markdown(result_text)