Commit ·
c489b93
1
Parent(s): a3a3acc
feat
Browse filesFiles changed (16)
- .gitattributes+2
- .pre-commit-config.yamlAdded+54
- README.md+1-1
- app.py+1196-152
- examples/Handwritten.jpgAdded
- examples/chemical-equation.jpgAdded
- examples/chinese-formula.jpgAdded
- examples/complex-formula.jpgAdded
- examples/complex-typeset.jpgAdded
- examples/formula-chart.jpgAdded
- examples/janpan-paper.jpgAdded
- examples/muti-column.jpgAdded
- examples/table.jpgAdded
- examples/tradition-chinese.jpgAdded
- examples/vertical-text.jpgAdded
- icon/upload.pngAdded
34 unmodified lines35363734 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textpp-structurev3_altered.png filter=lfs diff=lfs merge=lfs -textpp-structurev3.png filter=lfs diff=lfs merge=lfs -text34 unmodified lines353637383934 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textpp-structurev3_altered.png filter=lfs diff=lfs merge=lfs -textpp-structurev3.png filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354repos:- repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks: - id: check-added-large-files args: ['--maxkb=11000'] - id: check-case-conflict - id: check-merge-conflict - id: check-symlinks - id: detect-private-key - id: end-of-file-fixer - id: trailing-whitespace files: \.(md|c|cc|cxx|cpp|cu|h|hpp|hxx|py)$- repo: https://github.com/Lucas-C/pre-commit-hooks rev: v1.5.1 hooks: - id: remove-crlf - id: remove-tabs files: \.(md|c|cc|cxx|cpp|cu|h|hpp|hxx|py)$- repo: local hooks: - id: clang-format name: clang-format description: Format files with ClangFormat entry: bash .precommit/clang_format.hook -i language: system files: \.(c|cc|cxx|cpp|cu|h|hpp|hxx|cuh|proto)$ # For Python files- repo: https://github.com/psf/black.git rev: 24.4.2 hooks: - id: black files: (.*\.(py|pyi|bzl)|BUILD|.*\.BUILD|WORKSPACE)$
# Flake8- repo: https://github.com/pycqa/flake8 rev: 7.0.0 hooks: - id: flake8 args: - --count - --select=E9,F63,F7,F82,E721,F401 - --per-file-ignores=__init__.py:F401 - --show-source - --statistics
# isort- repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort args: - --profile=black7 unmodified lines8910111213147 unmodified linesapp_file: app.pypinned: falselicense: apache-2.0short_description: Next-Gen High-Precision Doc Parsing Solutiontags:- ocr- document-analysis7 unmodified lines8910111213147 unmodified linesapp_file: app.pypinned: falselicense: apache-2.0short_description: Next-Gen High-Precision Doc Parsing Solutiontags:- ocr- document-analysis
4 unmodified lines56789103 unmodified lines14151617181920214 unmodified lines26272829303114 unmodified lines46474849505152535455565758596061626364656664 unmodified lines13113213313413513613713813917 unmodified lines15715815916016116216316416559 unmodified lines22522622722822923023123223323423523623723823924024124224324424524615 unmodified lines2622632642652662673 unmodified lines2712722732742752762772782792802812822832842852863 unmodified lines29029129229329429510 unmodified lines3063073083093103113123133143153166 unmodified lines3233243253263273284 unmodified lines33333433533633733813 unmodified lines3523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195204 unmodified linesimport osimport reimport tempfileimport uuidimport zipfilefrom pathlib import Path3 unmodified linesfrom PIL import Image# API ConfigurationAPI_URL = "https://cf38vaydqdl2l4p2.aistudio-hub.baidu.com/layout-parsing"TOKEN = os.getenv("API_TOKEN", "")LOGO_PATH = Path(__file__).parent / "pp-structurev3.png"with open(LOGO_PATH, "rb") as image_file:4 unmodified linesTEMP_DIR = tempfile.TemporaryDirectory()atexit.register(TEMP_DIR.cleanup)CSS = """:root {14 unmodified linesfont-family: Arial, sans-serif;}.gradio-container {max-width: var(--content-width) !important;width: 100% !important;margin: 20px auto;padding: 20px;background-color: var(--white);}#component-0,#tabs,#settings {background-color: var(--white) !important;padding: 15px;}.upload-section {width: 100%;margin: 0 auto 30px;64 unmodified linesborder-radius: 4px;padding: 8px 16px;}button:hover {opacity: 0.8 !important;}.file-download {margin-top: 15px !important;17 unmodified linestext-align: center;margin: 20px 0;}"""MAX_NUM_PAGES = 10def url_to_bytes(url, *, timeout=10):59 unmodified linesdef process_file(file_path,use_formula_recognition,use_chart_recognition,use_doc_orientation_classify,use_doc_unwarping,use_textline_orientation,):"""Process uploaded file with API"""try:if not file_path:raise ValueError("Please upload a file first")if Path(file_path).suffix == ".pdf":file_type = "pdf"else:file_type = "image"# Read file contentwith open(file_path, "rb") as f:file_bytes = f.read()15 unmodified lines"useDocOrientationClassify": use_doc_orientation_classify,"useDocUnwarping": use_doc_unwarping,"useTextlineOrientation": use_textline_orientation,},headers=headers,timeout=1000,3 unmodified lines# Parse API responseresult = response.json()layout_results = result.get("result", {}).get("layoutParsingResults", [])layout_ordering_images = []markdown_texts = []markdown_images = []markdown_content_list = []input_images = []for res in layout_results:layout_ordering_images.append(url_to_bytes(res["outputImages"]["layout_order_res"]))markdown = res["markdown"]markdown_text = markdown["text"]markdown_texts.append(markdown_text)3 unmodified linesimg_path_to_bytes[path] = url_to_bytes(url)markdown_images.append(img_path_to_bytes)input_images.append(url_to_bytes(res["inputImage"]))markdown_content = embed_images_into_markdown_text(markdown_text, img_path_to_url)10 unmodified lines"original_file": file_path,"file_type": file_type,"layout_ordering_images": layout_ordering_images,"markdown_texts": markdown_texts,"markdown_images": markdown_images,"markdown_content_list": markdown_content_list,"concatenated_markdown_content": concatenated_markdown_content,"input_images": input_images,"api_response": result,}6 unmodified linesdef export_full_results(results):"""Create ZIP file with all analysis results"""try:if not results:raise ValueError("No results to export")4 unmodified linesfor i, img_bytes in enumerate(results["layout_ordering_images"]):zipf.writestr(f"layout_ordering_images/page_{i+1}.jpg", img_bytes)for i, (md_text, md_imgs) in enumerate(zip(results["markdown_texts"],13 unmodified linesfor i, img_bytes in enumerate(results["input_images"]):zipf.writestr(f"input_images/page_{i+1}.jpg", img_bytes)return str(zip_path)except Exception as e:raise gr.Error(f"Error creating ZIP file: {str(e)}")with gr.Blocks(css=CSS, title="Document Analysis System") as demo:results_state = gr.State()# Header with logowith gr.Column(elem_classes=["logo-container"]):gr.HTML(f'<img src="{LOGO_BASE64}" class="logo-img">')# Navigation barwith gr.Row(elem_classes=["nav-bar"]):gr.HTML("""<div class="nav-links"><a href="https://github.com/PaddlePaddle/PaddleOCR" class="nav-link" target="_blank">GitHub</a></div>""")# Upload sectionwith gr.Column(elem_classes=["upload-section"]):file_input = gr.File(label="Upload Document",file_types=[".pdf", ".jpg", ".jpeg", ".png"],type="filepath",)with gr.Row():use_formula_recognition_cb = gr.Checkbox(value=True, label="Use formula recognition")use_chart_recognition_cb = gr.Checkbox(value=False, label="Use chart recognition")with gr.Row():use_doc_orientation_classify_cb = gr.Checkbox(value=False, label="Use document image orientation classification")use_doc_unwarping_cb = gr.Checkbox(value=False, label="Use text image unwarping")with gr.Row():use_textline_orientation_cb = gr.Checkbox(value=False, label="Use text line orientation classification")concatenate_pages_cb = gr.Checkbox(value=True, label="Concatenate pages")process_btn = gr.Button("Analyze Document", variant="primary")gr.Markdown(f"""1. Only the first {MAX_NUM_PAGES} pages will be processed.2. Some formulas might not display correctly because of renderer limitations.""")loading_spinner = gr.Column(visible=False, elem_classes=["loader-container"])with loading_spinner:gr.HTML("""<div class="loader"></div><p>Processing, please wait...</p>""")# Results display sectionwith gr.Column():gr.Markdown("### Results")with gr.Row():with gr.Column():layout_ordering_images = []for i in range(MAX_NUM_PAGES):layout_ordering_images.append(gr.Image(label=f"Layout Ordering Image {i}",show_label=True,visible=False,))with gr.Column():markdown_display_list = []for i in range(MAX_NUM_PAGES):markdown_display_list.append(gr.Markdown(visible=False,container=True,show_copy_button=True,latex_delimiters=[{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},],))# Download sectionwith gr.Column(elem_classes=["download-section"]):gr.Markdown("### Result Export")download_all_btn = gr.Button("Download Full Results (ZIP)", variant="primary")download_file = gr.File(visible=False, label="Download File")# Interaction logicdef toggle_spinner():return gr.Column(visible=True)def hide_spinner():return gr.Column(visible=False)def update_display(results, concatenate_pages):if not results:return gr.skip()assert len(results["layout_ordering_images"]) <= MAX_NUM_PAGES, len(results["layout_ordering_images"])ret_img = []for img in results["layout_ordering_images"]:ret_img.append(gr.Image(value=bytes_to_image(img), visible=True))for _ in range(len(results["layout_ordering_images"]), MAX_NUM_PAGES):ret_img.append(gr.Image(visible=False))if concatenate_pages:markdown_content = results["concatenated_markdown_content"]ret_cont = [gr.Markdown(value=markdown_content, visible=True)]for _ in range(1, MAX_NUM_PAGES):ret_cont.append(gr.Markdown(visible=False))else:assert len(results["markdown_content_list"]) <= MAX_NUM_PAGES, len(results["markdown_content_list"])ret_cont = []for cont in results["markdown_content_list"]:ret_cont.append(gr.Markdown(value=cont, visible=True))for _ in range(len(results["markdown_content_list"]), MAX_NUM_PAGES):ret_cont.append(gr.Markdown(visible=False))return ret_img + ret_contprocess_btn.click(toggle_spinner, outputs=[loading_spinner]).then(process_file,inputs=[file_input,use_formula_recognition_cb,use_chart_recognition_cb,use_doc_orientation_classify_cb,use_doc_unwarping_cb,use_textline_orientation_cb,],outputs=[results_state],).then(hide_spinner, outputs=[loading_spinner]).then(update_display,inputs=[results_state, concatenate_pages_cb],outputs=layout_ordering_images + markdown_display_list,)download_all_btn.click(export_full_results, inputs=[results_state], outputs=[download_file]).success(lambda: gr.File(visible=True), outputs=[download_file])if __name__ == "__main__":demo.launch(server_name="0.0.0.0",server_port=7860,favicon_path=LOGO_PATH,)4 unmodified lines567891011123 unmodified lines1617181920212223244 unmodified lines293031323334353637383914 unmodified lines54555657585964 unmodified lines12412512612712812917 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432559 unmodified lines38538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243315 unmodified lines4494504514524534544554564574584594604614624634644654664674684694704714724734744754764774783 unmodified lines4824834844854864874884894904914924934944954964974984995005015025035045055063 unmodified lines51051151251351451551610 unmodified lines5275285295305315325335345355365375385395405416 unmodified lines5485495505515525535544 unmodified lines55956056156256356456556656756856957057157257357457513 unmodified lines58959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315644 unmodified linesimport osimport reimport tempfileimport threadingimport timeimport uuidimport zipfilefrom pathlib import Path3 unmodified linesfrom PIL import Image# API ConfigurationAPI_URL = os.environ["SERVER_URL"]TOKEN = os.environ["API_TOKEN"]LOGO_PATH = Path(__file__).parent / "pp-structurev3.png"with open(LOGO_PATH, "rb") as image_file:4 unmodified linesTEMP_DIR = tempfile.TemporaryDirectory()atexit.register(TEMP_DIR.cleanup)paddle_theme = gr.themes.Soft(font=["Roboto", "Open Sans", "Arial", "sans-serif"],font_mono=["Fira Code", "monospace"],)CSS = """:root {14 unmodified linesfont-family: Arial, sans-serif;}.upload-section {width: 100%;margin: 0 auto 30px;64 unmodified linesborder-radius: 4px;padding: 8px 16px;}.file-download {margin-top: 15px !important;17 unmodified linestext-align: center;margin: 20px 0;}.loader-container-prepare {text-align: left;margin: 20px 0;}.bold-label .gr-radio {margin-top: 8px;background-color: var(--white);padding: 10px;border-radius: 4px;}.bold-label .gr-radio label {font-size: 14px;color: var(--black);}#analyze-btn {background-color: #FF5722 !important;color: white !important;transition: all 0.3s ease !important;box-shadow: 0 2px 5px rgba(0,0,0,0.2) !important;position: fixed !important;bottom: 1% !important;left: 3% !important;z-index: 1000 !important;}#unzip-btn {background-color: #4CAF50 !important;color: white !important;transition: all 0.3s ease !important;box-shadow: 0 2px 5px rgba(0,0,0,0.2) !important;position: fixed !important;bottom: 1% !important;left: 18% !important;z-index: 1000 !important;}#download_file {position: fixed !important;bottom: 1% !important;left: 22% !important;z-index: 1000 !important;}#analyze-btn:hover,#unzip-btn:hover{transform: translateY(-3px) !important;box-shadow: 0 4px 8px rgba(0,0,0,0.3) !important;}.square-pdf-btn {width: 90% !important;height: 3% !important;padding: 0 !important;display: flex !important;flex-direction: column !important;align-items: center !important;justify-content: center !important;gap: 8px !important;}.square-pdf-btn img {width: 20% !important;height: 1% !important;margin: 0 !important;}.square-pdf-btn span {font-size: 14px !important;text-align: center !important;}.gradio-gallery-item:hover {background-color: transparent !important;filter: none !important;transform: none !important;}.custom-markdown h3 {font-size: 25px !important;}.tight-spacing {margin-bottom: -20px !important;}.tight-spacing-as {margin-top: 0px !important;margin-bottom: 0px !important;}.left-margin-column {margin-left: 5%;}.image-container img {display: inline-block !important;}}"""MAX_NUM_PAGES = 10TMP_DELETE_TIME = 900THREAD_WAKEUP_TIME = 600EXAMPLES_TEST = ["examples/chinese-formula.jpg","examples/chemical-equation.jpg","examples/formula-chart.jpg","examples/table.jpg","examples/complex-formula.jpg","examples/complex-typeset.jpg","examples/muti-column.jpg","examples/Handwritten.jpg","examples/janpan-paper.jpg","examples/vertical-text.jpg","examples/tradition-chinese.jpg",]DESC_DICT = {"concatenate_pages": "Whether to merge pages","use_formula_recognition": "Whether to use formula recognition subpipeline. If used, the formula can be converted into Latex code. If not used, the formula part is the text recognition result.","use_chart_recognition": "Use the PP-Chart2Table model to parse and convert the charts in the document into tables.","use_doc_orientation_classify": "Whether to use the document image orientation classification module. After use, you can correct distorted images, such as wrinkles, tilts, etc.","use_doc_unwarping": "Whether to use the document unwarping module. After use, you can correct distorted images, such as wrinkles, tilts, etc.","use_textline_orientation": "Whether to use the text line orientation classification module to support the distinction and correction of text lines of 0 degrees and 180 degrees.","use_region_detection": "Whether to use the layout region detection. After using it, it can handle complex layouts such as newspapers and magazines.","use_seal_recognition": "Whether to seal text recognition subpipeline. After use, the seal text content in the document can be extracted.","use_table_recognition": "Whether to table recognition subpipeline. If used, the table can be identified as a structured format (such as HTML, Markdown, etc.). If not used, the table part will be in the form of an image.","layout_threshold_nb": "The threshold used to filter out low confidence prediction results for the layout region, ranging from 0 to 1. If there are missed regions, this value can be appropriately lowered.","layout_nms": "Whether the layout region detection model uses NMS post-processing. After using it, nested boxes or those with large intersections can be removed.","layout_unclip_ratio_nb": "Use this method to expand each region of the layout. The larger the value, the larger the expanded region.","text_det_limit_type": "[Short side] means to ensure that the shortest side of the image is not less than [Image side length limit for text detection], and [Long side] means to ensure that the longest side of the image is not greater than [Image side length limit for text detection].","text_det_limit_side_len_nb": "For the side length limit of the text detection input image, for large images with dense text, if you want more accurate recognition, you should choose a larger size. This parameter is used in conjunction with the [Image side length limit type for text detection]. Generally, the maximum [Long side] is suitable for scenes with large images and text, and the minimum [Short side] is suitable for document scenes with small and dense images.","text_det_thresh_nb": "In the output probability map, only pixels with scores greater than the threshold are considered text pixels, and the value range is 0~1.","text_det_box_thresh_nb": "When the average score of all pixels in the detection result border is greater than the threshold, the result will be considered as a text area, and the value range is 0 to 1. If missed detection occurs, this value can be appropriately lowered.","text_det_unclip_ratio_nb": "Use this method to expand the text area. The larger the value, the larger the expanded area.","text_rec_score_thresh_nb": "After text detection, the text box performs text recognition, and the text results with scores greater than the threshold will be retained. The value range is 0~1.","seal_det_limit_type": "[Short side] means ensuring that the shortest side of the image is not less than [Image side length limit for seal text recognition], and [Long side] means ensuring that the longest side of the image is not greater than [Image side length limit for seal text recognition].","seal_det_limit_side_len_nb": "For the side length limit of the input image for seal text detection, for large images with dense text, if you want more accurate recognition, you should choose a larger size. This parameter is used in conjunction with [Image side length limit type for seal text detection]. Generally, the maximum [Long side] is suitable for scenes with large images and text, and the minimum [Short side] is suitable for document scenes with small and dense images and text.","seal_det_thresh_nb": "In the output probability map, only pixels with scores greater than the threshold are considered text pixels, and the value range is 0~1.","seal_det_box_thresh_nb": "When the average score of all pixels within the detection result border is greater than the threshold, the result will be considered as a text area, and the value range is 0~1.","seal_det_unclip_ratio_nb": "Use this method to expand the seal text area. The larger the value, the larger the expanded area.","seal_rec_score_thresh_nb": "After the seal text is detected, the text box is subjected to text recognition. The text results with scores greater than the threshold will be retained. The value range is 0~1.","use_ocr_results_with_table_cells": "Whether to enable the cell OCR mode. If not enabled, the global OCR result is used to fill the HTML table. If enabled, OCR is performed cell by cell and filled into the HTML table (which will increase the time consumption).","use_e2e_wired_table_rec_model": "Whether to enable the wired table end-to-end prediction mode. If not enabled, the table cell detection model prediction results are used to fill the HTML table. If enabled, the end-to-end table structure recognition model cell prediction results are used to fill the HTML table.","use_e2e_wireless_table_rec_model": "Whether to enable the wireless table end-to-end prediction mode. If not enabled, the table cell detection model prediction results are used to fill the HTML table. If enabled, the end-to-end table structure recognition model cell prediction results are used to fill the HTML table.","use_wired_table_cells_trans_to_html": "The wired table cell detection results are directly converted to HTML. The wired table structure recognition model is no longer used to predict the HTML structure. Instead, HTML is directly constructed based on the geometric relationship of the wired table cell detection results.","use_wireless_table_cells_trans_to_html": "The wireless table cell detection results are directly converted to HTML. The wireless table structure recognition model is no longer used to predict the HTML structure. Instead, HTML is directly constructed based on the geometric relationship of the wireless table cell detection results.","use_table_orientation_classify": "Using table orientation classification, when the table in the image is rotated 90/180/270 degrees, the orientation can be corrected and the table recognition can be completed correctly.",}tmp_time = {}lock = threading.Lock()def gen_tooltip_radio(desc_dict):tooltip = {}for key, desc in desc_dict.items():suffixes = ["_rd", "_md"]if key.endswith("_nb"):suffix = "_nb"suffixes = ["_nb", "_md"]key = key[: -len(suffix)]for suffix in suffixes:tooltip[f"{key}{suffix}"] = descreturn tooltipTOOLTIP_RADIO = gen_tooltip_radio(DESC_DICT)def url_to_bytes(url, *, timeout=10):59 unmodified linesdef process_file(file_path,image_input,use_formula_recognition,use_chart_recognition,use_doc_orientation_classify,use_doc_unwarping,use_textline_orientation,use_region_detection,use_seal_recognition,use_table_recognition,layout_threshold,layout_nms,layout_unclip_ratio,text_det_limit_type,text_det_limit_side_len,text_det_thresh,text_det_box_thresh,text_det_unclip_ratio,text_rec_score_thresh,seal_det_limit_type,seal_det_limit_side_len,seal_det_thresh,seal_det_box_thresh,seal_det_unclip_ratio,seal_rec_score_thresh,use_ocr_results_with_table_cells,use_e2e_wired_table_rec_model,use_e2e_wireless_table_rec_model,use_wired_table_cells_trans_to_html,use_wireless_table_cells_trans_to_html,use_table_orientation_classify,):"""Process uploaded file with API"""try:if not file_path and not image_input:raise ValueError("Please upload a file first")if file_path:if Path(file_path).suffix == ".pdf":file_type = "pdf"else:file_type = "image"else:file_path = image_inputfile_type = "image"# Read file contentwith open(file_path, "rb") as f:file_bytes = f.read()15 unmodified lines"useDocOrientationClassify": use_doc_orientation_classify,"useDocUnwarping": use_doc_unwarping,"useTextlineOrientation": use_textline_orientation,"useSealRecognition": use_seal_recognition,"useRegionDetection": use_region_detection,"useTableRecognition": use_table_recognition,"layoutThreshold": layout_threshold,"layoutNms": layout_nms,"layoutUnclipRatio": layout_unclip_ratio,"textDetLimitType": text_det_limit_type,"textTetLimitSideLen": text_det_limit_side_len,"textDetThresh": text_det_thresh,"textDetBoxThresh": text_det_box_thresh,"textDetUnclipRatio": text_det_unclip_ratio,"textRecScoreThresh": text_rec_score_thresh,"sealDetLimitType": seal_det_limit_type,"sealDetLimitSideLen": seal_det_limit_side_len,"sealDetThresh": seal_det_thresh,"sealDetBoxThresh": seal_det_box_thresh,"sealDetUnclipRatio": seal_det_unclip_ratio,"sealRecScoreThresh": seal_rec_score_thresh,"useOcrResultsWithTableCells": use_ocr_results_with_table_cells,"useE2eWiredTableRecModel": use_e2e_wired_table_rec_model,"useE2eWirelessTableRecModel": use_e2e_wireless_table_rec_model,"useWiredTableCellsTransToHtml": use_wired_table_cells_trans_to_html,"useWirelessWableCellsTransToHtml": use_wireless_table_cells_trans_to_html,"useTableOrientationClassify": use_table_orientation_classify,},headers=headers,timeout=1000,3 unmodified lines# Parse API responseresult = response.json()layout_results = result.get("result", {}).get("layoutParsingResults", [])layout_ordering_images = []layout_det_res_images = []overall_ocr_res_images = []output_json = result.get("result", {})markdown_texts = []markdown_images = []markdown_content_list = []input_images = []input_images_gallery = []for res in layout_results:layout_ordering_images.append(url_to_bytes(res["outputImages"]["layout_order_res"]))layout_det_res_images.append(url_to_bytes(res["outputImages"]["layout_det_res"]))overall_ocr_res_images.append(url_to_bytes(res["outputImages"]["overall_ocr_res"]))markdown = res["markdown"]markdown_text = markdown["text"]markdown_texts.append(markdown_text)3 unmodified linesimg_path_to_bytes[path] = url_to_bytes(url)markdown_images.append(img_path_to_bytes)input_images.append(url_to_bytes(res["inputImage"]))input_images_gallery.append(res["inputImage"])markdown_content = embed_images_into_markdown_text(markdown_text, img_path_to_url)10 unmodified lines"original_file": file_path,"file_type": file_type,"layout_ordering_images": layout_ordering_images,"layout_det_res_images": layout_det_res_images,"overall_ocr_res_images": overall_ocr_res_images,"output_json": output_json,"markdown_texts": markdown_texts,"markdown_images": markdown_images,"markdown_content_list": markdown_content_list,"concatenated_markdown_content": concatenated_markdown_content,"input_images": input_images,"input_images_gallery": input_images_gallery,"api_response": result,}6 unmodified linesdef export_full_results(results):"""Create ZIP file with all analysis results"""try:global tmp_timeif not results:raise ValueError("No results to export")4 unmodified linesfor i, img_bytes in enumerate(results["layout_ordering_images"]):zipf.writestr(f"layout_ordering_images/page_{i+1}.jpg", img_bytes)for i, img_bytes in enumerate(results["layout_det_res_images"]):zipf.writestr(f"layout_det_res_images/page_{i+1}.jpg", img_bytes)for i, img_bytes in enumerate(results["overall_ocr_res_images"]):zipf.writestr(f"overall_ocr_res_images/page_{i+1}.jpg", img_bytes)zipf.writestr("output.json",json.dumps(results["output_json"], indent=2, ensure_ascii=False),)for i, (md_text, md_imgs) in enumerate(zip(results["markdown_texts"],13 unmodified linesfor i, img_bytes in enumerate(results["input_images"]):zipf.writestr(f"input_images/page_{i+1}.jpg", img_bytes)with lock:tmp_time[zip_path] = time.time()return str(zip_path)except Exception as e:raise gr.Error(f"Error creating ZIP file: {str(e)}")def on_file_change(file):if file:return gr.Textbox(value=f"✅ Chosen file: {os.path.basename(file.name)}", visible=True)else:return gr.Textbox()def clear_file_selection():return gr.File(value=None), gr.Textbox(value=None)def clear_file_selection_examples(image_input):text_name = "✅ Chosen file: " + os.path.basename(image_input)return gr.File(value=None), gr.Textbox(value=text_name, visible=True)def toggle_sections(choice):return {Module_Options: gr.Column(visible=(choice == "Module Options")),Subpipeline_Options: gr.Column(visible=(choice == "Subpipeline Options")),Layout_region_detection_Options: gr.Column(visible=(choice == "Layout region detection Options")),Text_detection_Options: gr.Column(visible=(choice == "Text detection Options")),Seal_text_recognition_Options: gr.Column(visible=(choice == "Seal text recognition Options")),Table_recognition_Options: gr.Column(visible=(choice == "Table recognition Options")),}# Interaction logicdef toggle_spinner():return (gr.Column(visible=True),gr.Column(visible=False),gr.File(visible=False),gr.update(visible=False),)def hide_spinner():return gr.Column(visible=False), gr.update(visible=True)def update_display(results, concatenate_pages):if not results:return gr.skip()assert len(results["layout_ordering_images"]) <= MAX_NUM_PAGES, len(results["layout_ordering_images"])assert len(results["layout_det_res_images"]) <= MAX_NUM_PAGES, len(results["layout_det_res_images"])assert len(results["overall_ocr_res_images"]) <= MAX_NUM_PAGES, len(results["overall_ocr_res_images"])assert len(results["input_images_gallery"]) <= MAX_NUM_PAGES, len(results["input_images_gallery"])gallery_list_imgs = []for i in range(len(gallery_list)):gallery_list_imgs.append(gr.Gallery(value=results["input_images_gallery"],rows=len(results["input_images_gallery"]),))layout_order_imgs = []for img in results["layout_ordering_images"]:layout_order_imgs.append(gr.Image(value=bytes_to_image(img), visible=True))for _ in range(len(results["layout_ordering_images"]), MAX_NUM_PAGES):layout_order_imgs.append(gr.Image(visible=False))layout_det_imgs = []for img in results["layout_det_res_images"]:layout_det_imgs.append(gr.Image(value=bytes_to_image(img), visible=True))for _ in range(len(results["layout_det_res_images"]), MAX_NUM_PAGES):layout_det_imgs.append(gr.Image(visible=False))ocr_imgs = []for img in results["overall_ocr_res_images"]:ocr_imgs.append(gr.Image(value=bytes_to_image(img), visible=True))for _ in range(len(results["overall_ocr_res_images"]), MAX_NUM_PAGES):ocr_imgs.append(gr.Image(visible=False))output_json = [gr.Markdown(value=results["output_json"], visible=True)]if concatenate_pages:markdown_content = results["concatenated_markdown_content"]ret_cont = [gr.Markdown(value=markdown_content, visible=True)]for _ in range(1, MAX_NUM_PAGES):ret_cont.append(gr.Markdown(visible=False))else:assert len(results["markdown_content_list"]) <= MAX_NUM_PAGES, len(results["markdown_content_list"])ret_cont = []for cont in results["markdown_content_list"]:ret_cont.append(gr.Markdown(value=cont, visible=True))for _ in range(len(results["markdown_content_list"]), MAX_NUM_PAGES):ret_cont.append(gr.Markdown(visible=False))return (layout_order_imgs+ layout_det_imgs+ ocr_imgs+ output_json+ ret_cont+ gallery_list_imgs)def update_image(evt: gr.SelectData):update_images = []for index in range(MAX_NUM_PAGES):update_images.append(gr.Image(visible=False) if index != evt.index else gr.Image(visible=True))return update_imagesdef update_markdown(concatenate_pages, evt: gr.SelectData):update_markdowns = []if not concatenate_pages:for index in range(MAX_NUM_PAGES):update_markdowns.append(gr.Markdown(visible=False)if index != evt.indexelse gr.Markdown(visible=True))else:gr.Warning("When page merging is on, the thumbnail-to-page linking is disabled. If you want to navigate to the corresponding page when clicking on the thumbnail, please turn off page merging.")for index in range(MAX_NUM_PAGES):update_markdowns.append(gr.Markdown(visible=True) if index == 0 else gr.Markdown(visible=False))return update_markdownsdef delete_file_periodically():global tmp_timewhile True:current_time = time.time()delete_tmp = []for filename, strat_time in list(tmp_time.items()):if (current_time - strat_time) >= TMP_DELETE_TIME:if os.path.exists(filename):os.remove(filename)delete_tmp.append(filename)for filename in delete_tmp:with lock:del tmp_time[filename]time.sleep(THREAD_WAKEUP_TIME)with gr.Blocks(css=CSS, title="Document Analysis System", theme=paddle_theme) as demo:results_state = gr.State()# Header with logowith gr.Column(elem_classes=["logo-container"]):gr.HTML(f'<img src="{LOGO_BASE64}" class="logo-img">')gr.Markdown("""Since our inference server is deployed in mainland China, cross-bordernetwork transmission may be slow, which could result in a suboptimal experience on Hugging Face.We recommend visiting the [PaddlePaddle AI Studio Community](https://aistudio.baidu.com/community/app/518494/webUI?source=appCenter) to try the demo for a smoother experience.""",elem_classes=["tight-spacing-as"],visible=True,)# Upload sectionwith gr.Row():with gr.Column(scale=4):file_input = gr.File(label="Upload document",file_types=[".pdf", ".jpg", ".jpeg", ".png"],type="filepath",visible=False,)file_select = gr.Textbox(label="Select File Path", visible=False)image_input = gr.Image(label="Image",sources="upload",type="filepath",visible=False,interactive=True,placeholder="Click to upload image...",)pdf_btn = gr.Button("Click to upload file...",variant="primary",icon="icon/upload.png",elem_classes=["square-pdf-btn"],)examples_image = gr.Examples(fn=clear_file_selection_examples,inputs=image_input,outputs=[file_input, file_select],examples_per_page=11,examples=EXAMPLES_TEST,run_on_click=True,)file_input.change(fn=on_file_change, inputs=file_input, outputs=[file_select])concatenate_pages_md = gr.Markdown("### Merge pages", elem_id="concatenate_pages_md")concatenate_pages_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="concatenate_pages_rd",)with gr.Column():section_choice = gr.Dropdown(choices=["Module Options","Subpipeline Options","Layout region detection Options","Text detection Options","Seal text recognition Options","Table recognition Options",],value="Module Options",label="Advance Options",show_label=True,container=True,scale=0,elem_classes=["tight-spacing"],)with gr.Column(visible=True, elem_classes="left-margin-column") as Module_Options:use_chart_recognition_md = gr.Markdown("### Using the chart parsing module",elem_id="use_chart_recognition_md",)use_chart_recognition_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_chart_recognition_rd",)use_region_detection_md = gr.Markdown("### Using the layout region detection module",elem_id="use_region_detection_md",)use_region_detection_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=True,interactive=True,show_label=False,elem_id="use_region_detection_rd",)use_doc_orientation_classify_md = gr.Markdown("### Using the document image orientation classification module",elem_id="use_doc_orientation_classify_md",)use_doc_orientation_classify_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_doc_orientation_classify_rd",)use_doc_unwarping_md = gr.Markdown("### Using the document unwarping module",elem_id="use_doc_unwarping_md",)use_doc_unwarping_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_doc_unwarping_rd",)use_textline_orientation_md = gr.Markdown("### Using the text line orientation classification module",elem_id="use_textline_orientation_md",)use_textline_orientation_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_textline_orientation_rd",)with gr.Column(visible=False, elem_classes="left-margin-column") as Subpipeline_Options:use_seal_recognition_md = gr.Markdown("### Using the seal text recognition subpipeline",elem_id="use_seal_recognition_md",)use_seal_recognition_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=True,interactive=True,show_label=False,elem_id="use_seal_recognition_rd",)use_formula_recognition_md = gr.Markdown("### Using the formula recognition subpipeline",elem_id="use_formula_recognition_md",)use_formula_recognition_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=True,interactive=True,show_label=False,elem_id="use_formula_recognition_rd",)use_table_recognition_md = gr.Markdown("### Using the table recognition subpipeline",elem_id="use_table_recognition_md",)use_table_recognition_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=True,interactive=True,show_label=False,elem_id="use_table_recognition_rd",)with gr.Column(visible=False, elem_classes="left-margin-column") as Layout_region_detection_Options:layout_threshold_md = gr.Markdown("### Score threshold of layout region detection model",elem_id="layout_threshold_md",)layout_threshold_nb = gr.Number(value=0.5,step=0.1,minimum=0,maximum=1,interactive=True,show_label=False,elem_id="layout_threshold_nb",)layout_nms_md = gr.Markdown("### NMS post-processing of layout region detection",elem_id="layout_nms_md",)layout_nms_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=True,interactive=True,show_label=False,elem_id="layout_nms_rd",)layout_unclip_ratio_md = gr.Markdown("### Layout region detection expansion coefficient",elem_id="layout_unclip_ratio_md",)layout_unclip_ratio_nb = gr.Number(value=1.0,step=0.1,minimum=0,maximum=10.0,interactive=True,show_label=False,elem_id="layout_unclip_ratio_nb",)with gr.Column(visible=False, elem_classes="left-margin-column") as Text_detection_Options:text_det_limit_type_md = gr.Markdown("### Image side length restriction type for text detection",elem_id="text_det_limit_type_md",)text_det_limit_type_rd = gr.Radio(choices=[("Short side", "min"), ("Long side", "max")],value="min",interactive=True,show_label=False,elem_id="text_det_limit_type_rd",)text_det_limit_side_len_md = gr.Markdown("### Image side length limitation for text detection",elem_id="text_det_limit_side_len_md",)text_det_limit_side_len_nb = gr.Number(value=736,step=1,minimum=0,maximum=10000,interactive=True,show_label=False,elem_id="text_det_limit_side_len_nb",)text_det_thresh_md = gr.Markdown("### Text detection pixel threshold",elem_id="text_det_thresh_md",)text_det_thresh_nb = gr.Number(value=0.30,step=0.01,minimum=0.00,maximum=1.00,interactive=True,show_label=False,elem_id="text_det_thresh_nb",)text_det_box_thresh_md = gr.Markdown("### Text detection box threshold",elem_id="text_det_box_thresh_md",)text_det_box_thresh_nb = gr.Number(value=0.60,step=0.01,minimum=0.00,maximum=1.00,interactive=True,show_label=False,elem_id="text_det_box_thresh_nb",)text_det_unclip_ratio_md = gr.Markdown("### Text detection unclip ratio",elem_id="text_det_unclip_ratio_md",)text_det_unclip_ratio_nb = gr.Number(value=1.5,step=0.1,minimum=0,maximum=10.0,interactive=True,show_label=False,elem_id="text_det_unclip_ratio_nb",)text_rec_score_thresh_md = gr.Markdown("### Text recognition score threshold",elem_id="text_rec_score_thresh_md",)text_rec_score_thresh_nb = gr.Number(value=0.00,step=0.01,minimum=0,maximum=1.00,interactive=True,show_label=False,elem_id="text_rec_score_thresh_nb",)with gr.Column(visible=False, elem_classes="left-margin-column") as Seal_text_recognition_Options:seal_det_limit_type_md = gr.Markdown("### Image side length restriction type for seal text detection",elem_id="seal_det_limit_type_md",)seal_det_limit_type_rd = gr.Radio(choices=[("Short side", "min"), ("Long side", "max")],value="min",interactive=True,show_label=False,elem_id="seal_det_limit_type_rd",)seal_det_limit_side_len_md = gr.Markdown("### Image side length limitation for seal text detection",elem_id="seal_det_limit_side_len_md",)seal_det_limit_side_len_nb = gr.Number(value=736,step=1,minimum=0,maximum=10000,interactive=True,show_label=False,elem_id="seal_det_limit_side_len_nb",)seal_det_thresh_md = gr.Markdown("### Pixel threshold for seal text detection",elem_id="seal_det_thresh_md",)seal_det_thresh_nb = gr.Number(value=0.20,step=0.01,minimum=0.00,maximum=1.00,interactive=True,show_label=False,elem_id="seal_det_thresh_nb",)seal_det_box_thresh_md = gr.Markdown("### Seal text detection box threshold",elem_id="seal_det_box_thresh_md",)seal_det_box_thresh_nb = gr.Number(value=0.60,step=0.01,minimum=0.00,maximum=1.00,interactive=True,show_label=False,elem_id="seal_det_box_thresh_nb",)seal_det_unclip_ratio_md = gr.Markdown("### Seal text detection unclip ratio",elem_id="seal_det_unclip_ratio_md",)seal_det_unclip_ratio_nb = gr.Number(value=0.5,step=0.1,minimum=0,maximum=10.0,interactive=True,show_label=False,elem_id="seal_det_unclip_ratio_nb",)seal_rec_score_thresh_md = gr.Markdown("### Seal text detection threshold",elem_id="seal_rec_score_thresh_md",)seal_rec_score_thresh_nb = gr.Number(value=0.00,step=0.01,minimum=0,maximum=1.00,interactive=True,show_label=False,elem_id="seal_rec_score_thresh_nb",)with gr.Column(visible=False, elem_classes="left-margin-column") as Table_recognition_Options:use_ocr_results_with_table_cells_md = gr.Markdown("### Cell OCR mode",elem_id="use_ocr_results_with_table_cells_md",)use_ocr_results_with_table_cells_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=True,interactive=True,show_label=False,elem_id="use_ocr_results_with_table_cells_rd",)use_e2e_wired_table_rec_model_md = gr.Markdown("### Wired Table End-to-End Prediction model",elem_id="use_e2e_wired_table_rec_model_md",)use_e2e_wired_table_rec_model_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_e2e_wired_table_rec_model_rd",)use_e2e_wireless_table_rec_model_md = gr.Markdown("### Wireless Table End-to-End Prediction model",elem_id="use_e2e_wireless_table_rec_model_md",)use_e2e_wireless_table_rec_model_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_e2e_wireless_table_rec_model_rd",)use_wired_table_cells_trans_to_html_md = gr.Markdown("### Wired table to HTML mode",elem_id="use_wired_table_cells_trans_to_html_md",)use_wired_table_cells_trans_to_html_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_wired_table_cells_trans_to_html_rd",)use_wireless_table_cells_trans_to_html_md = gr.Markdown("### Wireless table to HTML mode",elem_id="use_wireless_table_cells_trans_to_html_md",)use_wireless_table_cells_trans_to_html_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=False,interactive=True,show_label=False,elem_id="use_wireless_table_cells_trans_to_html_rd",)use_table_orientation_classify_md = gr.Markdown("### Using table orientation classify module",elem_id="use_table_orientation_classify_md",)use_table_orientation_classify_rd = gr.Radio(choices=[("yes", True), ("no", False)],value=True,interactive=True,show_label=False,elem_id="use_table_orientation_classify_rd",)with gr.Row():process_btn = gr.Button("🚀 Parse Document", elem_id="analyze-btn", variant="primary")download_all_btn = gr.Button("📦 Download Full Results (ZIP)",elem_id="unzip-btn",variant="primary",)gr.Markdown(f"""1. Only the first {MAX_NUM_PAGES} pages will be processed.2. Some formulas might not display correctly because of renderer limitations or syntax errors.""")# Results display sectionwith gr.Column(scale=7):gr.Markdown("### Results", elem_classes="custom-markdown")loading_spinner = gr.Column(visible=False, elem_classes=["loader-container"])with loading_spinner:gr.HTML("""<div class="loader"></div><p>Processing, please wait...</p>""")prepare_spinner = gr.Column(visible=True, elem_classes=["loader-container-prepare"])with prepare_spinner:gr.HTML("""<div style="max-width: 100%;max-height: 100%;margin: 24px 0 0 12px;padding: 24px 32px;border: 2px solid #A8C1E7;border-radius: 12px;background: #f8faff;box-shadow: 0 2px 8px rgba(100,150,200,0.08);font-size: 18px;"><b>🚀 User Guide</b><br><b>Step 1:</b> Upload Your File<br>Supported formats: JPG, PNG, PDF, JPEG<br><b>Step 2:</b> Click Analyze Document Button<br>System will process automatically<br><b>Step 3:</b> Wait for Results<br>Results will be displayed after processing<br><b>Step 4:</b> Download results zip<br>Results zip will be displayed after processing<br></div>""")download_file = gr.File(visible=False, label="Download File")markdown_display_list = []layout_ordering_images = []layout_det_res_images = []overall_ocr_res_images = []output_json_list = []gallery_list = []with gr.Tabs(visible=False) as tabs:with gr.Tab("Layout Parsing"):with gr.Row():with gr.Column(scale=2, min_width=1):gallery_markdown = gr.Gallery(show_label=False,allow_preview=False,preview=False,columns=1,min_width=10,object_fit="contain",visible=True,)gallery_list.append(gallery_markdown)with gr.Column(scale=10):for i in range(MAX_NUM_PAGES):markdown_display_list.append(gr.Markdown(visible=False,container=True,show_copy_button=True,latex_delimiters=[{"left": "$$","right": "$$","display": True,},{"left": "$","right": "$","display": False,},],elem_classes=["image-container"],))with gr.Tab("Reading Order"):with gr.Row():with gr.Column(scale=2, min_width=1):gallery_layout_order = gr.Gallery(show_label=False,allow_preview=False,preview=False,columns=1,min_width=10,object_fit="contain",)gallery_list.append(gallery_layout_order)with gr.Column(scale=10):for i in range(MAX_NUM_PAGES):layout_ordering_images.append(gr.Image(label=f"Layout Ordering Image {i}",show_label=True,visible=False,container=True,))with gr.Tab("Layout Region Detection"):with gr.Row():with gr.Column(scale=2, min_width=1):gallery_layout_det = gr.Gallery(show_label=False,allow_preview=False,preview=False,columns=1,min_width=10,object_fit="contain",)gallery_list.append(gallery_layout_det)with gr.Column(scale=10):for i in range(MAX_NUM_PAGES):layout_det_res_images.append(gr.Image(label=f"Layout Detection Image {i}",show_label=True,visible=False,))with gr.Tab("OCR"):with gr.Row():with gr.Column(scale=2, min_width=1):gallery_ocr_det = gr.Gallery(show_label=False,allow_preview=False,preview=False,columns=1,min_width=10,object_fit="contain",)gallery_list.append(gallery_ocr_det)with gr.Column(scale=10):for i in range(MAX_NUM_PAGES):overall_ocr_res_images.append(gr.Image(label=f"OCR Image {i}",show_label=True,visible=False,))with gr.Tab("JSON"):with gr.Row():with gr.Column(scale=2, min_width=1):gallery_json = gr.Gallery(show_label=False,allow_preview=False,preview=False,columns=1,min_width=10,object_fit="contain",)gallery_list.append(gallery_json)with gr.Column(scale=10):gr.HTML("""<style>.line.svelte-19ir0ev svg {width: 30px !important;height: 30px !important;min-width: 30px !important;min-height: 30px !important;padding: 0 !important;font-size: 18px !important;}.line.svelte-19ir0ev span:contains('Object(') {font-size: 12px;}</style>""")output_json_list.append(gr.JSON(visible=False,))# # Navigation barwith gr.Column(elem_classes=["nav-bar"]):gr.HTML("""<div class="nav-links"><a href="https://github.com/PaddlePaddle/PaddleOCR" class="nav-link" target="_blank">GitHub</a></div>""")section_choice.change(fn=toggle_sections,inputs=section_choice,outputs=[Module_Options,Subpipeline_Options,Layout_region_detection_Options,Text_detection_Options,Seal_text_recognition_Options,Table_recognition_Options,],)pdf_btn.click(fn=clear_file_selection, inputs=[], outputs=[file_input, file_select]).then(None,[],[],js="""() => {const fileInput = document.querySelector('input[type="file"]');fileInput.value = '';fileInput.click();}""",)process_btn.click(toggle_spinner, outputs=[loading_spinner, prepare_spinner, download_file, tabs]).then(process_file,inputs=[file_input,image_input,use_formula_recognition_rd,use_chart_recognition_rd,use_doc_orientation_classify_rd,use_doc_unwarping_rd,use_textline_orientation_rd,use_region_detection_rd,use_seal_recognition_rd,use_table_recognition_rd,layout_threshold_nb,layout_nms_rd,layout_unclip_ratio_nb,text_det_limit_type_rd,text_det_limit_side_len_nb,text_det_thresh_nb,text_det_box_thresh_nb,text_det_unclip_ratio_nb,text_rec_score_thresh_nb,seal_det_limit_type_rd,seal_det_limit_side_len_nb,seal_det_thresh_nb,seal_det_box_thresh_nb,seal_det_unclip_ratio_nb,seal_rec_score_thresh_nb,use_ocr_results_with_table_cells_rd,use_e2e_wired_table_rec_model_rd,use_e2e_wireless_table_rec_model_rd,use_wired_table_cells_trans_to_html_rd,use_wireless_table_cells_trans_to_html_rd,use_table_orientation_classify_rd,],outputs=[results_state],).then(hide_spinner, outputs=[loading_spinner, tabs]).then(update_display,inputs=[results_state, concatenate_pages_rd],outputs=layout_ordering_images+ layout_det_res_images+ overall_ocr_res_images+ output_json_list+ markdown_display_list+ gallery_list,)gallery_markdown.select(update_markdown,inputs=concatenate_pages_rd,outputs=markdown_display_list,)gallery_layout_order.select(update_image, outputs=layout_ordering_images)gallery_layout_det.select(update_image, outputs=layout_det_res_images)gallery_ocr_det.select(update_image, outputs=overall_ocr_res_images)download_all_btn.click(export_full_results, inputs=[results_state], outputs=[download_file]).success(lambda: gr.File(visible=True), outputs=[download_file])demo.load(fn=lambda: None,inputs=[],outputs=[],js=f"""() => {{const tooltipTexts = {TOOLTIP_RADIO};let tooltip = document.getElementById("custom-tooltip");if (!tooltip) {{tooltip = document.createElement("div");tooltip.id = "custom-tooltip";tooltip.style.position = "fixed";tooltip.style.background = "rgba(0, 0, 0, 0.75)";tooltip.style.color = "white";tooltip.style.padding = "6px 10px";tooltip.style.borderRadius = "4px";tooltip.style.fontSize = "13px";tooltip.style.maxWidth = "300px";tooltip.style.zIndex = "10000";tooltip.style.pointerEvents = "none";tooltip.style.transition = "opacity 0.2s";tooltip.style.opacity = "0";tooltip.style.whiteSpace = "normal";document.body.appendChild(tooltip);}}Object.keys(tooltipTexts).forEach(id => {{const elem = document.getElementById(id);if (!elem) return;function showTooltip(e) {{tooltip.style.opacity = "1";tooltip.innerText = tooltipTexts[id];let x = e.clientX + 10;let y = e.clientY + 10;if (x + tooltip.offsetWidth > window.innerWidth) {{x = e.clientX - tooltip.offsetWidth - 10;}}if (y + tooltip.offsetHeight > window.innerHeight) {{y = e.clientY - tooltip.offsetHeight - 10;}}tooltip.style.left = x + "px";tooltip.style.top = y + "px";}}function hideTooltip() {{tooltip.style.opacity = "0";}}elem.addEventListener("mousemove", showTooltip);elem.addEventListener("mouseleave", hideTooltip);}});}}""",)if __name__ == "__main__":t = threading.Thread(target=delete_file_periodically)t.start()demo.launch(server_name="0.0.0.0",server_port=7860,)
.gitattributes+2
.pre-commit-config.yamlAdded+54
README.md+1-1
app.py+1196-152
examples/Handwritten.jpgAdded

