Spaces:
Sleeping
Sleeping
Harshit Ghosh Copilot commited on
Commit Β·
46811bc
1
Parent(s): 5105d0e
progress and cancel
Browse filesCo-authored-by: Copilot <copilot@github.com>
Files changed (5)
1055 unmodified lines1056105710581059105910601061106234 unmodified lines1097109810991100110011011102110311 unmodified lines111511161117111811191118111911201121112211231124112511261127112811294 unmodified lines1134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115922 unmodified lines11821183118411851186118711881189119011911192119311941195119611971198119912001201120212031055 unmodified lines user_id=current_user.id, details=f"batch_id={batch_id}, files={len(dcm_paths)}", ) return redirect(url_for("batch_progress", batch_id=batch_id)) return redirect(url_for("batch_progress", batch_id=batch_id, total=len(dcm_paths))) except Exception: logger.error("Celery unavailable; running synchronous fallback", exc_info=True) flash("Celery worker unavailable. Running batch synchronously; this may take a while.", "warning")34 unmodified lines user_id=current_user.id, details=f"batch_id={batch_id}, files={len(dcm_paths)}", ) return redirect(url_for("batch_progress", batch_id=batch_id)) return redirect(url_for("batch_progress", batch_id=batch_id, total=len(dcm_paths))) except Exception: logger.error("Celery unavailable; running synchronous directory scan", exc_info=True) flash("Celery worker unavailable. Running directory scan synchronously.", "warning")11 unmodified lines batch = _get_batch_from_celery(batch_id) if not batch or batch.get("user_id") != current_user.id: abort(404) return render_template("batch_progress.html", batch=batch, batch_id=batch_id) expected_total = request.args.get("total", type=int) if expected_total and (batch.get("total") or 0) == 0: batch["total"] = expected_total return render_template( "batch_progress.html", batch=batch, batch_id=batch_id, expected_total=expected_total or 0, )
@app.route("/batch/<batch_id>/status")@login_required4 unmodified lines return jsonify({"error": "Not found"}), 404 return jsonify(batch)
@app.route("/batch/<batch_id>/cancel", methods=["POST"])@login_requireddef cancel_batch(batch_id): """Cancel a running batch task.""" user_id = _extract_user_id_from_batch_id(batch_id) if user_id != current_user.id: abort(404) try: celery_app.control.revoke(batch_id, terminate=True, signal="SIGTERM") log_audit( "batch_canceled", user_id=current_user.id, details=f"batch_id={batch_id}", status="success", ) return jsonify({"status": "canceled"}) except Exception as exc: logger.error("Failed to cancel batch %s: %s", batch_id, exc, exc_info=True) return jsonify({"error": "Cancel failed"}), 500
def _get_batch_from_celery(batch_id: str) -> dict[str, Any] | None: """Retrieve batch status from Celery task result backend.""" # In a production system, we'd also validate user_id from the database22 unmodified lines "error": None, "queue_size": queue_size, } elif result.state == "REVOKED": return { "batch_id": batch_id, "user_id": user_id, "status": "canceled", "total": 0, "processed": 0, "succeeded": 0, "failed_ids": [], "image_ids": [], "current_file": "", "started_at": None, "finished_at": None, "error": None, "queue_size": queue_size, } # Build response matching _BATCHES format for frontend compatibility if result.state == "PROGRESS":91 unmodified lines929394959697989910091 unmodified lines return False, "OTP purpose mismatch. Please request a new code.", None
expires_raw = payload.get("expires_at") if not expires_raw: _clear_otp() return False, "OTP is invalid. Please request a new code.", None try: expires_at = datetime.fromisoformat(expires_raw) except Exception:962 unmodified lines963964965966967968969970971972973962 unmodified lines.batch-header { margin-bottom: 20px;}.batch-header-actions { margin-top: 14px; display: flex; justify-content: flex-end;}.batch-header h1 { font-size: 1.6rem; font-weight: 800;6 unmodified lines789101112131411 unmodified lines26272829303132333435363738394041424344454647484950515253545556575859606162636465396667686970717241737475768 unmodified lines8586878889909192939416 unmodified lines111112113114115116117118119120121122123124831251261271286 unmodified lines
var statusUrl = page.dataset.statusUrl; var pollMs = 1000; var expectedTotal = parseInt(page.dataset.expectedTotal || '0', 10) || 0; var cancelUrl = page.dataset.cancelUrl;
var title = document.getElementById('batchTitle'); var subtitle = document.getElementById('batchSubtitle');11 unmodified lines var doneSummary = document.getElementById('doneSummary'); var failPanel = document.getElementById('failPanel'); var failList = document.getElementById('failList'); var cancelBtn = document.getElementById('cancelBatch'); var prevIds = []; var canceled = false;
if (!statusUrl || !title || !subtitle || !fill || !pctLabel || !currentFile || !statTotal || !statProc || !statOK || !statFail || !feedPanel || !feedList || !donePanel || !doneSummary || !failPanel || !failList) { return; }
if (cancelBtn && cancelUrl) { cancelBtn.addEventListener('click', function () { if (!confirm('Cancel this batch? Any in-progress file may not complete.')) { return; } cancelBtn.disabled = true; fetch(cancelUrl, { method: 'POST' }) .then(function (response) { return response.json(); }) .then(function (data) { canceled = true; title.textContent = 'Batch Canceled'; subtitle.textContent = 'The batch was canceled. You can start a new upload anytime.'; currentFile.textContent = ''; if (queueStatus) { queueStatus.textContent = ''; } }) .catch(function () { cancelBtn.disabled = false; }); }); }
function poll() { fetch(statusUrl) .then(function (response) { return response.json(); }) .then(function (data) { var pct = data.total > 0 ? Math.round(data.processed / data.total * 100) : 0; if (canceled) { return; }
var total = data.total > 0 ? data.total : expectedTotal; var pct = total > 0 ? Math.round(data.processed / total * 100) : 0;
statTotal.textContent = data.total; statTotal.textContent = total; statProc.textContent = data.processed; statOK.textContent = data.succeeded; statFail.textContent = data.failed_ids ? data.failed_ids.length : 0;8 unmodified lines } }
if (data.status === 'pending' && expectedTotal > 0) { subtitle.textContent = 'Queued - waiting for a worker. Total files: ' + expectedTotal + '.'; }
fill.style.width = pct + '%'; pctLabel.textContent = pct + '%'; currentFile.textContent = data.current_file ? 'Processing: ' + data.current_file : '';16 unmodified lines }); }
if (data.status === 'canceled') { title.textContent = 'Batch Canceled'; subtitle.textContent = 'The batch was canceled.'; return; }
if (data.status === 'completed' || data.status === 'failed') { title.textContent = 'Batch Complete'; subtitle.textContent = ''; donePanel.style.display = 'block'; var failCount = data.failed_ids ? data.failed_ids.length : 0; doneSummary.textContent = data.succeeded + ' of ' + data.total + ' files processed successfully' + (failCount > 0 ? ', ' + failCount + ' failed' : '') + '.'; doneSummary.textContent = data.succeeded + ' of ' + total + ' files processed successfully' + (failCount > 0 ? ', ' + failCount + ' failed' : '') + '.';
if (data.failed_ids && data.failed_ids.length) { failPanel.style.display = 'block';2 unmodified lines345667891011121314155 unmodified lines21222318242526272829303132333435361 unmodified line38394032414243442 unmodified lines{% block title %}Batch Processing β AI Medical Intelligence Pipeline{% endblock %}
{% block content %}<div class="batch-page" data-batch-id="{{ batch_id }}" data-status-url="{{ url_for('batch_status', batch_id=batch_id) }}" data-reports-url="{{ url_for('reports') }}">{% set display_total = batch.total if batch.total else (expected_total or 0) %}<div class="batch-page" data-batch-id="{{ batch_id }}" data-status-url="{{ url_for('batch_status', batch_id=batch_id) }}" data-cancel-url="{{ url_for('cancel_batch', batch_id=batch_id) }}" data-reports-url="{{ url_for('reports') }}" data-expected-total="{{ display_total }}"><section class="breadcrumb"> <a href="{{ url_for('home') }}">Home</a> <span class="sep">/</span>5 unmodified lines<section class="batch-header"> <h1 id="batchTitle">Processing Batch…</h1> <p class="muted" id="batchSubtitle"> Analyzing {{ batch.total }} DICOM file{{ 's' if batch.total != 1 }} β please keep this page open. Analyzing {{ display_total }} DICOM file{{ 's' if display_total != 1 }} β please keep this page open. </p> <p class="muted" id="queueStatus"> {% if batch.queue_size is not none %} Queue size: {{ batch.queue_size }} {% endif %} </p> <div class="batch-header-actions"> <button type="button" class="btn btn-outline" id="cancelBatch">Cancel Batch</button> </div></section>
<!-- ββ Progress bar ββββββββββββββββββββββββββββββββββββββββββββββββββ -->1 unmodified line <div class="batch-stats-row"> <div class="batch-stat"> <span class="batch-stat-label">Total</span> <span class="batch-stat-value" id="statTotal">{{ batch.total }}</span> <span class="batch-stat-value" id="statTotal">{{ display_total }}</span> </div> <div class="batch-stat"> <span class="batch-stat-label">Processed</span>app_new.py+47-4
auth_routes.py+3
static/css/pages.css+5
static/js/batch.js+45-3
templates/batch_progress.html+12-3