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 lines105610571058105910601061106234 unmodified lines109710981099110011011102110311 unmodified lines111511161117111811191120112111224 unmodified lines11271128112911301131113222 unmodified lines1155115611571158115911601055 unmodified linesuser_id=current_user.id,details=f"batch_id={batch_id}, files={len(dcm_paths)}",)return redirect(url_for("batch_progress", batch_id=batch_id))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 linesuser_id=current_user.id,details=f"batch_id={batch_id}, files={len(dcm_paths)}",)return redirect(url_for("batch_progress", batch_id=batch_id))except Exception:logger.error("Celery unavailable; running synchronous directory scan", exc_info=True)flash("Celery worker unavailable. Running directory scan synchronously.", "warning")11 unmodified linesbatch = _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)@app.route("/batch/<batch_id>/status")@login_required4 unmodified linesreturn jsonify({"error": "Not found"}), 404return jsonify(batch)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,}# Build response matching _BATCHES format for frontend compatibilityif result.state == "PROGRESS":1055 unmodified lines105610571058105910601061106234 unmodified lines109710981099110011011102110311 unmodified lines1115111611171118111911201121112211231124112511261127112811294 unmodified lines1134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115922 unmodified lines11821183118411851186118711881189119011911192119311941195119611971198119912001201120212031055 unmodified linesuser_id=current_user.id,details=f"batch_id={batch_id}, files={len(dcm_paths)}",)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 linesuser_id=current_user.id,details=f"batch_id={batch_id}, files={len(dcm_paths)}",)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 linesbatch = _get_batch_from_celery(batch_id)if not batch or batch.get("user_id") != current_user.id:abort(404)expected_total = request.args.get("total", type=int)if expected_total and (batch.get("total") or 0) == 0:batch["total"] = expected_totalreturn 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 linesreturn jsonify({"error": "Not found"}), 404return 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"}), 500def _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 compatibilityif result.state == "PROGRESS":
91 unmodified lines92939495969791 unmodified linesreturn False, "OTP purpose mismatch. Please request a new code.", Noneexpires_raw = payload.get("expires_at")try:expires_at = datetime.fromisoformat(expires_raw)except Exception:91 unmodified lines929394959697989910091 unmodified linesreturn False, "OTP purpose mismatch. Please request a new code.", Noneexpires_raw = payload.get("expires_at")if not expires_raw:_clear_otp()return False, "OTP is invalid. Please request a new code.", Nonetry:expires_at = datetime.fromisoformat(expires_raw)except Exception:
962 unmodified lines963964965966967968962 unmodified lines.batch-header {margin-bottom: 20px;}.batch-header h1 {font-size: 1.6rem;font-weight: 800;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 lines78910111211 unmodified lines2425262728293031323334353637383940414243448 unmodified lines53545556575816 unmodified lines7576777879808182838485866 unmodified linesvar statusUrl = page.dataset.statusUrl;var pollMs = 1000;var title = document.getElementById('batchTitle');var subtitle = document.getElementById('batchSubtitle');11 unmodified linesvar doneSummary = document.getElementById('doneSummary');var failPanel = document.getElementById('failPanel');var failList = document.getElementById('failList');var prevIds = [];if (!statusUrl || !title || !subtitle || !fill || !pctLabel || !currentFile || !statTotal || !statProc || !statOK || !statFail || !feedPanel || !feedList || !donePanel || !doneSummary || !failPanel || !failList) {return;}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;statTotal.textContent = data.total;statProc.textContent = data.processed;statOK.textContent = data.succeeded;statFail.textContent = data.failed_ids ? data.failed_ids.length : 0;8 unmodified lines}}fill.style.width = pct + '%';pctLabel.textContent = pct + '%';currentFile.textContent = data.current_file ? 'Processing: ' + data.current_file : '';16 unmodified lines});}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' : '') + '.';if (data.failed_ids && data.failed_ids.length) {failPanel.style.display = 'block';6 unmodified lines789101112131411 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475768 unmodified lines8586878889909192939416 unmodified lines1111121131141151161171181191201211221231241251261271286 unmodified linesvar 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 linesvar 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) {if (canceled) {return;}var total = data.total > 0 ? data.total : expectedTotal;var pct = total > 0 ? Math.round(data.processed / total * 100) : 0;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 ' + total + ' files processed successfully' + (failCount > 0 ? ', ' + failCount + ' failed' : '') + '.';if (data.failed_ids && data.failed_ids.length) {failPanel.style.display = 'block';
2 unmodified lines34567895 unmodified lines151617181920212223242526271 unmodified line293031323334352 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') }}"><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.</p><p class="muted" id="queueStatus">{% if batch.queue_size is not none %}Queue size: {{ batch.queue_size }}{% endif %}</p></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></div><div class="batch-stat"><span class="batch-stat-label">Processed</span>2 unmodified lines34567891011121314155 unmodified lines212223242526272829303132333435361 unmodified line383940414243442 unmodified lines{% block title %}Batch Processing β AI Medical Intelligence Pipeline{% endblock %}{% block content %}{% 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 {{ 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">{{ 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