Large File Pointer Details
- SHA256: 4fbd1482b39b103a31b049d0d3a5830b8deb694edf12176116f47d3e7ffd966a
- Pointer size: 131 Bytes
- Size of remote file: 465 kB
examples/chemical-equation.jpgAdded

Large File Pointer Details
- SHA256: d0d50911acb3010fb6d7b35c98efd83cf5bd89acebcfe4d5a1d1ff0203be7492
- Pointer size: 131 Bytes
- Size of remote file: 225 kB
examples/chinese-formula.jpgAdded

Large File Pointer Details
- SHA256: 28c17e5bf8b8c603667e531016ed087fb7bebc67b0b304db0bd74ceee164aeb5
- Pointer size: 131 Bytes
- Size of remote file: 224 kB
examples/complex-formula.jpgAdded

Large File Pointer Details
- SHA256: 0ea2daa1fc3e5e0e3244a3229c93b88c9a5e89130c550cb06e9f80d572613a26
- Pointer size: 131 Bytes
- Size of remote file: 221 kB
examples/complex-typeset.jpgAdded

Large File Pointer Details
- SHA256: ee4b25fe50bd0f0c270efff76c50445c9695bb12e96f05b2b971df986f4466b0
- Pointer size: 131 Bytes
- Size of remote file: 966 kB
examples/formula-chart.jpgAdded

