Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ·
9e9a60d
0
Parent(s):
Deploy to Space
Browse filesFiles changed (13)
- .gitattributesAdded+35
- .github/workflows/deploy-to-spaces.ymlAdded+31
- LICENSEAdded+201
- README.mdAdded+13
- app.pyAdded+395
- images/PMC1156947_3.jpgAdded
- models/column_detection.ptAdded+3
- models/column_segmentation.ptAdded+3
- models/row_detection.ptAdded+3
- models/row_segmentation.ptAdded+3
- models/table_detection.ptAdded+3
- requirements.txtAdded+3
- usage.pyAdded+50
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031name: Deploy to Spaces
on: push: branches: [ hfspace ]
jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 1 ref: hfspace lfs: true
- name: Configure Git run: | git config --global user.email "github-actions[bot]@users.noreply.github.com" git config --global user.name "github-actions[bot]" git lfs install
- name: Push to Space env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | git checkout --orphan temp_branch git add -A git commit -m "Deploy to Space" git lfs push --all https://jayllfpt:$HF_TOKEN@huggingface.co/spaces/jayllfpt/table2html temp_branch git push -f https://jayllfpt:$HF_TOKEN@huggingface.co/spaces/jayllfpt/table2html temp_branch:main123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213---title: table2htmlemoji: 🐧colorFrom: pinkcolorTo: bluesdk: streamlitsdk_version: 1.40.1app_file: app.pypinned: falselicense: apache-2.0---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395import cv2import streamlit as stfrom table2html import Table2HTMLfrom table2html.source import visualize_boxes, crop_imageimport numpy as npimport timeimport osimport tempfileimport fitz # PyMuPDFfrom PIL import Image
default_configs = { 'table_detection': { 'model_path': 'models/table_detection.pt', 'confidence_threshold': 0.25, 'iou_threshold': 0.7 }, 'column_detection': { 'model_path': 'models/column_detection.pt', 'confidence_threshold': 0.25, 'iou_threshold': 0.7, 'task': 'detect' }, 'row_detection': { 'model_path': 'models/row_detection.pt', 'confidence_threshold': 0.25, 'iou_threshold': 0.7, 'task': 'detect' }, 'table_crop_padding': 15}
thumbnail_columns = 5
def initialize_session_state(): if 'table_detections' not in st.session_state: st.session_state.table_detections = [] if 'structure_detections' not in st.session_state: st.session_state.structure_detections = [] if 'cropped_tables' not in st.session_state: st.session_state.cropped_tables = [] if 'html_tables' not in st.session_state: st.session_state.html_tables = [] if 'detection_data' not in st.session_state: st.session_state.detection_data = [] if 'current_image' not in st.session_state: st.session_state.current_image = None if 'configs' not in st.session_state: st.session_state.configs = default_configs
def clear_results(): st.session_state.table_detections = [] st.session_state.structure_detections = [] st.session_state.cropped_tables = [] st.session_state.html_tables = []
def detect_update_results(image, configs): table2html = Table2HTML( table_detection_config=configs["table_detection"], row_detection_config=configs["row_detection"], column_detection_config=configs["column_detection"] ) detection_data = table2html(image, configs["table_crop_padding"])
if len(detection_data) == 0: st.warning("No tables detected on this page.") return
# Clear previous results st.session_state.detection_data = detection_data
for data in detection_data: # Store table detection visualization table_detection = visualize_boxes( image.copy(), [data["table_bbox"]], color=(0, 0, 255), thickness=2 ) st.session_state.table_detections.append(table_detection)
# Store cropped table cropped_table = crop_image( image, data["table_bbox"], configs["table_crop_padding"]) st.session_state.cropped_tables.append(cropped_table)
# Store structure detection visualization structure_detection = visualize_boxes( cropped_table.copy(), [cell['box'] for cell in data['cells']], color=(0, 255, 0), thickness=1 ) st.session_state.structure_detections.append(structure_detection)
# Store HTML st.session_state.html_tables.append(data["html"])
def inference_one_image(image, configs): clear_results() with st.spinner("Processing..."): start_time = time.time()
try: # Update process_image call to include all model paths detect_update_results(image, configs)
# Clean up temporary files if using custom models for model_type, config in configs.items(): if f"{model_type}_option" in st.session_state and \ st.session_state[f"{model_type}_option"] == "custom": os.unlink(config["model_path"])
execution_time = time.time() - start_time st.success( f"Processing completed in {execution_time:.2f} seconds") except Exception as e: st.error(f"Error processing image: {str(e)}") # Clean up temporary files on error for model_type, config in configs.items(): if f"{model_type}_option" in st.session_state and \ st.session_state[f"{model_type}_option"] == "custom": os.unlink(config["model_path"])
def main(): initialize_session_state() st.set_page_config(layout="wide")
# Add page selection page = st.sidebar.radio("Select Page", ["Inference", "Configuration"])
if page == "Inference": st.title("Table Detection and Recognition")
# Image Upload Section st.subheader("Image Upload") uploaded_file = st.file_uploader( "Choose an image or PDF file", type=['jpg', 'jpeg', 'png', 'pdf'] )
# Get configurations from session state configs = st.session_state.get('configs', default_configs)
current_image = None
if uploaded_file is not None and all(configs.values()): if uploaded_file.type == "application/pdf": # Convert PDF to images pdf_bytes = uploaded_file.read() pdf_images = []
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
for page_num in range(doc.page_count): page = doc[page_num] pix = page.get_pixmap(dpi=200) pil_image = Image.frombytes( "RGB", [pix.width, pix.height], pix.samples) img_array = np.array(pil_image) pdf_images.append(img_array)
# Show thumbnails st.write("Select a page to process:") cols = st.columns(thumbnail_columns) for idx, img in enumerate(pdf_images): with cols[idx % thumbnail_columns]: st.image(img, width=150, use_container_width=True) if st.button(f"Process Page {idx+1}"): current_image = img st.session_state.current_image = img inference_one_image( current_image, configs) else: # Handle regular image upload file_bytes = np.asarray( bytearray(uploaded_file.read()), dtype=np.uint8) current_image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) st.session_state.current_image = current_image
# Process button if st.button("Process Image"): inference_one_image( current_image, configs)
if len(st.session_state.cropped_tables) > 0: st.header("Results")
# General Results Section st.subheader("General Results") gen_img_col, gen_html_col = st.columns([1, 1])
with gen_img_col: show_all_detections = st.toggle( "Show Table Detections", value=False, key="show_all_detections" )
# Display either original image or detection visualization if show_all_detections and len(st.session_state.detection_data) > 0: # Create visualization with all table detections all_tables_viz = visualize_boxes( st.session_state.current_image.copy(), [data["table_bbox"] for data in st.session_state.detection_data], color=(0, 0, 255), thickness=2 ) st.image( all_tables_viz, caption="All Table Detections", use_container_width=True ) else: st.image( st.session_state.current_image, caption="Original Image", use_container_width=True )
with gen_html_col: st.markdown("### All HTML Tables:") # Combine all HTML tables all_html = "\n".join(st.session_state.html_tables) st.markdown(all_html, unsafe_allow_html=True)
# Download all HTML tables combined_html = "<!DOCTYPE html><html><body>\n" + all_html + "\n</body></html>" st.download_button( label="Download All Tables HTML", data=combined_html, file_name="all_tables.html", mime="text/html", key="download_all_btn" )
st.divider()
# Detailed Results Section show_details = st.toggle("Show Detailed Results", value=False)
if show_details: st.subheader("Detailed Results") for idx in range(len(st.session_state.cropped_tables)): st.subheader(f"Table {idx + 1}")
# Visualization controls for each table control_col1, control_col2 = st.columns([1, 1]) with control_col1: show_table_detection = st.toggle( f"Show Table Detection for Table {idx + 1}", value=False, key=f"table_detection_{idx}" ) with control_col2: show_structure_detection = st.toggle( f"Show Structure Detection for Table {idx + 1}", value=False, key=f"structure_detection_{idx}" )
# Create columns for each table result img_col, html_col = st.columns([1, 1])
with img_col: # Show either the cropped table or visualizations based on toggles if show_table_detection: st.image( st.session_state.table_detections[idx], caption="Table Detection", use_container_width=True ) if show_structure_detection: st.image( st.session_state.structure_detections[idx], caption="Structure Detection", use_container_width=True ) if not show_table_detection and not show_structure_detection: st.image( st.session_state.cropped_tables[idx], caption="Cropped Table", use_container_width=True )
with html_col: st.markdown("### HTML Output:") st.markdown( st.session_state.html_tables[idx], unsafe_allow_html=True ) st.download_button( label=f"Download Table {idx + 1} HTML", data=st.session_state.html_tables[idx], file_name=f"table_{idx + 1}.html", mime="text/html", key=f"download_btn_{idx}" )
st.divider()
else: # Configuration page st.title("Model Configuration")
# Model selection options model_types = ["Table Detection", "Column Detection", "Row Detection"] configs = {} # Store both paths and thresholds
for idx, model_type in enumerate(model_types): st.markdown(f"### {model_type}") key_prefix = model_type.lower().replace(" ", "_")
# Model file selection model_option = st.radio( f"Choose {model_type} Model", options=["default", "custom"], horizontal=True, key=f"{key_prefix}_option" )
if model_option == "default": default_path = f"models/{key_prefix}.pt" configs[key_prefix] = {"model_path": default_path} st.info(f"Using default model: {default_path}") else: model_upload = st.file_uploader( f"Choose {model_type} Model File (.pt)", type=['pt'], key=f"{key_prefix}_upload" ) if model_upload: with tempfile.NamedTemporaryFile(delete=False, suffix='.pt') as tmp_file: tmp_file.write(model_upload.getvalue()) configs[key_prefix] = { "model_path": tmp_file.name} else: configs[key_prefix] = {"model_path": None} st.warning( f"Please upload a {model_type.lower()} model file")
# Add threshold controls thresh_col1, thresh_col2 = st.columns(2) with thresh_col1: conf_threshold = st.slider( f"{model_type} Confidence Threshold", min_value=0.0, max_value=1.0, value=0.25, step=0.05, key=f"{key_prefix}_conf_threshold" ) with thresh_col2: iou_threshold = st.slider( f"{model_type} IOU Threshold", min_value=0.0, max_value=1.0, value=0.7, step=0.05, key=f"{key_prefix}_iou_threshold" )
if configs[key_prefix]["model_path"]: configs[key_prefix].update({ "confidence_threshold": conf_threshold, "iou_threshold": iou_threshold }) # Add task field for row and column detection if key_prefix in ["column_detection", "row_detection"]: configs[key_prefix]["task"] = "detect"
st.divider()
# Padding input below the model configurations table_crop_padding = st.number_input( "Table Crop Padding", value=15, min_value=0, max_value=100 )
# Save configurations to session state if st.button("Save Configuration"): st.session_state.configs = configs st.success("Configuration saved successfully!")
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:7e15f9f0ef4de361d880e359c899e50ee6c0f6d26d9a7dfa41b6d46f94c8817asize 40499813123version https://git-lfs.github.com/spec/v1oid sha256:5d5b57c2b2ab7dfb2b7a05ff41ef4b80d1eceb44274dc1e0acaadf9ba217e916size 45142063123version https://git-lfs.github.com/spec/v1oid sha256:3fe6d5360016dd2d426d3971578ca6806557e1ee64379c56a97e79ba0d2e2ed1size 40499813123version https://git-lfs.github.com/spec/v1oid sha256:db22b415fd54ff5f32f3b83f05a95ecf3e4093c4a174fc3fceddb2cd4028e12fsize 45131055123version https://git-lfs.github.com/spec/v1oid sha256:a1d3701d0c42ac395423089965a8b6e16e4af292ccc3054ae016ea709833f014size 19172627123table2htmlstreamlitpymupdf1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950from table2html.source import visualize_boxesfrom table2html.source import crop_imagefrom table2html import Table2HTMLimport cv2
table_crop_padding = 15
table_config = {
}
row_config = {
}
column_config = {
}
table2html = Table2HTML(table_config, row_config, column_config)
image = cv2.imread( r"C:\Users\jayll\Downloads\no_tables.jpg")
detection_data = table2html(image, table_crop_padding)
for i, data in enumerate(detection_data): table_image = crop_image(image, data["table_bbox"], table_crop_padding) cv2.imwrite( "table_detection.jpg", visualize_boxes( image, [data["table_bbox"]], color=(0, 0, 255), thickness=1 ) ) cv2.imwrite( "structure_detection.jpg", visualize_boxes( table_image, [cell['box'] for cell in data['cells']], color=(0, 255, 0), thickness=1 ) )
with open(f"table_{i}.html", "w") as f: f.write(data["html"]).gitattributesAdded+35
.github/workflows/deploy-to-spaces.ymlAdded+31
LICENSEAdded+201
README.mdAdded+13
app.pyAdded+395
images/PMC1156947_3.jpgAdded

models/column_detection.ptAdded+3
models/column_segmentation.ptAdded+3
models/row_detection.ptAdded+3
models/row_segmentation.ptAdded+3
models/table_detection.ptAdded+3
requirements.txtAdded+3
usage.pyAdded+50