Spaces:
Runtime error
Runtime error
Update app.py
Browse files53 unmodified lines54555657585950 unmodified lines11011111211311411511611711811912012111 unmodified lines13313413513613713813914014114214355 unmodified lines1992002012022032042052062072082092102112122134 unmodified lines2182192202212222232242252262272282292302312322332342352362372 unmodified lines2402412422432442451 unmodified line2472482492502512522532542552562572582592602612622632642652662672682694 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153166 unmodified lines32332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445553 unmodified linescurrent_model = Nonecurrent_processor = Nonecurrent_model_name = Nonedef colormap(N=256, normalized=False):"""Generate dynamic colormap."""50 unmodified linesreturn torch.tensor(keep, dtype=torch.long)def load_model(model_name):"""Load the selected model automatically."""global current_model, current_processor, current_model_nameif current_model_name == model_name:return current_model, current_processortry:model_info = MODELS[model_name]11 unmodified linescurrent_model = modelcurrent_model_name = model_namereturn model, processorexcept Exception as e:print(f"Error loading model: {e}")return None, Nonedef visualize_bbox(image_input, bboxes, classes, scores, id_to_names, alpha=0.3, show_labels=True):"""Visualize bounding boxes with OpenCV."""55 unmodified linesreturn cv2.cvtColor(image, cv2.COLOR_BGR2RGB)def process_image(input_img, model_name, conf_threshold, iou_threshold, nms_method, alpha, show_labels):"""Process image with document layout detection."""if input_img is None:return None, "โ Please upload an image first."# Load model if neededmodel, processor = load_model(model_name)if model is None or processor is None:return None, f"โ Error loading model {model_name}."try:# Prepare image4 unmodified linesinput_img = input_img.convert('RGB')# Process with modelinputs = processor(images=[input_img], return_tensors="pt")inputs = {k: v.to(device) for k, v in inputs.items()}with torch.no_grad():outputs = model(**inputs)# Post-process resultsresults = processor.post_process_object_detection(outputs,target_sizes=torch.tensor([input_img.size[::-1]]),threshold=conf_threshold,)if not results or len(results) == 0:return np.array(input_img), "โน๏ธ No detections found."result = results[0]2 unmodified lineslabels = result["labels"]if len(boxes) == 0:return np.array(input_img), f"โน๏ธ No detections above threshold {conf_threshold:.2f}."# Apply NMS1 unmodified lineif nms_method == "Custom IoMin":keep_indices = nms_custom(boxes=boxes, scores=scores, iou_threshold=iou_threshold)else:# Use torchvision NMS with correct formatkeep_indices = torchvision.ops.nms(boxes, scores, iou_threshold)boxes = boxes[keep_indices]scores = scores[keep_indices]labels = labels[keep_indices]# Visualize resultsoutput = visualize_bbox(input_img, boxes, labels, scores, classes_map, alpha=alpha, show_labels=show_labels)labels_status = "with labels" if show_labels else "without labels"info = f"โ Found {len(boxes)} detections ({labels_status}) | Model: {model_name} | Confidence: {conf_threshold:.2f}"return output, infoexcept Exception as e:print(f"[ERROR] process_image failed: {e}")error_msg = f"โ Processing error: {str(e)}"if input_img is not None:return np.array(input_img), error_msg4 unmodified linesprint(f"๐ฑ Device: {device}")print(f"๐ค Available models: {len(MODELS)}")# Custom CSS for compact layoutcustom_css = """.gradio-container {max-width: 1400px !important;margin: 0 auto !important;padding: 20px !important;}.controls-container {background: #f8f9fa;border-radius: 12px;border: 1px solid #dee2e6;padding: 20px;margin-bottom: 20px;}.results-container {background: #ffffff;border-radius: 12px;border: 1px solid #dee2e6;padding: 20px;}.section-divider {border-top: 2px solid #e9ecef;margin: 20px 0;padding-top: 20px;}.analyze-btn {background: linear-gradient(45deg, #667eea, #764ba2) !important;border: none !important;color: white !important;font-weight: bold !important;font-size: 18px !important;padding: 15px 30px !important;border-radius: 10px !important;}"""6 unmodified lines# Headergr.HTML("""<div style='text-align: center; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px; margin-bottom: 30px;'><h1 style='margin: 0; font-size: 2.5em; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);'>๐ Document Layout Analysis</h1><p style='margin: 10px 0 0 0; font-size: 1.2em; opacity: 0.9;'>Compact interface for advanced document structure detection</p></div>""")# LEFT COLUMN - Controls and Inputwith gr.Column(scale=1):# Controls Sectionwith gr.Group(elem_classes=["controls-container"]):# 1. Image Upload (First)gr.HTML("<h3 style='margin-top: 0;'>๐ Upload Document</h3>")input_img = gr.Image(label="Document Image",type="pil",height=300,interactive=True)# Dividergr.HTML("<div class='section-divider'></div>")# 2. Model Selection (Second)gr.HTML("<h3>๐ค Model Selection</h3>")model_dropdown = gr.Dropdown(choices=list(MODELS.keys()),value="Egret XLarge",label="AI Model",info="Model will load automatically when analyzing",interactive=True)# Dividergr.HTML("<div class='section-divider'></div>")# 3. Detection Parameters (Third)gr.HTML("<h3>โ๏ธ Detection Settings</h3>")with gr.Row():conf_threshold = gr.Slider(minimum=0.0,maximum=1.0,value=0.6,step=0.05,label="Confidence Threshold",info="Minimum confidence for detections")iou_threshold = gr.Slider(minimum=0.0,maximum=1.0,value=0.5,step=0.05,label="NMS IoU Threshold",info="Non-maximum suppression threshold")with gr.Row():nms_method = gr.Radio(choices=["Custom IoMin", "Standard IoU"],value="Custom IoMin",label="NMS Algorithm",info="Choose suppression method")alpha_slider = gr.Slider(minimum=0.0,maximum=1.0,value=0.3,step=0.1,label="Overlay Transparency",info="Transparency of detection overlays")show_labels_checkbox = gr.Checkbox(value=True,label="Show Class Labels and Confidence Scores",info="Display detection labels on the output image",interactive=True)# Dividergr.HTML("<div class='section-divider'></div>")# 4. Analyze Button (Last)detect_btn = gr.Button("๐ Analyze Document",variant="primary",size="lg",elem_classes=["analyze-btn"])# RIGHT COLUMN - Results and Outputwith gr.Column(scale=1):# Results Sectionwith gr.Group(elem_classes=["results-container"]):gr.HTML("<h3 style='margin-top: 0;'>๐ฏ Analysis Results</h3>")output_img = gr.Image(label="Analyzed Document",type="numpy",height=600,interactive=False)detection_info = gr.Textbox(label="Detection Summary",value="Ready for analysis. Upload an image and click 'Analyze Document'.",interactive=False,lines=2,show_copy_button=True)# Event Handlerdetect_btn.click(fn=process_image,inputs=[input_img,model_dropdown,conf_threshold,iou_threshold,nms_method,alpha_slider,show_labels_checkbox],outputs=[output_img, detection_info])53 unmodified lines5455565758596050 unmodified lines11111211311411511611711811912012112211 unmodified lines13413513613713813914014114214314455 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302314 unmodified lines2362372382392402412422432442452462472482492502512522532542552562 unmodified lines2592602612622632642651 unmodified line2672682692702712722732742752762772782792802812822832842852862872882892902912924 unmodified lines2972982993003013023033043053063073083093103113123133143153163173183193203213223236 unmodified lines33033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144253 unmodified linescurrent_model = Nonecurrent_processor = Nonecurrent_model_name = Nonecached_results = None # Para guardar los resultados y poder cambiar labels sin reprocesardef colormap(N=256, normalized=False):"""Generate dynamic colormap."""50 unmodified linesreturn torch.tensor(keep, dtype=torch.long)def load_model_if_needed(model_name):"""Load the selected model if not already loaded."""global current_model, current_processor, current_model_nameif current_model_name == model_name and current_model is not None:return Truetry:model_info = MODELS[model_name]11 unmodified linescurrent_model = modelcurrent_model_name = model_namereturn Trueexcept Exception as e:print(f"Error loading model: {e}")return Falsedef visualize_bbox(image_input, bboxes, classes, scores, id_to_names, alpha=0.3, show_labels=True):"""Visualize bounding boxes with OpenCV."""55 unmodified linesreturn cv2.cvtColor(image, cv2.COLOR_BGR2RGB)def toggle_labels_visualization(show_labels, alpha):"""Toggle labels without reprocessing the image."""global cached_resultsif cached_results is None:return None, "โ ๏ธ No cached results. Please analyze an image first."input_img, boxes, labels, scores = cached_resultsoutput = visualize_bbox(input_img, boxes, labels, scores, classes_map, alpha=alpha, show_labels=show_labels)labels_status = "with labels" if show_labels else "without labels"info = f"โ Visualization updated ({labels_status}) | {len(boxes)} detections"return output, infodef process_image(input_img, model_name, conf_threshold, iou_threshold, nms_method, alpha, show_labels):"""Process image with document layout detection."""global cached_resultsif input_img is None:return None, "โ Please upload an image first."# Load model if neededif not load_model_if_needed(model_name):return None, f"โ Failed to load model {model_name}."try:# Prepare image4 unmodified linesinput_img = input_img.convert('RGB')# Process with modelinputs = current_processor(images=[input_img], return_tensors="pt")inputs = {k: v.to(device) for k, v in inputs.items()}with torch.no_grad():outputs = current_model(**inputs)# Post-process resultsresults = current_processor.post_process_object_detection(outputs,target_sizes=torch.tensor([input_img.size[::-1]]),threshold=conf_threshold,)if not results or len(results) == 0:cached_results = Nonereturn np.array(input_img), "โน๏ธ No detections found."result = results[0]2 unmodified lineslabels = result["labels"]if len(boxes) == 0:cached_results = Nonereturn np.array(input_img), f"โน๏ธ No detections above threshold {conf_threshold:.2f}."# Apply NMS1 unmodified lineif nms_method == "Custom IoMin":keep_indices = nms_custom(boxes=boxes, scores=scores, iou_threshold=iou_threshold)else:keep_indices = torchvision.ops.nms(boxes, scores, iou_threshold)boxes = boxes[keep_indices]scores = scores[keep_indices]labels = labels[keep_indices]# Cache results for label togglingcached_results = (input_img, boxes, labels, scores)# Visualize resultsoutput = visualize_bbox(input_img, boxes, labels, scores, classes_map, alpha=alpha, show_labels=show_labels)labels_status = "with labels" if show_labels else "without labels"info = f"โ Found {len(boxes)} detections ({labels_status}) | Model: {model_name} | NMS: {nms_method} | Conf: {conf_threshold:.2f}"return output, infoexcept Exception as e:print(f"[ERROR] process_image failed: {e}")cached_results = Noneerror_msg = f"โ Processing error: {str(e)}"if input_img is not None:return np.array(input_img), error_msg4 unmodified linesprint(f"๐ฑ Device: {device}")print(f"๐ค Available models: {len(MODELS)}")# Custom CSS for clean layoutcustom_css = """.gradio-container {max-width: 100% !important;padding: 15px !important;}.control-panel {background: #f8f9fa;border-radius: 12px;border: 1px solid #e9ecef;padding: 20px;margin-bottom: 15px;}.results-panel {background: #f8f9fa;border-radius: 12px;border: 1px solid #e9ecef;padding: 20px;min-height: 600px;}"""6 unmodified lines# Headergr.HTML("""<div style='text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 12px; margin-bottom: 20px;'><h1 style='margin: 0; font-size: 2.5em;'>๐ Document Layout Analysis</h1><p style='margin: 8px 0 0 0; font-size: 1.1em; opacity: 0.9;'>Advanced document structure detection</p></div>""")# Main content in two columnswith gr.Row():# LEFT COLUMN - Controls (more compact)with gr.Column(scale=1):with gr.Group(elem_classes=["control-panel"]):# 1. Image Upload (first)gr.HTML("<h3>๐ Upload Image</h3>")input_img = gr.Image(label="Document Image",type="pil",height=300,interactive=True)gr.HTML("<br><h3>๐ค Model Selection</h3>")# 2. Model Selection (second, without buttons)model_dropdown = gr.Dropdown(choices=list(MODELS.keys()),value="Egret XLarge",label="AI Model",info="Model will be loaded automatically",interactive=True)gr.HTML("<br><h3>โ๏ธ Parameters</h3>")# 3. All parameters together (third)with gr.Row():conf_threshold = gr.Slider(minimum=0.0, maximum=1.0, value=0.6, step=0.05,label="Confidence", info="Detection threshold")iou_threshold = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, step=0.05,label="NMS IoU", info="Suppression threshold")with gr.Row():nms_method = gr.Radio(choices=["Custom IoMin", "Standard IoU"],value="Custom IoMin",label="NMS Method", scale=2)alpha_slider = gr.Slider(minimum=0.0, maximum=1.0, value=0.3, step=0.1,label="Transparency", scale=1)gr.HTML("<br>")# 4. Analyze button (last)analyze_btn = gr.Button("๐ Analyze Document", variant="primary", size="lg")# RIGHT COLUMN - Resultswith gr.Column(scale=1):with gr.Group(elem_classes=["results-panel"]):gr.HTML("<h3>๐ฏ Analysis Results</h3>")output_img = gr.Image(label="Detected Layout",type="numpy",height=450,interactive=False)detection_info = gr.Textbox(label="Detection Summary",value="",interactive=False,lines=2,placeholder="Results will appear here...")# Labels toggle (independent control)gr.HTML("<h4>๐จ Visualization</h4>")show_labels_checkbox = gr.Checkbox(value=True,label="Show Class Labels",info="Toggle labels without reprocessing",interactive=True)# Event Handlers# Main analysis (full processing)analyze_btn.click(fn=process_image,inputs=[input_img, model_dropdown, conf_threshold, iou_threshold, nms_method, alpha_slider, show_labels_checkbox],outputs=[output_img, detection_info])# Independent label toggle (no reprocessing)show_labels_checkbox.change(fn=toggle_labels_visualization,inputs=[show_labels_checkbox, alpha_slider],outputs=[output_img, detection_info])# Also update visualization when transparency changes (if we have cached results)alpha_slider.change(fn=toggle_labels_visualization,inputs=[show_labels_checkbox, alpha_slider],outputs=[output_img, detection_info])
app.py+143-156