Large File Pointer Details
- SHA256: 80f629e74f1a9272004b5578bf21b8e99f26859cd2381b1151537b61d1abdb40
- Pointer size: 131 Bytes
- Size of remote file: 171 kB
examples/janpan-paper.jpgAdded

Large File Pointer Details
- SHA256: 5bcbeeb9691cf2abf9f3832bf04aef6a3f63709d5f987c364b73c25c8360ed1f
- Pointer size: 131 Bytes
- Size of remote file: 655 kB
examples/muti-column.jpgAdded

Large File Pointer Details
- SHA256: 6cafba2ef3d7281c4095f8b429eb7358d89690596a764b2f9b02bf5fca630dbd
- Pointer size: 131 Bytes
- Size of remote file: 808 kB
examples/table.jpgAdded

Large File Pointer Details
- SHA256: d424db7d01fa6a842afea3ff1a7a41bf03e9e7089fb931e19ce578ccce42de06
- Pointer size: 131 Bytes
- Size of remote file: 900 kB
examples/tradition-chinese.jpgAdded

Large File Pointer Details
- SHA256: 101e1863680032368af0b64bb514ee7a7d401288d2c2b23632932437c933a053
- Pointer size: 131 Bytes
- Size of remote file: 393 kB
examples/vertical-text.jpgAdded

Large File Pointer Details
- SHA256: 442f70532f79419288fa1ca99b03400a716691a8a65576290e57f620f1e6e801
- Pointer size: 131 Bytes
- Size of remote file: 561 kB
icon/upload.pngAdded
Large File Pointer Details
- SHA256: bf7780dd26d21a5f09ef9c0f9c86ba992b2bf53fcd5f5618617cce33afec44b6
- Pointer size: 130 Bytes
- Size of remote file: 49.2 kB