github-actions[bot] commited on
Commit
9e9a60d
·
0 Parent(s):

Deploy to Space

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.github/workflows/deploy-to-spaces.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Deploy to Spaces
2
+
3
+ on:
4
+ push:
5
+ branches: [ hfspace ]
6
+
7
+ jobs:
8
+ deploy:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ with:
13
+ fetch-depth: 1
14
+ ref: hfspace
15
+ lfs: true
16
+
17
+ - name: Configure Git
18
+ run: |
19
+ git config --global user.email "github-actions[bot]@users.noreply.github.com"
20
+ git config --global user.name "github-actions[bot]"
21
+ git lfs install
22
+
23
+ - name: Push to Space
24
+ env:
25
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
26
+ run: |
27
+ git checkout --orphan temp_branch
28
+ git add -A
29
+ git commit -m "Deploy to Space"
30
+ git lfs push --all https://jayllfpt:$HF_TOKEN@huggingface.co/spaces/jayllfpt/table2html temp_branch
31
+ git push -f https://jayllfpt:$HF_TOKEN@huggingface.co/spaces/jayllfpt/table2html temp_branch:main
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: table2html
3
+ emoji: 🐧
4
+ colorFrom: pink
5
+ colorTo: blue
6
+ sdk: streamlit
7
+ sdk_version: 1.40.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import streamlit as st
3
+ from table2html import Table2HTML
4
+ from table2html.source import visualize_boxes, crop_image
5
+ import numpy as np
6
+ import time
7
+ import os
8
+ import tempfile
9
+ import fitz # PyMuPDF
10
+ from PIL import Image
11
+
12
+
13
+ default_configs = {
14
+ 'table_detection': {
15
+ 'model_path': 'models/table_detection.pt',
16
+ 'confidence_threshold': 0.25,
17
+ 'iou_threshold': 0.7
18
+ },
19
+ 'column_detection': {
20
+ 'model_path': 'models/column_detection.pt',
21
+ 'confidence_threshold': 0.25,
22
+ 'iou_threshold': 0.7,
23
+ 'task': 'detect'
24
+ },
25
+ 'row_detection': {
26
+ 'model_path': 'models/row_detection.pt',
27
+ 'confidence_threshold': 0.25,
28
+ 'iou_threshold': 0.7,
29
+ 'task': 'detect'
30
+ },
31
+ 'table_crop_padding': 15
32
+ }
33
+
34
+ thumbnail_columns = 5
35
+
36
+
37
+ def initialize_session_state():
38
+ if 'table_detections' not in st.session_state:
39
+ st.session_state.table_detections = []
40
+ if 'structure_detections' not in st.session_state:
41
+ st.session_state.structure_detections = []
42
+ if 'cropped_tables' not in st.session_state:
43
+ st.session_state.cropped_tables = []
44
+ if 'html_tables' not in st.session_state:
45
+ st.session_state.html_tables = []
46
+ if 'detection_data' not in st.session_state:
47
+ st.session_state.detection_data = []
48
+ if 'current_image' not in st.session_state:
49
+ st.session_state.current_image = None
50
+ if 'configs' not in st.session_state:
51
+ st.session_state.configs = default_configs
52
+
53
+
54
+ def clear_results():
55
+ st.session_state.table_detections = []
56
+ st.session_state.structure_detections = []
57
+ st.session_state.cropped_tables = []
58
+ st.session_state.html_tables = []
59
+
60
+
61
+ def detect_update_results(image, configs):
62
+ table2html = Table2HTML(
63
+ table_detection_config=configs["table_detection"],
64
+ row_detection_config=configs["row_detection"],
65
+ column_detection_config=configs["column_detection"]
66
+ )
67
+ detection_data = table2html(image, configs["table_crop_padding"])
68
+
69
+ if len(detection_data) == 0:
70
+ st.warning("No tables detected on this page.")
71
+ return
72
+
73
+ # Clear previous results
74
+ st.session_state.detection_data = detection_data
75
+
76
+ for data in detection_data:
77
+ # Store table detection visualization
78
+ table_detection = visualize_boxes(
79
+ image.copy(),
80
+ [data["table_bbox"]],
81
+ color=(0, 0, 255),
82
+ thickness=2
83
+ )
84
+ st.session_state.table_detections.append(table_detection)
85
+
86
+ # Store cropped table
87
+ cropped_table = crop_image(
88
+ image, data["table_bbox"], configs["table_crop_padding"])
89
+ st.session_state.cropped_tables.append(cropped_table)
90
+
91
+ # Store structure detection visualization
92
+ structure_detection = visualize_boxes(
93
+ cropped_table.copy(),
94
+ [cell['box'] for cell in data['cells']],
95
+ color=(0, 255, 0),
96
+ thickness=1
97
+ )
98
+ st.session_state.structure_detections.append(structure_detection)
99
+
100
+ # Store HTML
101
+ st.session_state.html_tables.append(data["html"])
102
+
103
+
104
+ def inference_one_image(image, configs):
105
+ clear_results()
106
+ with st.spinner("Processing..."):
107
+ start_time = time.time()
108
+
109
+ try:
110
+ # Update process_image call to include all model paths
111
+ detect_update_results(image, configs)
112
+
113
+ # Clean up temporary files if using custom models
114
+ for model_type, config in configs.items():
115
+ if f"{model_type}_option" in st.session_state and \
116
+ st.session_state[f"{model_type}_option"] == "custom":
117
+ os.unlink(config["model_path"])
118
+
119
+ execution_time = time.time() - start_time
120
+ st.success(
121
+ f"Processing completed in {execution_time:.2f} seconds")
122
+ except Exception as e:
123
+ st.error(f"Error processing image: {str(e)}")
124
+ # Clean up temporary files on error
125
+ for model_type, config in configs.items():
126
+ if f"{model_type}_option" in st.session_state and \
127
+ st.session_state[f"{model_type}_option"] == "custom":
128
+ os.unlink(config["model_path"])
129
+
130
+
131
+ def main():
132
+ initialize_session_state()
133
+ st.set_page_config(layout="wide")
134
+
135
+ # Add page selection
136
+ page = st.sidebar.radio("Select Page", ["Inference", "Configuration"])
137
+
138
+ if page == "Inference":
139
+ st.title("Table Detection and Recognition")
140
+
141
+ # Image Upload Section
142
+ st.subheader("Image Upload")
143
+ uploaded_file = st.file_uploader(
144
+ "Choose an image or PDF file",
145
+ type=['jpg', 'jpeg', 'png', 'pdf']
146
+ )
147
+
148
+ # Get configurations from session state
149
+ configs = st.session_state.get('configs', default_configs)
150
+
151
+ current_image = None
152
+
153
+ if uploaded_file is not None and all(configs.values()):
154
+ if uploaded_file.type == "application/pdf":
155
+ # Convert PDF to images
156
+ pdf_bytes = uploaded_file.read()
157
+ pdf_images = []
158
+
159
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
160
+
161
+ for page_num in range(doc.page_count):
162
+ page = doc[page_num]
163
+ pix = page.get_pixmap(dpi=200)
164
+ pil_image = Image.frombytes(
165
+ "RGB", [pix.width, pix.height], pix.samples)
166
+ img_array = np.array(pil_image)
167
+ pdf_images.append(img_array)
168
+
169
+ # Show thumbnails
170
+ st.write("Select a page to process:")
171
+ cols = st.columns(thumbnail_columns)
172
+ for idx, img in enumerate(pdf_images):
173
+ with cols[idx % thumbnail_columns]:
174
+ st.image(img, width=150, use_container_width=True)
175
+ if st.button(f"Process Page {idx+1}"):
176
+ current_image = img
177
+ st.session_state.current_image = img
178
+ inference_one_image(
179
+ current_image, configs)
180
+ else:
181
+ # Handle regular image upload
182
+ file_bytes = np.asarray(
183
+ bytearray(uploaded_file.read()), dtype=np.uint8)
184
+ current_image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
185
+ st.session_state.current_image = current_image
186
+
187
+ # Process button
188
+ if st.button("Process Image"):
189
+ inference_one_image(
190
+ current_image, configs)
191
+
192
+ if len(st.session_state.cropped_tables) > 0:
193
+ st.header("Results")
194
+
195
+ # General Results Section
196
+ st.subheader("General Results")
197
+ gen_img_col, gen_html_col = st.columns([1, 1])
198
+
199
+ with gen_img_col:
200
+ show_all_detections = st.toggle(
201
+ "Show Table Detections",
202
+ value=False,
203
+ key="show_all_detections"
204
+ )
205
+
206
+ # Display either original image or detection visualization
207
+ if show_all_detections and len(st.session_state.detection_data) > 0:
208
+ # Create visualization with all table detections
209
+ all_tables_viz = visualize_boxes(
210
+ st.session_state.current_image.copy(),
211
+ [data["table_bbox"]
212
+ for data in st.session_state.detection_data],
213
+ color=(0, 0, 255),
214
+ thickness=2
215
+ )
216
+ st.image(
217
+ all_tables_viz,
218
+ caption="All Table Detections",
219
+ use_container_width=True
220
+ )
221
+ else:
222
+ st.image(
223
+ st.session_state.current_image,
224
+ caption="Original Image",
225
+ use_container_width=True
226
+ )
227
+
228
+ with gen_html_col:
229
+ st.markdown("### All HTML Tables:")
230
+ # Combine all HTML tables
231
+ all_html = "\n".join(st.session_state.html_tables)
232
+ st.markdown(all_html, unsafe_allow_html=True)
233
+
234
+ # Download all HTML tables
235
+ combined_html = "<!DOCTYPE html><html><body>\n" + all_html + "\n</body></html>"
236
+ st.download_button(
237
+ label="Download All Tables HTML",
238
+ data=combined_html,
239
+ file_name="all_tables.html",
240
+ mime="text/html",
241
+ key="download_all_btn"
242
+ )
243
+
244
+ st.divider()
245
+
246
+ # Detailed Results Section
247
+ show_details = st.toggle("Show Detailed Results", value=False)
248
+
249
+ if show_details:
250
+ st.subheader("Detailed Results")
251
+ for idx in range(len(st.session_state.cropped_tables)):
252
+ st.subheader(f"Table {idx + 1}")
253
+
254
+ # Visualization controls for each table
255
+ control_col1, control_col2 = st.columns([1, 1])
256
+ with control_col1:
257
+ show_table_detection = st.toggle(
258
+ f"Show Table Detection for Table {idx + 1}",
259
+ value=False,
260
+ key=f"table_detection_{idx}"
261
+ )
262
+ with control_col2:
263
+ show_structure_detection = st.toggle(
264
+ f"Show Structure Detection for Table {idx + 1}",
265
+ value=False,
266
+ key=f"structure_detection_{idx}"
267
+ )
268
+
269
+ # Create columns for each table result
270
+ img_col, html_col = st.columns([1, 1])
271
+
272
+ with img_col:
273
+ # Show either the cropped table or visualizations based on toggles
274
+ if show_table_detection:
275
+ st.image(
276
+ st.session_state.table_detections[idx],
277
+ caption="Table Detection",
278
+ use_container_width=True
279
+ )
280
+ if show_structure_detection:
281
+ st.image(
282
+ st.session_state.structure_detections[idx],
283
+ caption="Structure Detection",
284
+ use_container_width=True
285
+ )
286
+ if not show_table_detection and not show_structure_detection:
287
+ st.image(
288
+ st.session_state.cropped_tables[idx],
289
+ caption="Cropped Table",
290
+ use_container_width=True
291
+ )
292
+
293
+ with html_col:
294
+ st.markdown("### HTML Output:")
295
+ st.markdown(
296
+ st.session_state.html_tables[idx],
297
+ unsafe_allow_html=True
298
+ )
299
+ st.download_button(
300
+ label=f"Download Table {idx + 1} HTML",
301
+ data=st.session_state.html_tables[idx],
302
+ file_name=f"table_{idx + 1}.html",
303
+ mime="text/html",
304
+ key=f"download_btn_{idx}"
305
+ )
306
+
307
+ st.divider()
308
+
309
+ else: # Configuration page
310
+ st.title("Model Configuration")
311
+
312
+ # Model selection options
313
+ model_types = ["Table Detection", "Column Detection", "Row Detection"]
314
+ configs = {} # Store both paths and thresholds
315
+
316
+ for idx, model_type in enumerate(model_types):
317
+ st.markdown(f"### {model_type}")
318
+ key_prefix = model_type.lower().replace(" ", "_")
319
+
320
+ # Model file selection
321
+ model_option = st.radio(
322
+ f"Choose {model_type} Model",
323
+ options=["default", "custom"],
324
+ horizontal=True,
325
+ key=f"{key_prefix}_option"
326
+ )
327
+
328
+ if model_option == "default":
329
+ default_path = f"models/{key_prefix}.pt"
330
+ configs[key_prefix] = {"model_path": default_path}
331
+ st.info(f"Using default model: {default_path}")
332
+ else:
333
+ model_upload = st.file_uploader(
334
+ f"Choose {model_type} Model File (.pt)",
335
+ type=['pt'],
336
+ key=f"{key_prefix}_upload"
337
+ )
338
+ if model_upload:
339
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pt') as tmp_file:
340
+ tmp_file.write(model_upload.getvalue())
341
+ configs[key_prefix] = {
342
+ "model_path": tmp_file.name}
343
+ else:
344
+ configs[key_prefix] = {"model_path": None}
345
+ st.warning(
346
+ f"Please upload a {model_type.lower()} model file")
347
+
348
+ # Add threshold controls
349
+ thresh_col1, thresh_col2 = st.columns(2)
350
+ with thresh_col1:
351
+ conf_threshold = st.slider(
352
+ f"{model_type} Confidence Threshold",
353
+ min_value=0.0,
354
+ max_value=1.0,
355
+ value=0.25,
356
+ step=0.05,
357
+ key=f"{key_prefix}_conf_threshold"
358
+ )
359
+ with thresh_col2:
360
+ iou_threshold = st.slider(
361
+ f"{model_type} IOU Threshold",
362
+ min_value=0.0,
363
+ max_value=1.0,
364
+ value=0.7,
365
+ step=0.05,
366
+ key=f"{key_prefix}_iou_threshold"
367
+ )
368
+
369
+ if configs[key_prefix]["model_path"]:
370
+ configs[key_prefix].update({
371
+ "confidence_threshold": conf_threshold,
372
+ "iou_threshold": iou_threshold
373
+ })
374
+ # Add task field for row and column detection
375
+ if key_prefix in ["column_detection", "row_detection"]:
376
+ configs[key_prefix]["task"] = "detect"
377
+
378
+ st.divider()
379
+
380
+ # Padding input below the model configurations
381
+ table_crop_padding = st.number_input(
382
+ "Table Crop Padding",
383
+ value=15,
384
+ min_value=0,
385
+ max_value=100
386
+ )
387
+
388
+ # Save configurations to session state
389
+ if st.button("Save Configuration"):
390
+ st.session_state.configs = configs
391
+ st.success("Configuration saved successfully!")
392
+
393
+
394
+ if __name__ == "__main__":
395
+ main()
images/PMC1156947_3.jpg ADDED
models/column_detection.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e15f9f0ef4de361d880e359c899e50ee6c0f6d26d9a7dfa41b6d46f94c8817a
3
+ size 40499813
models/column_segmentation.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d5b57c2b2ab7dfb2b7a05ff41ef4b80d1eceb44274dc1e0acaadf9ba217e916
3
+ size 45142063
models/row_detection.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3fe6d5360016dd2d426d3971578ca6806557e1ee64379c56a97e79ba0d2e2ed1
3
+ size 40499813
models/row_segmentation.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db22b415fd54ff5f32f3b83f05a95ecf3e4093c4a174fc3fceddb2cd4028e12f
3
+ size 45131055
models/table_detection.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d3701d0c42ac395423089965a8b6e16e4af292ccc3054ae016ea709833f014
3
+ size 19172627
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ table2html
2
+ streamlit
3
+ pymupdf
usage.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from table2html.source import visualize_boxes
2
+ from table2html.source import crop_image
3
+ from table2html import Table2HTML
4
+ import cv2
5
+
6
+
7
+ table_crop_padding = 15
8
+
9
+ table_config = {
10
+
11
+ }
12
+
13
+ row_config = {
14
+
15
+ }
16
+
17
+ column_config = {
18
+
19
+ }
20
+
21
+ table2html = Table2HTML(table_config, row_config, column_config)
22
+
23
+ image = cv2.imread(
24
+ r"C:\Users\jayll\Downloads\no_tables.jpg")
25
+
26
+ detection_data = table2html(image, table_crop_padding)
27
+
28
+ for i, data in enumerate(detection_data):
29
+ table_image = crop_image(image, data["table_bbox"], table_crop_padding)
30
+ cv2.imwrite(
31
+ "table_detection.jpg",
32
+ visualize_boxes(
33
+ image,
34
+ [data["table_bbox"]],
35
+ color=(0, 0, 255),
36
+ thickness=1
37
+ )
38
+ )
39
+ cv2.imwrite(
40
+ "structure_detection.jpg",
41
+ visualize_boxes(
42
+ table_image,
43
+ [cell['box'] for cell in data['cells']],
44
+ color=(0, 255, 0),
45
+ thickness=1
46
+ )
47
+ )
48
+
49
+ with open(f"table_{i}.html", "w") as f:
50
+ f.write(data["html"])