Update app.py
Browse files1234567891011121314151617181920212223242526272829304 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869705 unmodified lines76777879808182import gradio as grimport cv2import numpy as npimport osfrom huggingface_hub import snapshot_download# --- KEY FIX: Use the standard PPStructure class ---# The 'PPStructureV3' class is currently broken/strict in the PyPI release.# The standard 'PPStructure' class is stable and CAN load V3 weights# because it reads the architecture from the downloaded inference.yml file.from paddleocr import PPStructure# --- STEP 1: Download the V3 Model ---print("Downloading PP-DocLayoutV3 from Hugging Face...")model_path = snapshot_download(repo_id="PaddlePaddle/PP-DocLayoutV3", allow_patterns=["*.pdiparams", "*.pdmodel", "*.yml", "*.json"])print(f"Model downloaded to: {model_path}")# --- STEP 2: Initialize ---# We use the stable class but point 'layout_model_dir' to your V3 download.layout_engine = PPStructure(layout_model_dir=model_path, # This argument is valid in the standard classuse_angle_cls=True,enable_mkldnn=False, # Keeps your CPU from crashingshow_log=False, # Explicitly False to avoid "Unknown Argument" error# We disable these extra modules to focus strictly on layout analysis speedtable=False,ocr=False)def analyze_layout(input_image):4 unmodified lines# Run Inferencetry:# The standard class returns a list of results directlyresult = layout_engine(image_np)except Exception as e:return image_np, f"Error running layout analysis: {e}"viz_image = image_np.copy()detections_text = []if not result:return viz_image, "No layout detected."# --- STEP 3: Visualize ---for region in result:# PPStructure V2/Standard output format: dict with 'type', 'bbox', 'img'# Note: V3 model output via V2 class might label keys slightly differently,# so we check for both standard sets of keys.box = region.get('bbox')label = region.get('type') or region.get('label')if box is None: continuetry:x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3])# Color codingcolor = (0, 255, 0) # Text (Green)if label == 'title': color = (0, 0, 255) # Title (Red)elif label == 'figure': color = (255, 0, 0) # Figure (Blue)elif label == 'table': color = (255, 255, 0)# Table (Cyan)cv2.rectangle(viz_image, (x1, y1), (x2, y2), color, 3)cv2.putText(viz_image, str(label), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)5 unmodified lineswith gr.Blocks(title="PP-DocLayoutV3 Explorer") as demo:gr.Markdown("## ๐ PP-DocLayoutV3 Explorer")gr.Markdown("Using **PP-DocLayoutV3** weights via the stable engine.")with gr.Row():with gr.Column():12345678910111213144 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535 unmodified lines59606162636465import gradio as grimport cv2import numpy as npfrom paddleocr import PPStructureV3 # Explicitly import the class that exists# --- INITIALIZATION ---# We do NOT pass a custom model path. We let PPStructureV3 download its own default model.# This avoids the "ValueError: Unknown argument" crashes.layout_engine = PPStructureV3(use_doc_orientation_classify=True, # Standard V3 argument for orientationenable_mkldnn=False # CRITICAL: Keeps CPU from crashing)def analyze_layout(input_image):4 unmodified lines# Run Inferencetry:# V3 returns a generator, so we convert to list immediatelyresults = list(layout_engine(image_np))except Exception as e:return image_np, f"Error running layout analysis: {e}"viz_image = image_np.copy()detections_text = []if not results:return viz_image, "No layout detected."# --- VISUALIZATION ---for region in results:if not isinstance(region, dict): continue# V3 usually puts the box in 'layout_bbox' or 'bbox'box = region.get('layout_bbox') or region.get('bbox')label = region.get('label', 'unknown')if box is None: continuetry:x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3])# Color codingcolor = (0, 255, 0) # Green (Default)if label == 'title': color = (0, 0, 255) # Redelif label == 'figure': color = (255, 0, 0) # Blueelif label == 'table': color = (255, 255, 0)# Cyancv2.rectangle(viz_image, (x1, y1), (x2, y2), color, 3)cv2.putText(viz_image, str(label), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)5 unmodified lineswith gr.Blocks(title="PP-DocLayoutV3 Explorer") as demo:gr.Markdown("## ๐ PP-DocLayoutV3 Explorer")gr.Markdown("Auto-downloading the latest V3 weights for structure analysis.")with gr.Row():with gr.Column():
app.py+22-39