Spaces:
Paused
Paused
root commited on
Commit ·
1f36eb9
1
Parent(s): 9c0138c
update
Browse files63 unmodified lines646566676869707172737475767717 unmodified lines959697989910010110210310410510641 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781797 unmodified lines1871881891901911921932 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182191 unmodified line22122222322422522622722822923023123223323437 unmodified lines27227327427527627727827918 unmodified lines29829930030130230330463 unmodified linesreturn mddef _get_examples_from_dir(dir_path: str) -> List[List[str]]:supported_exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}examples = []if not os.path.exists(dir_path): return []for filename in sorted(os.listdir(dir_path)):if os.path.splitext(filename)[1].lower() in supported_exts:examples.append([os.path.join(dir_path, filename)])return examplesTARGETED_EXAMPLES_DIR = "examples/targeted"COMPLEX_EXAMPLES_DIR = "examples/complex"targeted_recognition_examples = _get_examples_from_dir(TARGETED_EXAMPLES_DIR)17 unmodified lineselse:return gr.update(value="", visible=False)def _on_gallery_select(example_paths: List[str], evt: gr.SelectData):try:idx = evt.indexreturn example_paths[idx]except Exception:return None# =========================# API Call Logic41 unmodified linesreturn data# =========================# API Response Processing# =========================# 【改动点】: 这个函数现在不再需要,因为我们不再将URL下载为PIL Image对象。# def url_to_pil_image(url: str) -> Optional[Image.Image]:# """Downloads an image from a URL and returns it as a PIL Image object for the Gradio Image component."""# if not url or not url.startswith(('http://', 'https://')):# print(f"Warning: Invalid URL provided for visualization image: {url}")# return None# try:# start_time = time.time()# response = requests.get(url, timeout=600)# end_time = time.time()# print(f"Fetched visualization image from {url} in {end_time - start_time:.2f} seconds.")## response.raise_for_status()# image_bytes = response.content# pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB")# return pil_image# except requests.exceptions.RequestException as e:# print(f"Error fetching visualization image from URL {url}: {e}")# return None# except Exception as e:# print(f"Error processing visualization image from URL {url}: {e}")# return Nonedef _process_api_response_page(result: Dict[str, Any]) -> Tuple[str, str, str]:"""7 unmodified linespage0 = layout_results[0] or {}# Step 1: Process Markdown content (unchanged from previous optimization)md_data = page0.get("markdown") or {}md_text = md_data.get("text", "") or ""md_images_map = md_data.get("images", {})2 unmodified linesmd_text = md_text.replace(f'src="{placeholder_path}"', f'src="{image_url}"') \.replace(f']({placeholder_path})', f']({image_url})')# 【核心改动点】 Step 2: Process Visualization images by creating an HTML stringoutput_html = "<p style='text-align:center; color:#888;'>No visualization image available.</p>"out_imgs = page0.get("outputImages") or {}# Get all image URLs and sort themsorted_urls = [img_url for _, img_url in sorted(out_imgs.items()) if img_url]# Logic to select the final visualization image URLoutput_image_url: Optional[str] = Noneif len(sorted_urls) >= 2:output_image_url = sorted_urls[1]elif sorted_urls:output_image_url = sorted_urls[0]# If a URL was found, create the <img> tagif output_image_url:print(f"Found visualization image URL: {output_image_url}")# The CSS will style this `img` tag because of the `#vis_image_doc img` selectoroutput_html = f'<img src="{output_image_url}" alt="Detection Visualization">'else:print("Warning: No visualization image URL found in the API response.")1 unmodified linemd_text = _escape_inequalities_in_math(md_text)return md_text or "(Empty result)", output_html, md_text# =========================# Handlers# =========================def handle_complex_doc(file_path: str, use_chart_recognition: bool) -> Tuple[str, str, str]:if not file_path: raise gr.Error("Please upload an image first.")data = _call_api(DEFAULT_API_URL, file_path, use_layout_detection=True, prompt_label=None, use_chart_recognition=use_chart_recognition)result = data.get("result", {})# Note the return types now align with the new function signaturereturn _process_api_response_page(result)def handle_targeted_recognition(file_path: str, prompt_choice: str) -> Tuple[str, str]:37 unmodified lineswith gr.Blocks(head=GOOGLE_FONTS_URL, css=custom_css, theme=gr.themes.Soft()) as demo:logo_data_url = image_to_base64_data_url(LOGO_IMAGE_PATH) if os.path.exists(LOGO_IMAGE_PATH) else ""gr.HTML(f"""<div class="app-header"><img src="{logo_data_url}" alt="App Logo" style="max-height:10%; width: auto; margin: 10px auto; display: block;"></div>""")gr.HTML("""<div class="notice"><strong>Heads up:</strong> The Hugging Face demo can be slow at times. For a faster experience, please try <a href="https://aistudio.baidu.com/application/detail/98365" target="_blank" rel="noopener noreferrer">Baidu AI Studio</a> or <a href="https://modelscope.cn/studios/PaddlePaddle/PaddleOCR-VL_Online_Demo/summary" target="_blank" rel="noopener noreferrer">ModelScope</a>.</div>""")gr.HTML("""<div class="quick-links"><a href="https://github.com/PaddlePaddle/PaddleOCR" target="_blank">GitHub</a> | <a href="https://ernie.baidu.com/blog/publication/PaddleOCR-VL_Technical_Report.pdf" target="_blank">Technical Report</a> | <a href="https://huggingface.co/PaddlePaddle/PaddleOCR-VL" target="_blank">Model</a></div>""")with gr.Tabs():with gr.Tab("Document Parsing"):18 unmodified lineswith gr.Tab("Markdown Preview"):md_preview_doc = gr.Markdown("Please upload an image and click 'Parse Document'.", latex_delimiters=LATEX_DELIMS, elem_id="md_preview_doc")with gr.Tab("Visualization"):# 【核心改动点】: 将 gr.Image 替换为 gr.HTMLvis_image_doc = gr.HTML(label="Detection Visualization", elem_id="vis_image_doc")with gr.Tab("Markdown Source"):md_raw_doc = gr.Code(label="Markdown Source Code", language="markdown")63 unmodified lines64656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111217 unmodified lines13013113213313413513641 unmodified lines1781791801811821837 unmodified lines1911921931941951962 unmodified lines1992002012022032042052062072082092102112122132142152162171 unmodified line21922022122222322422522622722837 unmodified lines26626726826927027127218 unmodified lines29129229329429529663 unmodified linesreturn mddef _get_examples_from_dir(dir_path: str) -> List[List[str]]:"""读取本地 examples 目录中的文件名,但不转 base64,而是拼接远程根路径作为完整图片 URL。"""BASE_URL = "https://paddle-model-ecology.bj.bcebos.com/PPOCRVL/dataset/examples"supported_exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}examples = []if not os.path.exists(dir_path):print(f"Warning: example dir {dir_path} not found.")return []for filename in sorted(os.listdir(dir_path)):ext = os.path.splitext(filename)[1].lower()if ext in supported_exts:subdir = os.path.basename(dir_path.rstrip("/"))img_url = f"{BASE_URL}/{subdir}/{filename}"examples.append([img_url])return examplesimport tempfilefrom urllib.parse import urlparsedef _download_to_temp(url: str) -> str:r = requests.get(url, timeout=600)r.raise_for_status()ext = os.path.splitext(urlparse(url).path)[1] or ".jpg"fd, tmp_path = tempfile.mkstemp(suffix=ext)with os.fdopen(fd, "wb") as f:f.write(r.content)return tmp_pathdef _on_gallery_select(example_paths: List[str], evt: gr.SelectData):idx = evt.indexselected_path = example_paths[idx]if isinstance(selected_path, list):selected_path = selected_path[0]if isinstance(selected_path, str) and selected_path.startswith(("http://", "https://")):tmp_file = _download_to_temp(selected_path)print(f"Selected remote example -> tmp file: {tmp_file}")return tmp_fileelse:return selected_pathTARGETED_EXAMPLES_DIR = "examples/targeted"COMPLEX_EXAMPLES_DIR = "examples/complex"targeted_recognition_examples = _get_examples_from_dir(TARGETED_EXAMPLES_DIR)17 unmodified lineselse:return gr.update(value="", visible=False)# =========================# API Call Logic41 unmodified linesreturn datadef _process_api_response_page(result: Dict[str, Any]) -> Tuple[str, str, str]:"""7 unmodified linespage0 = layout_results[0] or {}md_data = page0.get("markdown") or {}md_text = md_data.get("text", "") or ""md_images_map = md_data.get("images", {})2 unmodified linesmd_text = md_text.replace(f'src="{placeholder_path}"', f'src="{image_url}"') \.replace(f']({placeholder_path})', f']({image_url})')output_html = "<p style='text-align:center; color:#888;'>No visualization image available.</p>"out_imgs = page0.get("outputImages") or {}sorted_urls = [img_url for _, img_url in sorted(out_imgs.items()) if img_url]output_image_url: Optional[str] = Noneif len(sorted_urls) >= 2:output_image_url = sorted_urls[1]elif sorted_urls:output_image_url = sorted_urls[0]if output_image_url:print(f"Found visualization image URL: {output_image_url}")output_html = f'<img src="{output_image_url}" alt="Detection Visualization">'else:print("Warning: No visualization image URL found in the API response.")1 unmodified linemd_text = _escape_inequalities_in_math(md_text)return md_text or "(Empty result)", output_html, md_textdef handle_complex_doc(file_path: str, use_chart_recognition: bool) -> Tuple[str, str, str]:if not file_path: raise gr.Error("Please upload an image first.")data = _call_api(DEFAULT_API_URL, file_path, use_layout_detection=True, prompt_label=None, use_chart_recognition=use_chart_recognition)result = data.get("result", {})return _process_api_response_page(result)def handle_targeted_recognition(file_path: str, prompt_choice: str) -> Tuple[str, str]:37 unmodified lineswith gr.Blocks(head=GOOGLE_FONTS_URL, css=custom_css, theme=gr.themes.Soft()) as demo:logo_data_url = image_to_base64_data_url(LOGO_IMAGE_PATH) if os.path.exists(LOGO_IMAGE_PATH) else ""gr.HTML(f"""<div class="app-header"><img src="{logo_data_url}" alt="App Logo" style="max-height:10%; width: auto; margin: 10px auto; display: block;"></div>""")gr.HTML("""<div class="quick-links"><a href="https://github.com/PaddlePaddle/PaddleOCR" target="_blank">GitHub</a> | <a href="https://ernie.baidu.com/blog/publication/PaddleOCR-VL_Technical_Report.pdf" target="_blank">Technical Report</a> | <a href="https://www.modelscope.cn/models/PaddlePaddle/PaddleOCR-VL" target="_blank">Model</a></div>""")with gr.Tabs():with gr.Tab("Document Parsing"):18 unmodified lineswith gr.Tab("Markdown Preview"):md_preview_doc = gr.Markdown("Please upload an image and click 'Parse Document'.", latex_delimiters=LATEX_DELIMS, elem_id="md_preview_doc")with gr.Tab("Visualization"):vis_image_doc = gr.HTML(label="Detection Visualization", elem_id="vis_image_doc")with gr.Tab("Markdown Source"):md_raw_doc = gr.Code(label="Markdown Source Code", language="markdown")
app.py+40-48