Spaces:
Running
Running
File size: 21,556 Bytes
0a4f1a6 0fec4be 0a4f1a6 0fec4be 9d0759c 9e65713 0a4f1a6 0fec4be 9d0759c 0a4f1a6 9d0759c 0fec4be 0a4f1a6 9d0759c 0fec4be 0a4f1a6 9d0759c 0a4f1a6 0fec4be 0a4f1a6 0fec4be 0a4f1a6 0fec4be 0a4f1a6 0fec4be 0a4f1a6 0fec4be 0a4f1a6 0fec4be 0a4f1a6 9d0759c 0a4f1a6 9d0759c 0a4f1a6 9e65713 9d0759c 0fec4be 0a4f1a6 9d0759c 9e65713 0fec4be 0a4f1a6 0fec4be 0a4f1a6 9d0759c 0a4f1a6 0fec4be 9d0759c 0fec4be 9d0759c 0a4f1a6 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c 9e65713 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9e65713 0fec4be 9d0759c 9e65713 0fec4be 9d0759c 9e65713 0fec4be 9e65713 0fec4be 9d0759c 0fec4be 9d0759c 0fec4be 9e65713 0fec4be 9d0759c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 |
"""Multi-file processing utilities for batch inference.
Handles multiple file uploads and iterative processing.
Supports TXT, CSV, and JSON file formats with automatic detection."""
from typing import List, Dict, Any, Tuple, Optional, Union
import time
import streamlit as st
import numpy as np
import pandas as pd
import json
import csv
import io
from pathlib import Path
from .preprocessing import resample_spectrum
from .errors import ErrorHandler, safe_execute
from .results_manager import ResultsManager
from .confidence import calculate_softmax_confidence
def detect_file_format(filename: str, content: str) -> str:
"""Automatically detect file format based on exstention and content
Args:
filename: Name of the file
content: Content of the file
Returns:
File format: .'txt', .'csv', .'json'
"""
# First try by extension
suffix = Path(filename).suffix.lower()
if suffix == ".json":
try:
json.loads(content)
return "json"
except:
pass
elif suffix == ".csv":
return "csv"
elif suffix == ".txt":
return "txt"
# If extension doesn't match or is unclear, try content detection
content_stripped = content.strip()
# Try JSON
if content_stripped.startswith(("{", "[")):
try:
json.loads(content)
return "json"
except:
pass
# Try CSV (look for commas in first few lines)
lines = content_stripped.split("\n")[:5]
comma_count = sum(line.count(",") for line in lines)
if comma_count > len(lines): # More commas than lines suggests CSV
return "csv"
# Default to TXT
return "txt"
# /////////////////////////////////////////////////////
def parse_json_spectrum(
content: str, filename: str = "unknown"
) -> Tuple[np.ndarray, np.ndarray]:
"""
Parse spectrum data from JSON format.
Expected formats:
- {"wavenumbers": [...], "intensities": [...]}
- {"x": [...], "y": [...]}
- [{"wavenumber": val, "intensity": val}, ...]
"""
try:
data = json.load(content)
# Format 1: Object with arrays
if isinstance(data, dict):
x_key = None
y_key = None
# Try common key names for x-axis
for key in ["wavenumbers", "wavenumber", "x", "freq", "frequency"]:
if key in data:
x_key = key
break
# Try common key names for y-axis
for key in ["intensities", "intensity", "y", "counts", "absorbance"]:
if key in data:
y_key = key
break
if x_key and y_key:
x_vals = np.array(data[x_key], dtype=float)
y_vals = np.array(data[y_key], dtype=float)
return x_vals, y_vals
# Format 2: Array of objects
elif isinstance(data, list) and len(data) > 0 and isinstance(data[0], dict):
x_vals = []
y_vals = []
for item in data:
# Try to find x and y values
x_val = None
y_val = None
for x_key in ["wavenumber", "wavenumbers", "x", "freq"]:
if x_key in item:
x_val = float(item[x_key])
break
for y_key in ["intensity", "intensities", "y", "counts"]:
if y_key in item:
y_val = float(item[y_key])
break
if x_val is not None and y_val is not None:
x_vals.append(x_val)
y_vals.append(y_val)
if x_vals and y_vals:
return np.array(x_vals), np.array(y_vals)
raise ValueError(
"JSON format not recognized. Expected wavenumber/intensity pairs."
)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON format: {str(e)}")
except Exception as e:
raise ValueError(f"Failed to parse JSON spectrum: {str(e)}")
# /////////////////////////////////////////////////////
def parse_csv_spectrum(
content: str, filename: str = "unknown"
) -> Tuple[np.ndarray, np.ndarray]:
"""
Parse spectrum data from CSV format.
Handles various CSV formats with headers or without.
"""
try:
# Use StringIO to treat string as file-like object
csv_file = io.StringIO(content)
# Try to detect delimiter
sample = content[:1024]
delimiter = ","
if sample.count(";") > sample.count(","):
delimiter = ";"
elif sample.count("\t") > sample.count(","):
delimiter = "\t"
# Read CSV
csv_reader = csv.reader(csv_file, delimiter=delimiter)
rows = list(csv_reader)
if not rows:
raise ValueError("Empty CSV file")
# Check if first row is header
has_header = False
try:
# If first row contains non-numeric data, it's likely a header
float(rows[0][0])
float(rows[0][1])
except (ValueError, IndexError):
has_header = True
data_rows = rows[1:] if has_header else rows
# Extract x and y values
x_vals = []
y_vals = []
for i, row in enumerate(data_rows):
if len(row) < 2:
continue
try:
x_val = float(row[0])
y_val = float(row[1])
x_vals.append(x_val)
y_vals.append(y_val)
except ValueError:
ErrorHandler.log_warning(
f"Could not parse CSV row {i+1}: {row}", f"Parsing {filename}"
)
continue
if len(x_vals) < 10:
raise ValueError(
f"Insufficient data points ({len(x_vals)}). Need at least 10 points."
)
return np.array(x_vals), np.array(y_vals)
except Exception as e:
raise ValueError(f"Failed to parse CSV spectrum: {str(e)}")
# /////////////////////////////////////////////////////
def parse_spectrum_data(
text_content: str, filename: str = "unknown", file_format: Optional[str] = None
) -> Tuple[np.ndarray, np.ndarray]:
"""
Parse spectrum data from text content with automatic format detection.
Args:
text_content: Raw text content of the spectrum file
filename: Name of the file for error reporting
file_format: Force specific format ('txt', 'csv', 'json') or None for auto-detection
Returns:
Tuple of (x_values, y_values) as numpy arrays
Raises:
ValueError: If the data cannot be parsed
"""
try:
# Detect format if not specified
if file_format is None:
file_format = detect_file_format(filename, text_content)
# Parse based on detected/specified format
if file_format == "json":
x, y = parse_json_spectrum(text_content, filename)
elif file_format == "csv":
x, y = parse_csv_spectrum(text_content, filename)
else: # Default to TXT format
x, y = parse_txt_spectrum(text_content, filename)
# Common validation for all formats
validate_spectrum_data(x, y, filename)
return x, y
except Exception as e:
raise ValueError(f"Failed to parse spectrum data: {str(e)}")
# /////////////////////////////////////////////////////
def parse_txt_spectrum(
content: str, filename: str = "unknown"
) -> Tuple[np.ndarray, np.ndarray]:
"""
Parse spectrum data from TXT format (original implementation).
"""
lines = content.strip().split("\n")
# ==Remove empty lines and comments==
data_lines = []
for line in lines:
line = line.strip()
if line and not line.startswith("#") and not line.startswith("%"):
data_lines.append(line)
if not data_lines:
raise ValueError("No data lines found in file")
# ==Try to parse==
x_vals, y_vals = [], []
for i, line in enumerate(data_lines):
try:
# Handle different separators
parts = line.replace(",", " ").split()
numbers = [
p
for p in parts
if p.replace(".", "", 1)
.replace("-", "", 1)
.replace("+", "", 1)
.isdigit()
]
if len(numbers) >= 2:
x_val = float(numbers[0])
y_val = float(numbers[1])
x_vals.append(x_val)
y_vals.append(y_val)
except ValueError:
ErrorHandler.log_warning(
f"Could not parse line {i+1}: {line}", f"Parsing {filename}"
)
continue
if len(x_vals) < 10: # ==Need minimum points for interpolation==
raise ValueError(
f"Insufficient data points ({len(x_vals)}). Need at least 10 points."
)
return np.array(x_vals), np.array(y_vals)
# /////////////////////////////////////////////////////
def validate_spectrum_data(x: np.ndarray, y: np.ndarray, filename: str) -> None:
"""
Validate parsed spectrum data for common issues.
"""
# Check for NaNs
if np.any(np.isnan(x)) or np.any(np.isnan(y)):
raise ValueError("Input data contains NaN values")
# Check monotonic increasing x (sort if needed)
if not np.all(np.diff(x) >= 0):
# Sort by x values if not monotonic
sort_idx = np.argsort(x)
x = x[sort_idx]
y = y[sort_idx]
ErrorHandler.log_warning(
"Wavenumbers were not monotonic - data has been sorted",
f"Parsing {filename}",
)
# Check reasonable range for spectroscopy
if min(x) < 0 or max(x) > 10000 or (max(x) - min(x)) < 100:
ErrorHandler.log_warning(
f"Unusual wavenumber range: {min(x):.1f} - {max(x):.1f} cm⁻¹",
f"Parsing {filename}",
)
# /////////////////////////////////////////////////////
def process_single_file(
filename: str,
text_content: str,
model_choice: str,
load_model_func,
run_inference_func,
label_file_func,
) -> Optional[Dict[str, Any]]:
"""
Process a single spectrum file
Args:
filename: Name of the file
text_content: Raw text content
model_choice: Selected model name
load_model_func: Function to load the model
run_inference_func: Function to run inference
label_file_func: Function to extract ground truth label
Returns:
Dictionary with processing results or None if failed
"""
start_time = time.time()
try:
# ==Parse spectrum data==
result, success = safe_execute(
parse_spectrum_data,
text_content,
filename,
error_context=f"parsing {filename}",
show_error=False,
)
if not success or result is None:
return None
x_raw, y_raw = result
# ==Resample spectrum==
result, success = safe_execute(
resample_spectrum,
x_raw,
y_raw,
500, # TARGET_LEN
error_context=f"resampling {filename}",
show_error=False,
)
if not success or result is None:
return None
x_resampled, y_resampled = result
# ==Run inference==
result, success = safe_execute(
run_inference_func,
y_resampled,
model_choice,
error_context=f"inference on {filename}",
show_error=False,
)
if not success or result is None:
ErrorHandler.log_error(
Exception("Inference failed"), f"processing {filename}"
)
return None
prediction, logits_list, probs, inference_time, logits = result
# ==Calculate confidence==
if logits is not None:
probs_np, max_confidence, confidence_level, confidence_emoji = (
calculate_softmax_confidence(logits)
)
else:
probs_np = np.array([])
max_confidence = 0.0
confidence_level = "LOW"
confidence_emoji = "🔴"
# ==Get ground truth==
try:
ground_truth = label_file_func(filename)
ground_truth = ground_truth if ground_truth >= 0 else None
except Exception:
ground_truth = None
# ==Get predicted class==
label_map = {0: "Stable (Unweathered)", 1: "Weathered (Degraded)"}
predicted_class = label_map.get(prediction, f"Unknown ({prediction})")
processing_time = time.time() - start_time
return {
"filename": filename,
"success": True,
"prediction": prediction,
"predicted_class": predicted_class,
"confidence": max_confidence,
"confidence_level": confidence_level,
"confidence_emoji": confidence_emoji,
"logits": logits_list if logits_list else [],
"probabilities": probs_np.tolist() if len(probs_np) > 0 else [],
"ground_truth": ground_truth,
"processing_time": processing_time,
"x_raw": x_raw,
"y_raw": y_raw,
"x_resampled": x_resampled,
"y_resampled": y_resampled,
}
except Exception as e:
ErrorHandler.log_error(e, f"processing {filename}")
return {
"filename": filename,
"success": False,
"error": str(e),
"processing_time": time.time() - start_time,
}
def process_multiple_files(
uploaded_files: List,
model_choice: str,
load_model_func,
run_inference_func,
label_file_func,
progress_callback=None,
) -> List[Dict[str, Any]]:
"""
Process multiple uploaded files
Args:
uploaded_files: List of uploaded file objects
model_choice: Selected model name
load_model_func: Function to load the model
run_inference_func: Function to run inference
label_file_func: Function to extract ground truth label
progress_callback: Optional callback to update progress
Returns:
List of processing results
"""
results = []
total_files = len(uploaded_files)
ErrorHandler.log_info(f"Starting batch processing of {total_files} files")
for i, uploaded_file in enumerate(uploaded_files):
if progress_callback:
progress_callback(i, total_files, uploaded_file.name)
try:
# ==Read file content==
raw = uploaded_file.read()
text_content = raw.decode("utf-8") if isinstance(raw, bytes) else raw
# ==Process the file==
result = process_single_file(
uploaded_file.name,
text_content,
model_choice,
load_model_func,
run_inference_func,
label_file_func,
)
if result:
results.append(result)
# ==Add successful results to the results manager==
if result.get("success", False):
ResultsManager.add_results(
filename=result["filename"],
model_name=model_choice,
prediction=result["prediction"],
predicted_class=result["predicted_class"],
confidence=result["confidence"],
logits=result["logits"],
ground_truth=result["ground_truth"],
processing_time=result["processing_time"],
metadata={
"confidence_level": result["confidence_level"],
"confidence_emoji": result["confidence_emoji"],
},
)
except Exception as e:
ErrorHandler.log_error(e, f"reading file {uploaded_file.name}")
results.append(
{
"filename": uploaded_file.name,
"success": False,
"error": f"Failed to read file: {str(e)}",
}
)
if progress_callback:
progress_callback(total_files, total_files, "Complete")
ErrorHandler.log_info(
f"Completed batch processing: {sum(1 for r in results if r.get('success', False))}/{total_files} successful"
)
return results
def display_batch_results(batch_results: list):
"""Renders a clean, consolidated summary of batch processing results using metrics and a pandas DataFrame replacing the old expander list"""
if not batch_results:
st.info("No batch results to display.")
return
successful_runs = [r for r in batch_results if r.get("success", False)]
failed_runs = [r for r in batch_results if not r.get("success", False)]
# 1. High Level Metrics
st.markdown("###### Batch Summary")
metric_cols = st.columns(3)
metric_cols[0].metric("Total Files Processed", f"{len(batch_results)}")
metric_cols[1].metric("✔️ Successful", f"{len(successful_runs)}")
metric_cols[2].metric("❌ Failed", f"{len(failed_runs)}")
# 3 Hidden Failure Details
if failed_runs:
with st.expander(
f"View details for {len(failed_runs)} failed file(s)", expanded=False
):
for r in failed_runs:
st.error(f"**File:** `{r.get('filename', 'unknown')}`")
st.caption(
f"Reason for failure: {r.get('error', 'No details provided')}"
)
# Legacy display batch results
# def display_batch_results(results: List[Dict[str, Any]]) -> None:
# """
# Display batch processing results in the UI
# Args:
# results: List of processing results
# """
# if not results:
# st.warning("No results to display")
# return
# successful = [r for r in results if r.get("success", False)]
# failed = [r for r in results if not r.get("success", False)]
# # ==Summary==
# col1, col2, col3 = st.columns(3, border=True)
# with col1:
# st.metric("Total Files", len(results))
# with col2:
# st.metric("Successful", len(successful),
# delta=f"{len(successful)/len(results)*100:.1f}%")
# with col3:
# st.metric("Failed", len(
# failed), delta=f"-{len(failed)/len(results)*100:.1f}%" if failed else "0%")
# # ==Results tabs==
# tab1, tab2 = st.tabs(["✅Successful", "❌ Failed"], width="stretch")
# with tab1:
# with st.expander("Successful"):
# if successful:
# for result in successful:
# with st.expander(f"{result['filename']}", expanded=False):
# col1, col2 = st.columns(2)
# with col1:
# st.write(
# f"**Prediction:** {result['predicted_class']}")
# st.write(
# f"**Confidence:** {result['confidence_emoji']} {result['confidence_level']} ({result['confidence']:.3f})")
# with col2:
# st.write(
# f"**Processing Time:** {result['processing_time']:.3f}s")
# if result['ground_truth'] is not None:
# gt_label = {0: "Stable", 1: "Weathered"}.get(
# result['ground_truth'], "Unknown")
# correct = "✅" if result['prediction'] == result['ground_truth'] else "❌"
# st.write(
# f"**Ground Truth:** {gt_label} {correct}")
# else:
# st.info("No successful results")
# with tab2:
# if failed:
# for result in failed:
# with st.expander(f"❌ {result['filename']}", expanded=False):
# st.error(f"Error: {result.get('error', 'Unknown error')}")
# else:
# st.success("No failed files!")
def create_batch_uploader() -> List:
"""
Create multi-file uploader widget
Returns:
List of uploaded files
"""
uploaded_files = st.file_uploader(
"Upload multiple Raman spectrum files (.txt)",
type="txt",
accept_multiple_files=True,
help="Select multiple .txt files with wavenumber and intensity columns",
key="batch_uploader",
)
return uploaded_files if uploaded_files else []
|