Spaces:
Sleeping
Sleeping
Commit ·
8f0f112
1
Parent(s): b67be67
feat: upgrade to BacSense v2 with dynamic batch dashboard and UI improvements
Browse filesFiles changed (19)
- BacSense_v2_Technical_Documentation.docx.txtAdded+628
- bacsense_v2_package/class_names.pklAdded+3
- bacsense_v2_package/example_usage.pyAdded+48
- bacsense_v2_package/inference.pyAdded+268
- bacsense_v2_package/pca_model.pklAdded+3
- bacsense_v2_package/requirements.txtAdded+7
- bacsense_v2_package/specialist_metadata.jsonAdded+38
- bacsense_v2_package/specialist_pca.pklAdded+3
- bacsense_v2_package/specialist_scaler.pklAdded+3
- bacsense_v2_package/specialist_svm.pklAdded+3
- bacsense_v2_package/standard_scaler.pklAdded+3
- bacsense_v2_package/svm_classifier.pklAdded+3
- bacsense_v2_package/vgg16_feature_extractor.kerasAdded+3
- frontend/.gitignore+1
- frontend/run_frontend.ps1Added+2
- frontend/src/App.tsx+6-2
- frontend/src/components/Results.tsx+32-37
- frontend/src/components/UploadZone.tsx+196-63
- frontend/vercel.jsonAdded+8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628BacSense v2 | Technical Documentation
BacSenseVersion 2.0Technical Architecture & Model Documentation
Cascaded Hybrid Classifier for Waterborne Bacterial IdentificationVGG16 Transfer Learning + Hand-Crafted Feature Engineering + RBF-SVM
Author Alapan Sen Guide Dr. Nilanjana Dutta Roy Institution Amity University Kolkata Deployed bacsense.streamlit.app Version 2.0 — Cascaded Specialist Date March 2026 ________________
1. Executive SummaryBacSense v2 is a two-stage cascaded hybrid classifier for the identification of five waterborne bacterial species from Gram-stained microscopy images. The system combines deep transfer learning (VGG16) with rich hand-crafted feature engineering and a binary specialist Support Vector Machine to resolve a critical confusion pair that the original single-stage model completely failed on.
Problem: The original BacSense v1 achieved 95.83% overall accuracy but had near-zero F1 scores for Escherichia coli and Pseudomonas aeruginosa — two morphologically similar Gram-negative rods that VGG16 FC features alone could not separate.
Solution: A cascaded architecture that routes ambiguous predictions to a specialist binary SVM trained on a 683-dimensional feature vector combining VGG16 deep features with seven hand-crafted descriptors targeting the discriminative signals invisible to the main model.
Metric v1 (Main SVM only) v2 (Cascaded) Overall Accuracy 95.83% 95.65% E. coli F1 ~0.00 (failing) 0.9568 P. aeruginosa F1 ~0.00 (failing) 0.9563 P. aeruginosa Recall ~0.00 0.9480 Specialist ROC-AUC — 0.9863 CV F1 (Specialist) — 0.9498
________________
2. Dataset2.1 Source: DIBaS (Digital Image of Bacteria Species)The DIBaS dataset, introduced by Zielinski et al. (2017) in PLOS ONE, is the primary source of microscopy images. It contains 660 images across 33 bacterial species captured at 100x magnification with oil immersion. BacSense uses a 5-class subset of 307 original images corresponding to clinically relevant waterborne pathogens.
Species Gram Shape Original Images Risk Level Escherichia coli Negative Rod 59 High Pseudomonas aeruginosa Negative Rod 63 High Enterococcus faecalis Positive Coccus 62 Medium Clostridium perfringens Positive Rod 61 High Listeria monocytogenes Positive Rod 62 High
2.2 Data AugmentationThe original 307 images are insufficient for robust deep feature training. An aggressive augmentation pipeline expands the dataset 18.7x to approximately 5,000 images for main model training. For specialist training, each of the two confusion classes is independently augmented to 800 images.
Parameter Value Rotation range 360 degrees (full circular) Width / height shift 10% Horizontal / vertical flip Enabled Zoom range 15% Brightness range 0.85 – 1.15 Fill mode Reflect Target per class (specialist) 800 augmented + original PNG
For the specialist, original PNG images (59 E. coli + 63 P. aeruginosa) are combined with augmented JPG images during training to prevent domain shift artifacts between file formats. Total specialist training data: 1,722 images.________________
3. System Architecture3.1 Overview: Two-Stage Cascaded DesignBacSense v2 uses a cascaded architecture where a fast 5-class main SVM provides an initial prediction. If that prediction falls within the known confusion pair (E. coli or P. aeruginosa), the image is routed to a dedicated specialist binary SVM that uses a much richer feature representation to make the final call.
Architecture Flow: Input Image → VGG16 Feature Extractor → PCA(94) → Main SVM → [if ambiguous] → 683-dim Feature Extraction → PCA(243) → Specialist SVM → Final Prediction
Stage 1: Main SVM If Ambiguous Stage 2: Specialist Final Output InputRaw image FeaturesVGG16 (512-dim) → PCA (94-dim) TriggerE. coli or P. aeruginosa predicted Features683-dim rich vector → PCA (243-dim) Output5-class or binary species label
3.2 Stage 1: Main Classifier3.2.1 Feature Extractor — VGG16VGG16 is used as a frozen feature extractor with ImageNet pre-trained weights. The top classification layer is removed, and the output of the last global average pooling layer provides a 512-dimensional feature vector for each input image. Images are resized to 128 x 128 pixels and normalized to [0, 1] before passing through the network.
Component Detail Base architecture VGG16 (Simonyan & Zisserman, 2014) Pre-training ImageNet (1.2M images, 1000 classes) Fine-tuning None — weights fully frozen Input size 128 x 128 x 3 (RGB) Output 512-dimensional feature vector
3.2.2 Dimensionality Reduction — PCAPrincipal Component Analysis reduces the 512-dimensional VGG16 output to 94 components while retaining 95% of explained variance. This reduces overfitting risk, lowers SVM training time, and removes correlated feature dimensions that introduce noise into the decision boundary.
3.2.3 Main Classifier — RBF-SVMA Radial Basis Function Support Vector Machine is trained on the PCA-reduced features for 5-class classification. The SVM uses a one-vs-one decision strategy with class-balanced weighting to handle slight class imbalance in the original dataset.
Hyperparameter Value Selection Method Kernel RBF Fixed — standard for high-dim features C (regularization) 10 GridSearchCV, 3-fold CV Gamma 0.01 GridSearchCV, 3-fold CV Class weight Balanced Fixed — handles class imbalance Decision function OVO (one-vs-one) Default for multi-class SVC
________________
4. Stage 2: Specialist Classifier4.1 Motivation — Why a Specialist?E. coli and P. aeruginosa are both Gram-negative, rod-shaped bacteria with similar cell dimensions and staining characteristics. The standard VGG16 FC feature vector collapses their representations into overlapping regions in feature space, producing near-zero F1 scores for both species in the main model. Three peer-reviewed papers converge on the same solution: richer feature concatenation targeting color distribution, texture micropatterns, and spatial arrangement.
Paper Key Finding Feature Applied in BacSense Zielinski et al., 2017 (PLOS ONE) Color distribution features explicitly recommended for morphologically similar species HSV histogram (48-dim) Wahid et al. (Inception-v3 + SVM) Feature concatenation is the principled fix for intra-species confusion Full 683-dim concatenated vector Rachmad et al., 2020 Binary CNN+SVM specialist viable for rod-shaped bacteria Cascaded binary specialist SVM
4.2 Feature Vector — 683 DimensionsThe specialist uses a 683-dimensional feature vector formed by concatenating VGG16 deep features with seven hand-crafted descriptors. Each descriptor targets a specific visual property that differentiates E. coli from P. aeruginosa in Gram-stained images.
Feature Group Dims What It Captures Target Signal VGG16 FC Features 512 Deep semantic representation from ImageNet General shape, high-level patterns HSV Histogram 48 Color distribution across Hue/Sat/Value bins (4x4x3) Stain intensity differences Morphological 5 Area, perimeter, circularity, aspect ratio, solidity Cell shape and size LBP Histogram 59 Local Binary Patterns, P=8, R=1, uniform Texture micropatterns, biofilm GLCM Descriptors 24 Contrast, dissimilarity, homogeneity, energy, correlation, ASM (4 angles) Spatial gray-level co-occurrence Channel Stats 9 Mean, std, skewness per H/S/V channel Fine-grained color statistics Density Grid 16 4x4 spatial grid of foreground pixel density Clustering vs dispersal pattern Hu Moments 7 7 rotation-invariant moment descriptors (log-transformed) Global shape invariants Curvature 3 Mean, std, max curvature across all contour points Rod bending — key P. aeruginosa signal
4.3 Why Each Feature Matters for This PairLBP (Local Binary Patterns)P. aeruginosa is known to form loose biofilm-like clusters under microscopy. LBP captures the local texture microstructure created by these aggregations — a signal completely absent from VGG16 FC features which operate at a semantic rather than textural level.
GLCM (Gray-Level Co-occurrence Matrix)GLCM descriptors computed at four angles (0, 45, 90, 135 degrees) capture the spatial relationship between intensity values across the image. P. aeruginosa typically shows higher local contrast and dissimilarity values due to its clustering behavior and slightly different staining depth.
Curvature StatisticsP. aeruginosa rods tend to exhibit more curvature and bending than E. coli rods, which are typically straighter. Curvature is computed as the cross product of consecutive edge vectors along detected contours, summarized as mean, standard deviation, and maximum curvature values across all contours in the image.
Spatial Density GridA 4x4 grid divides the image into 16 cells and computes foreground pixel density in each cell. This captures the spatial distribution and clustering pattern of bacteria across the slide — P. aeruginosa tends to form denser local aggregations while E. coli distributes more uniformly.
4.4 Specialist PipelineStep Operation Output Dims 1. VGG16 extraction Forward pass through frozen VGG16 512 2. Hand-craft extraction HSV + Morph + LBP + GLCM + ChannelStats + Density + Hu + Curvature 171 3. Concatenation np.concatenate([vgg, rich]) 683 4. Standardization StandardScaler (zero mean, unit variance) 683 5. PCA Retain 95% variance 243 6. SVM prediction RBF-SVM, C=100, gamma=0.001, probability=True Binary (0=E.coli, 1=P.aeru) 7. Confidence gate Accept specialist if prob >= 0.90, else fallback to Stage 1 Final label
4.5 Confidence Threshold GateA confidence gate prevents the specialist from overriding the main SVM when it is uncertain. If the specialist's maximum class probability is below 0.90, the main SVM's prediction is used as the final answer. This is a practical engineering decision that prevents low-confidence specialist predictions from overriding a correct main SVM result, at the cost of occasionally retaining main SVM errors in the E. coli / P. aeruginosa pair.
Design Note: The 0.90 threshold was chosen based on observed confidence distributions. Future work should calibrate this threshold using a held-out validation set to maximize the F1 score of the gated system. ________________
5. Training Details5.1 Main Model TrainingComponent Configuration Training images ~5,000 (307 original × 18.7x augmentation) PCA components 94 (95% variance retained from 512-dim input) SVM kernel RBF Hyperparameter search GridSearchCV, 3-fold cross-validation Search space C [0.1, 1, 10, 100] Search space gamma ["scale", 0.1, 0.01, 0.001] Best params C=10, gamma=0.01 Scoring metric F1 (macro) Test accuracy 95.83%
5.2 Specialist Model TrainingComponent Configuration Training images 1,722 total (800 aug E.coli + 800 aug P.aeru + 122 original PNG) Feature vector 683-dim (512 VGG16 + 171 hand-crafted) PCA components 243 (95% variance retained from 683-dim input) SVM kernel RBF Hyperparameter search GridSearchCV, 3-fold cross-validation Search space C [1, 10, 100] Search space gamma ["scale", 0.01, 0.001] Best params C=100, gamma=0.001 Class weight Balanced Scoring metric F1 (binary) CV F1 0.9498 Test accuracy 95.65%
5.3 Domain Shift HandlingThe augmented training images were saved as JPEG files, while the original DIBaS images are PNG. JPEG compression introduces subtle color and texture artifacts that shift the feature distribution, causing the specialist (trained on augmented JPEGs) to misclassify original PNG images at inference. This was resolved by mixing all original PNG images into the specialist training set, forcing the model to learn features robust to both formats.________________
6. Evaluation Results6.1 Specialist Classifier PerformanceMetric E. coli P. aeruginosa Macro Avg Precision 0.9486 0.9647 0.9566 Recall 0.9651 0.9480 0.9565 F1-Score 0.9568 0.9563 0.9565 Support 172 173 345
Overall test accuracy: 95.65% on 345 held-out images. ROC-AUC: 0.9863, indicating strong probability calibration across the decision boundary.
6.2 Improvement Over v1Metric v1 Main Model v2 Specialist Improvement E. coli F1 ~0.00 0.9568 +0.9568 P. aeruginosa F1 ~0.00 0.9563 +0.9563 P. aeruginosa Recall ~0.00 0.9480 +0.9480 CV F1 N/A 0.9498 — ROC-AUC N/A 0.9863 —
6.3 Integration TestEnd-to-end testing of the full cascaded pipeline on original held-out images (not seen during training) produced the following results:
Test Correct / Total Notes E. coli (original PNG) 5 / 5 All routed to specialist, correctly classified P. aeruginosa (original PNG) 5 / 5 All routed to specialist, correctly classified Total 10 / 10 100% on held-out originals ________________
7. Technical StackComponent Library / Version Purpose Deep feature extractor TensorFlow / Keras + VGG16 ImageNet transfer learning Dimensionality reduction scikit-learn PCA Variance-preserving compression Main classifier scikit-learn SVC (RBF) 5-class prediction Specialist classifier scikit-learn SVC (RBF, probability=True) Binary E.coli / P.aeru LBP features scikit-image local_binary_pattern Texture micropatterns GLCM features scikit-image graycomatrix / graycoprops Spatial co-occurrence Color / morphology OpenCV (cv2) HSV histogram, contours, moments Statistical features scipy.stats.skew Channel skewness Image I/O Pillow (PIL) Image loading and resizing Deployment Streamlit Web interface at bacsense.streamlit.app
8. Saved ArtifactsAll model artifacts are saved to Google Drive and packaged into bacsense_v2_package.zip for local deployment.
File Size Description vgg16_feature_extractor.keras ~55 MB Frozen VGG16 feature extractor (no top layer) pca_model.pkl ~2 MB PCA model for main pipeline (512 → 94 dims) standard_scaler.pkl ~0.1 MB Scaler for main SVM input svm_classifier.pkl Variable Trained 5-class RBF-SVM class_names.pkl <1 KB Ordered list of 5 species names specialist_svm.pkl ~712 KB Binary specialist RBF-SVM (prob=True) specialist_scaler.pkl ~13 KB Scaler for 683-dim specialist input specialist_pca.pkl ~1 MB PCA for specialist (683 → 243 dims) specialist_metadata.json <1 KB Training config, metrics, timestamps inference.py ~15 KB Standalone BacSense class for deployment requirements.txt <1 KB Python dependency list example_usage.py ~3 KB Quickstart and Streamlit integration code ________________
9. Inference API9.1 InstallationInstall dependencies and point the BacSense class at the unpacked package directory:
Install: pip install tensorflow scikit-learn scikit-image opencv-python scipy Pillow
9.2 UsageMethod Signature Returns Constructor BacSense(model_dir, specialist_threshold=0.90) BacSense instance warmup() Pre-loads all models into memory None predict() predict(img_path, verbose=False) Result dict (see below) predict_batch() predict_batch(img_paths, verbose=False) List of result dicts
9.3 Result DictionaryKey Type Example Value prediction str Escherichia coli confidence float 0.9621 routed_to_specialist bool True specialist_accepted bool True main_prediction str Escherichia coli gram str Negative shape str Rod risk str High ________________
10. Limitations & Future Work10.1 Current Limitations* P. aeruginosa recall is 94.80% — approximately 5.2% of P. aeruginosa images are still misclassified.* The confidence threshold (0.90) was chosen empirically, not calibrated on a held-out validation set.* The dataset is small (307 original images across 5 classes). Models trained on small datasets may not generalize to different microscopes, staining protocols, or magnifications.* JPEG augmentation introduces domain shift relative to original PNG images; mitigated by mixing formats in training, but not fully eliminated.* Inference speed is slower than single-stage models due to sequential feature extraction for routed images.
10.2 Future Work* Collect 20-30 more original P. aeruginosa images to improve specialist recall beyond 0.95.* Add Gabor filter features (5 scales x 8 orientations = 40 dims) to further capture P. aeruginosa biofilm texture.* Calibrate confidence threshold using cross-validated F1 optimization on a dedicated validation set.* Extend specialist to handle all morphologically similar pairs, not just E. coli / P. aeruginosa.* Evaluate on images from a different microscopy system to assess generalization.* Replace binary specialist with a soft-label ensemble combining main SVM and specialist votes.________________
11. References
[1] Zielinski, B., Plichta, A., Misztal, K., Spurek, P., Brzychczy-Wloch, M., & Ochonska, D. (2017). Deep learning approach to bacterial colony classification. PLOS ONE, 12(9), e0184554.
[2] Rachmad, A., et al. (2020). Comparison of CNN-Based methods for tuberculosis bacteria classification using ResNet-101 and Support Vector Machine. Journal of Physics: Conference Series.
[3] Wahid, A., et al. CNN-based bacterial image classification using Inception-v3 with SVM, KNN, and Naive Bayes classifiers. Applied Sciences.
[4] Simonyan, K., & Zisserman, A. (2014). Very deep convolutional networks for large-scale image recognition. arXiv:1409.1556.
[5] Ojala, T., Pietikainen, M., & Maenpaa, T. (2002). Multiresolution gray-scale and rotation invariant texture classification with local binary patterns. IEEE TPAMI, 24(7), 971-987.
[6] Haralick, R. M., Shanmugam, K., & Dinstein, I. (1973). Textural features for image classification. IEEE Transactions on Systems, Man, and Cybernetics, 3(6), 610-621.Amity University Kolkata | Alapan SenPage123version https://git-lfs.github.com/spec/v1oid sha256:5acfb42b5a3aa9da5d6a4479ca3ef12d737a42923c4205fa51645dcfdb4bb635size 135123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# =============================================================================# BacSense v2 — Usage Examples# pip install -r requirements.txt# =============================================================================
from inference import BacSense
# ── Basic usage ───────────────────────────────────────────────────model = BacSense("bacsense_v2_package")model.warmup() # pre-load at startup (optional but recommended)
result = model.predict("image.png", verbose=True)print(result["prediction"]) # Escherichia coliprint(result["confidence"]) # 0.9621print(result["gram"]) # Negativeprint(result["shape"]) # Rodprint(result["risk"]) # High
# ── Batch prediction ──────────────────────────────────────────────results = model.predict_batch(["img1.png", "img2.png", "img3.png"])for r in results: print(r["prediction"], r["confidence"])
# ── Streamlit app ─────────────────────────────────────────────────# import streamlit as st# from inference import BacSense## @st.cache_resource# def load_model():# m = BacSense("bacsense_v2_package")# m.warmup()# return m## model = load_model()# st.title("BacSense v2 — Bacterial Classifier")# uploaded = st.file_uploader("Upload microscopy image", type=["png","jpg","jpeg"])# if uploaded:# with open("temp_input.png", "wb") as f:# f.write(uploaded.read())# result = model.predict("temp_input.png", verbose=True)# st.success(f"Prediction: {result['prediction']}")# st.metric("Confidence", f"{result['confidence']:.2%}")# col1, col2, col3 = st.columns(3)# col1.metric("Gram Stain", result["gram"])# col2.metric("Shape", result["shape"])# col3.metric("Risk Level", result["risk"])# if result["routed_to_specialist"]:# st.info("Specialist classifier was used for E.coli / P.aeruginosa disambiguation")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
# =============================================================================# BacSense v2 — Standalone Inference Module# =============================================================================# Usage:# from inference import BacSense# model = BacSense("path/to/bacsense_v2_package")# result = model.predict("image.png")# print(result["prediction"])# =============================================================================
import pickle, cv2, warningsimport numpy as npfrom pathlib import Pathfrom PIL import Image
warnings.filterwarnings("ignore")
def _lazy_imports(): from scipy.stats import skew from skimage.feature import local_binary_pattern, graycomatrix, graycoprops from tensorflow.keras.models import load_model return skew, local_binary_pattern, graycomatrix, graycoprops, load_model
class BacSense: """ BacSense v2 — Two-stage cascaded bacterial classifier.
Stage 1 : VGG16 + PCA(94) + RBF-SVM → 5-class prediction Stage 2 : VGG16 + 171-dim handcrafted features + PCA(243) + RBF-SVM (only for E. coli / P. aeruginosa confusion pair)
Feature vector (Stage 2): 683-dim VGG16(512) + HSV histogram(48) + Morphological(5) + LBP(59) + GLCM(24) + Channel stats(9) + Density grid(16) + Hu moments(7) + Curvature(3)
Performance: Overall accuracy : 95.65% E. coli F1 : 0.9568 P. aeruginosa F1 : 0.9563 ROC-AUC : 0.9863 """
SPECIES_INFO = { "Escherichia coli": {"gram": "Negative", "shape": "Rod", "risk": "High"}, "Pseudomonas aeruginosa": {"gram": "Negative", "shape": "Rod", "risk": "High"}, "Enterococcus faecalis": {"gram": "Positive", "shape": "Coccus", "risk": "Medium"}, "Clostridium perfringens": {"gram": "Positive", "shape": "Rod", "risk": "High"}, "Listeria monocytogenes": {"gram": "Positive", "shape": "Rod", "risk": "High"}, }
AMBIGUOUS = ["Escherichia coli", "Pseudomonas aeruginosa"]
def __init__(self, model_dir: str, specialist_threshold: float = 0.90): """ Args: model_dir : path to folder containing all model files specialist_threshold : min specialist confidence to accept (default 0.90) """ self.model_dir = Path(model_dir) self.threshold = specialist_threshold self._loaded = False
def _load(self): if self._loaded: return print("Loading BacSense v2 models...") skew, lbp_fn, graycomatrix, graycoprops, load_model = _lazy_imports() self._skew = skew self._lbp_fn = lbp_fn self._graycomatrix = graycomatrix self._graycoprops = graycoprops
d = self.model_dir self.feature_extractor = load_model(str(d / "vgg16_feature_extractor.keras")) with open(d / "pca_model.pkl", "rb") as f: self.pca = pickle.load(f) with open(d / "standard_scaler.pkl", "rb") as f: self.scaler = pickle.load(f) with open(d / "svm_classifier.pkl", "rb") as f: self.main_svm = pickle.load(f) with open(d / "class_names.pkl", "rb") as f: self.class_names = pickle.load(f) with open(d / "specialist_svm.pkl", "rb") as f: self.spec_svm = pickle.load(f) with open(d / "specialist_scaler.pkl", "rb") as f: self.spec_scaler = pickle.load(f) with open(d / "specialist_pca.pkl", "rb") as f: self.spec_pca = pickle.load(f) self._loaded = True print(" All models loaded ✅")
# ── Feature extractors ─────────────────────────────────────────
def _hsv_histogram(self, img_path, bins=(4, 4, 3)): img = cv2.imread(str(img_path)) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) hist = cv2.calcHist([hsv], [0,1,2], None, list(bins), [0,180,0,256,0,256]) return cv2.normalize(hist, hist).flatten() # 48
def _morphological(self, img_path): img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) blur = cv2.GaussianBlur(img, (5,5), 0) _,thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) contours,_ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: return np.zeros(5) c = max(contours, key=cv2.contourArea) area = cv2.contourArea(c) perim = cv2.arcLength(c, True) circ = 4*np.pi*area / (perim**2+1e-6) x,y,w,h = cv2.boundingRect(c) aspect = w / (h+1e-6) solidity = area / (cv2.contourArea(cv2.convexHull(c))+1e-6) return np.array([area, perim, circ, aspect, solidity]) # 5
def _lbp(self, img_path, P=8, R=1, n_bins=59): img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (128,128)) lbp = self._lbp_fn(img, P, R, method="uniform") hist,_ = np.histogram(lbp.ravel(), bins=n_bins, range=(0,n_bins)) hist = hist.astype(float); hist /= (hist.sum()+1e-6) return hist # 59
def _glcm(self, img_path): img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (128,128)) img = (img//4).astype(np.uint8) angles = [0, np.pi/4, np.pi/2, 3*np.pi/4] glcm = self._graycomatrix(img, distances=[1], angles=angles, levels=64, symmetric=True, normed=True) feats = [] for prop in ["contrast","dissimilarity","homogeneity", "energy","correlation","ASM"]: feats.extend(self._graycoprops(glcm, prop).flatten()) return np.array(feats) # 24
def _channel_stats(self, img_path): img = cv2.imread(str(img_path)) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype(float) feats = [] for ch in range(3): d = hsv[:,:,ch].ravel() feats.extend([d.mean(), d.std(), self._skew(d)]) return np.array(feats) # 9
def _density_grid(self, img_path, grid=4): img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (128,128)) _,thresh = cv2.threshold( cv2.GaussianBlur(img,(5,5),0), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) h,w = thresh.shape; gh,gw = h//grid, w//grid return np.array([ thresh[i*gh:(i+1)*gh, j*gw:(j+1)*gw].mean()/255.0 for i in range(grid) for j in range(grid) ]) # 16
def _hu_moments(self, img_path): img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (128,128)) _,thresh = cv2.threshold( cv2.GaussianBlur(img,(5,5),0), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) hu = cv2.HuMoments(cv2.moments(thresh)).flatten() return -np.sign(hu) * np.log10(np.abs(hu)+1e-10) # 7
def _curvature(self, img_path): img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) _,thresh = cv2.threshold( cv2.GaussianBlur(img,(5,5),0), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) contours,_ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) if not contours: return np.zeros(3) curvatures = [] for c in contours: if len(c) < 5: continue pts = c[:,0,:].astype(float) for i in range(1, len(pts)-1): v1 = pts[i]-pts[i-1]; v2 = pts[i+1]-pts[i] cross = abs(v1[0]*v2[1]-v1[1]*v2[0]) curvatures.append(cross/(np.linalg.norm(v1)*np.linalg.norm(v2)+1e-6)) if not curvatures: return np.zeros(3) curv = np.array(curvatures) return np.array([curv.mean(), curv.std(), curv.max()]) # 3
def _rich_features(self, img_path): return np.concatenate([ self._hsv_histogram(img_path), # 48 self._morphological(img_path), # 5 self._lbp(img_path), # 59 self._glcm(img_path), # 24 self._channel_stats(img_path), # 9 self._density_grid(img_path), # 16 self._hu_moments(img_path), # 7 self._curvature(img_path), # 3 ]) # 171 total
# ── Public API ─────────────────────────────────────────────────
def predict(self, img_path: str, verbose: bool = False) -> dict: """ Classify a bacterial microscopy image.
Returns dict: prediction : str species name confidence : float 0-1 routed_to_specialist : bool specialist_accepted : bool main_prediction : str gram : str Positive / Negative shape : str Rod / Coccus risk : str High / Medium / Low """ self._load() img_path = str(img_path)
# Stage 1 — Main SVM (5-class) img = Image.open(img_path).convert("RGB").resize((128,128), Image.LANCZOS) arr = np.expand_dims(np.array(img).astype("float32")/255.0, axis=0)
vgg = self.feature_extractor.predict(arr, verbose=0) scaled = self.scaler.transform(self.pca.transform(vgg)) main_pred = self.main_svm.predict(scaled)[0] main_class = self.class_names[main_pred] main_conf = float(np.max(self.main_svm.decision_function(scaled)[0]))
if verbose: print(f"Stage 1 — Main SVM: {main_class} (score: {main_conf:.4f})")
result = { "prediction": main_class, "confidence": main_conf, "routed_to_specialist": False, "specialist_accepted": False, "main_prediction": main_class, **self.SPECIES_INFO.get(main_class, {"gram":"Unknown","shape":"Unknown","risk":"Unknown"}) }
# Stage 2 — Specialist (ambiguous pair only) if main_class in self.AMBIGUOUS: if verbose: print("Routing to specialist...")
rich = self._rich_features(img_path).reshape(1,-1) combined = np.concatenate([vgg, rich], axis=1) pca_spec = self.spec_pca.transform(self.spec_scaler.transform(combined)) spec_pred = self.spec_svm.predict(pca_spec)[0] spec_proba = self.spec_svm.predict_proba(pca_spec)[0] spec_conf = spec_proba.max() spec_class = "Escherichia coli" if spec_pred == 0 else "Pseudomonas aeruginosa"
accepted = spec_conf >= self.threshold final = spec_class if accepted else main_class
if verbose: tag = "✅ accepted" if accepted else f"⚠️ below {self.threshold}, fallback to main" print(f"Stage 2 — Specialist: {spec_class} (conf: {spec_conf:.4f}) {tag}") print(f"Final: {final}")
result.update({ "prediction": final, "confidence": spec_conf, "routed_to_specialist": True, "specialist_accepted": accepted, **self.SPECIES_INFO.get(final, {"gram":"Unknown","shape":"Unknown","risk":"Unknown"}) })
return result
def predict_batch(self, img_paths: list, verbose: bool = False) -> list: """Classify a list of image paths. Returns list of result dicts.""" return [self.predict(p, verbose=verbose) for p in img_paths]
def warmup(self): """Pre-load all models into memory (call once at app startup).""" self._load() print("BacSense v2 ready ✅")123version https://git-lfs.github.com/spec/v1oid sha256:36d2993f7e2095ecfe3cf449a5213460c7c8ce780965434ee213d3be170c16e9size 1965171234567tensorflow>=2.12.0scikit-learn>=1.3.0scikit-image>=0.21.0opencv-python>=4.8.0numpy>=1.24.0Pillow>=9.5.0scipy>=1.11.01234567891011121314151617181920212223242526272829303132333435363738{ "timestamp": "2026-03-16 07:11:14", "architecture": "VGG16(512) + HSV(48) + Morph(5) + LBP(59) + GLCM(24) + ChannelStats(9) + DensityGrid(16) + HuMoments(7) + Curvature(3) \u2192 PCA(243) \u2192 SVM", "feature_dims": { "vgg16": 512, "hsv_histogram": 48, "morphological": 5, "lbp": 59, "glcm": 24, "channel_stats": 9, "density_grid": 16, "hu_moments": 7, "curvature": 3, "combined": 683, "after_pca": 243 }, "best_params": { "C": 100, "gamma": 0.001, "kernel": "rbf" }, "cv_f1": 0.9498, "test_accuracy": 0.9565, "ecoli_f1": 0.9568, "ecoli_recall": 0.9651, "pseudomonas_f1": 0.9563, "pseudomonas_recall": 0.948, "training_data": { "augmented_jpg": 1600, "original_png": 122, "total": 1722 }, "improvement_over_v1": { "accuracy": "0.9536 \u2192 0.9565", "pseudomonas_recall": "0.9306 \u2192 0.9480", "cv_f1": "0.9262 \u2192 0.9498" }}123version https://git-lfs.github.com/spec/v1oid sha256:271f198091fa0baeb308ab96be7daefba2622f82dbb76a9c72e0f0807955f93bsize 1339847123version https://git-lfs.github.com/spec/v1oid sha256:2e59b83d5e0fd6cf002571ee70e889741a7d94b0556a5a260aeacd795ab0ae44size 16855123version https://git-lfs.github.com/spec/v1oid sha256:8df00d049310dbdead39c7e6e6bf58779f0f14b5fe62627e908d15ab59ba0a57size 749525123version https://git-lfs.github.com/spec/v1oid sha256:c133477b15a420b3d00ed5c9ca41d72b3fe5212152227c82f0f43490823d3e0esize 2715123version https://git-lfs.github.com/spec/v1oid sha256:55296fc956943a2e5e041256a957cc782eea5f47f1a808dcde71f2076d2fda97size 2013194123version https://git-lfs.github.com/spec/v1oid sha256:48d0af85e0b48c38950b874e49ed61b46ce35085976c84fb8c595d30534bdefesize 5893310721 unmodified lines22232421 unmodified lines*.njsproj*.sln*.sw?21 unmodified lines2223242521 unmodified lines*.njsproj*.sln*.sw?.vercel
12npm installnpm run dev1234567891011126 unmodified lines1920212223242526import { Header } from "./components/Header"import { Hero } from "./components/Hero"import { Species } from "./components/Species"import { UploadZone } from "./components/UploadZone"import { Results } from "./components/Results"import { Footer } from "./components/Footer"import TargetCursor from "./components/TargetCursor"function App() {return (<><TargetCursor6 unmodified lines<main className="pt-32 pb-20"><Hero /><Species /><UploadZone /><Results /></main><Footer /></>123456789101112131415166 unmodified lines2324252627282930import { useState } from "react"import { Header } from "./components/Header"import { Hero } from "./components/Hero"import { Species } from "./components/Species"import { UploadZone } from "./components/UploadZone"import type { PredictionResult } from "./components/UploadZone"import { Results } from "./components/Results"import { Footer } from "./components/Footer"import TargetCursor from "./components/TargetCursor"function App() {const [results, setResults] = useState<PredictionResult[] | null>(null);return (<><TargetCursor6 unmodified lines<main className="pt-32 pb-20"><Hero /><Species /><UploadZone onResultsGenerated={setResults} />{results && results.length > 0 && <Results items={results} />}</main><Footer /></>
123410 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859export const Results = () => {return (<section className="max-w-7xl mx-auto px-6 mb-24"><h3 className="text-3xl font-display font-bold mb-8">Classification Results</h3>10 unmodified lines</tr></thead><tbody className="divide-y divide-slate-200 dark:divide-slate-800 text-slate-900 dark:text-slate-100"><tr className="hover:bg-primary/5 transition-colors"><td className="px-6 py-4 text-sm font-medium">sample_a102.png</td><td className="px-6 py-4 text-sm italic">E. coli</td><td className="px-6 py-4"><span className="bg-green-500/10 text-green-500 text-[11px] font-bold px-2 py-0.5 rounded">98.2%</span></td><td className="px-6 py-4 text-sm">Negative</td><td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400">Rod</td><td className="px-6 py-4"><span className="bg-red-500/10 text-red-500 text-[11px] font-bold px-2 py-0.5 rounded uppercase">High Risk</span></td></tr><tr className="hover:bg-primary/5 transition-colors"><td className="px-6 py-4 text-sm font-medium">sample_b405.png</td><td className="px-6 py-4 text-sm italic">S. aureus</td><td className="px-6 py-4"><span className="bg-green-500/10 text-green-500 text-[11px] font-bold px-2 py-0.5 rounded">96.7%</span></td><td className="px-6 py-4 text-sm">Positive</td><td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400">Cocci</td><td className="px-6 py-4"><span className="bg-orange-500/10 text-orange-500 text-[11px] font-bold px-2 py-0.5 rounded uppercase">Moderate</span></td></tr><tr className="hover:bg-primary/5 transition-colors"><td className="px-6 py-4 text-sm font-medium">sample_z901.png</td><td className="px-6 py-4 text-sm italic">B. cereus</td><td className="px-6 py-4"><span className="bg-yellow-500/10 text-yellow-500 text-[11px] font-bold px-2 py-0.5 rounded">84.1%</span></td><td className="px-6 py-4 text-sm">Positive</td><td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400">Spore-rod</td><td className="px-6 py-4"><span className="bg-blue-500/10 text-blue-500 text-[11px] font-bold px-2 py-0.5 rounded uppercase">Low Risk</span></td></tr></tbody></table></div></section>);};1234567891010 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354import type { PredictionResult } from "./UploadZone";interface ResultsProps {items: PredictionResult[];}export const Results = ({ items }: ResultsProps) => {return (<section className="max-w-7xl mx-auto px-6 mb-24"><h3 className="text-3xl font-display font-bold mb-8">Classification Results</h3>10 unmodified lines</tr></thead><tbody className="divide-y divide-slate-200 dark:divide-slate-800 text-slate-900 dark:text-slate-100">{items.map((item, index) => {if (!item.success) return null;const risk = item.details?.pathogenicity || 'Unknown';const confColor = (item.confidence || 0) >= 80 ? 'bg-green-500/10 text-green-500' : 'bg-yellow-500/10 text-yellow-500';let riskColor = 'bg-blue-500/10 text-blue-500'; // low/unknownif (risk.toLowerCase().includes('high')) riskColor = 'bg-red-500/10 text-red-500';else if (risk.toLowerCase().includes('moderate')) riskColor = 'bg-orange-500/10 text-orange-500';return (<tr key={index} className="hover:bg-primary/5 transition-colors"><td className="px-6 py-4 text-sm font-medium">{item.filename}</td><td className="px-6 py-4 text-sm italic">{item.prediction}</td><td className="px-6 py-4"><span className={`${confColor} text-[11px] font-bold px-2 py-0.5 rounded`}>{(item.confidence || 0).toFixed(1)}%</span></td><td className="px-6 py-4 text-sm">{item.details?.gram_stain}</td><td className="px-6 py-4 text-sm text-slate-500 dark:text-slate-400">{item.details?.shape}</td><td className="px-6 py-4"><span className={`${riskColor} text-[11px] font-bold px-2 py-0.5 rounded uppercase`}>{risk}</span></td></tr>);})}</tbody></table></div></section>);};
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950514 unmodified lines56575859606162636465666768697071727374757677787980811 unmodified line83848586878889909192939495969798991001011021 unmodified line1041051061071081091106 unmodified lines117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import { useState, useRef } from "react";interface PredictionResult {success: boolean;prediction: string;confidence: number;probabilities: { name: string; probability: number }[];details: {gram_stain: string;shape: string;pathogenicity: string;};}export const UploadZone = () => {const [file, setFile] = useState<File | null>(null);const [previewUrl, setPreviewUrl] = useState<string | null>(null);const [isUploading, setIsUploading] = useState(false);const [progress, setProgress] = useState(0);const [result, setResult] = useState<PredictionResult | null>(null);const [error, setError] = useState<string | null>(null);const fileInputRef = useRef<HTMLInputElement>(null);const handleFile = async (selectedFile: File) => {setFile(selectedFile);setPreviewUrl(URL.createObjectURL(selectedFile));setResult(null);setError(null);setIsUploading(true);setProgress(20);const formData = new FormData();formData.append("file", selectedFile);try {setProgress(60);const response = await fetch("http://localhost:5000/predict", {method: "POST",body: formData,});if (!response.ok) {throw new Error("Failed to analyze image");}setProgress(90);const data = await response.json();setResult(data);setProgress(100);} catch (err: any) {setError(err.message || "An error occurred");4 unmodified linesconst onFileDrop = (e: React.DragEvent<HTMLDivElement>) => {e.preventDefault();const droppedFile = e.dataTransfer.files[0];if (droppedFile) handleFile(droppedFile);};const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {const selectedFile = e.target.files?.[0];if (selectedFile) handleFile(selectedFile);};return (<section className="max-w-7xl mx-auto px-6 mb-24 relative z-10" id="upload"><div className={`grid ${result ? 'grid-cols-1 lg:grid-cols-2' : 'grid-cols-1 max-w-2xl mx-auto'} gap-12`}><div className="space-y-6"><h3 className="text-3xl font-display font-bold">Upload Zone</h3><divonDragOver={(e) => e.preventDefault()}onDrop={onFileDrop}onClick={() => fileInputRef.current?.click()}className="cursor-target border-2 border-dashed border-primary/30 rounded-3xl p-12 flex flex-col items-center justify-center text-center bg-background-light/50 dark:bg-background-dark/50 backdrop-blur-md hover:bg-primary/10 transition-colors group cursor-pointer"><inputtype="file"1 unmodified lineonChange={onFileChange}className="hidden"accept="image/*"/><div className="w-20 h-20 rounded-full bg-primary/20 flex items-center justify-center mb-6 group-hover:scale-110 transition-transform"><span className="material-symbols-outlined text-primary text-4xl">cloud_upload</span></div><h4 className="text-xl font-bold mb-2 text-slate-900 dark:text-white">Drag and drop images here</h4><p className="text-slate-500 dark:text-slate-400 mb-6">Supports JPG, PNG up to 20MB.</p><button className="cursor-target bg-primary text-white px-6 py-2 rounded-lg font-bold hover:scale-105 transition-transform">Browse Files</button></div>{/* Upload Progress */}{isUploading && (<div className="bg-slate-100 dark:bg-slate-800/80 p-6 rounded-2xl border border-slate-200 dark:border-slate-700 backdrop-blur-md"><div className="flex items-center justify-between mb-2"><span className="text-sm font-semibold text-slate-900 dark:text-slate-100">Processing {file?.name}</span><span className="text-sm font-bold text-primary">{progress}%</span></div><div className="w-full h-2 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">1 unmodified line</div><p className="text-xs text-slate-500 mt-3 flex items-center gap-1"><span className="material-symbols-outlined text-[14px] animate-spin">sync</span>Analyzing morphological features via VGG16 backbone...</p></div>)}6 unmodified lines)}</div>{result && (<div className="space-y-6"><h3 className="text-3xl font-display font-bold">Detailed Analysis</h3><div className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-md p-8 rounded-3xl border border-slate-200 dark:border-slate-700 shadow-xl"><div className="flex flex-col sm:flex-row gap-6 mb-8"><div className="w-32 h-32 rounded-2xl overflow-hidden border-2 border-primary/20 flex-shrink-0 bg-black">{previewUrl && <img className="w-full h-full object-cover" alt="Uploaded preview" src={previewUrl} />}</div><div className="flex-1"><div className="flex flex-wrap items-center justify-between gap-2 mb-2"><h4 className="text-2xl font-bold italic text-slate-900 dark:text-slate-100">{result.prediction}</h4><span className={`text-xs font-bold px-3 py-1 rounded-full whitespace-nowrap ${result.confidence > 80 ? 'bg-green-500/10 text-green-500' : 'bg-yellow-500/10 text-yellow-500'}`}>{result.confidence > 80 ? 'High Confidence' : 'Moderate'}</span></div><div className="flex items-center gap-4 mb-4"><div className="text-3xl font-display font-bold text-primary">{result.confidence.toFixed(1)}%</div></div><div className="grid grid-cols-2 gap-4"><div className="text-xs text-slate-900 dark:text-slate-100"><span className="text-slate-500">Morphology:</span> <span className="font-semibold">{result.details.shape}</span></div><div className="text-xs text-slate-900 dark:text-slate-100"><span className="text-slate-500">Stain:</span> <span className="font-semibold">{result.details.gram_stain}</span></div></div></div></div><div className="space-y-4"><h5 className="text-xs font-bold uppercase tracking-widest text-slate-500">Probability Distribution</h5><div className="space-y-3">{result.probabilities.slice(0, 3).map((prob, idx) => (<div key={prob.name}><div className="flex justify-between text-xs mb-1 text-slate-900 dark:text-slate-100"><span>{prob.name}</span><span className="font-bold">{prob.probability.toFixed(1)}%</span></div><div className="w-full h-1.5 bg-slate-100 dark:bg-slate-700 rounded-full"><div className={`h-full rounded-full ${idx === 0 ? 'bg-primary' : 'bg-slate-400'}`} style={{ width: `${prob.probability}%` }}></div></div></div>))}</div></div></div></div>)}</div></section>);};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687884 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201 unmodified line1221231241251261271281291301311321331341351361371381391401411421 unmodified line1441451461471481491506 unmodified lines157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300import { useState, useRef } from "react";export interface PredictionResult {filename?: string;success: boolean;error?: string;prediction?: string;confidence?: number;probabilities?: { name: string; probability: number }[];details?: {gram_stain: string;shape: string;pathogenicity: string;};previewUrl?: string;}const PRECAUTIONS: Record<string, string> = {"Escherichia coli": "Indicator of fecal contamination. \n\nPrecautions/Actions: Boil water immediately before consumption. Source trace to find sewage leaks. Do not use for washing open wounds.","Pseudomonas aeruginosa": "Opportunistic pathogen resistant to many sanitizers. \n\nPrecautions/Actions: Ensure water chlorination levels are adequate. Can cause severe infections in immunocompromised individuals. Avoid contact with eyes or ears.","Enterococcus faecalis": "Indicates prolonged fecal contamination. Very resilient. \n\nPrecautions/Actions: Shock chlorinate the water system. Discontinue use for drinking until negative tests are returned.","Clostridium perfringens": "Spore-forming bacteria, highly resistant to standard disinfection. \n\nPrecautions/Actions: Indicates remote or past fecal contamination. UV filtration or extreme heat treatment may be required.","Listeria monocytogenes": "Dangerous to pregnant women and immunocompromised individuals. \n\nPrecautions/Actions: Do not use water for food preparation or drinking. Pasteurization/boiling is required."};interface UploadZoneProps {onResultsGenerated?: (results: PredictionResult[] | null) => void;}export const UploadZone = ({ onResultsGenerated }: UploadZoneProps) => {const [files, setFiles] = useState<File[]>([]);const [isUploading, setIsUploading] = useState(false);const [progress, setProgress] = useState(0);const [localResults, setLocalResults] = useState<PredictionResult[] | null>(null);const [selectedResult, setSelectedResult] = useState<PredictionResult | null>(null);const [error, setError] = useState<string | null>(null);const fileInputRef = useRef<HTMLInputElement>(null);const handleFiles = async (selectedFiles: FileList | File[]) => {const fileArray = Array.from(selectedFiles);if (fileArray.length === 0) return;setFiles(fileArray);// Generate preview URLsconst previewUrls = fileArray.map(f => URL.createObjectURL(f));setLocalResults(null);if (onResultsGenerated) onResultsGenerated(null);setSelectedResult(null);setError(null);setIsUploading(true);setProgress(20);const formData = new FormData();fileArray.forEach(f => {formData.append("files", f);});try {setProgress(60);const response = await fetch("http://localhost:5000/predict_batch", {method: "POST",body: formData,});if (!response.ok) {throw new Error("Failed to analyze images");}setProgress(90);const data = await response.json();// Attach preview URLs to results for displayif (data.results && Array.isArray(data.results)) {const resultsWithPreviews = data.results.map((r: any) => {const matchIndex = fileArray.findIndex(f => f.name === r.filename);return {...r,previewUrl: matchIndex >= 0 ? previewUrls[matchIndex] : null};});setLocalResults(resultsWithPreviews);if (onResultsGenerated) onResultsGenerated(resultsWithPreviews);}setProgress(100);} catch (err: any) {setError(err.message || "An error occurred");4 unmodified linesconst onFileDrop = (e: React.DragEvent<HTMLDivElement>) => {e.preventDefault();if (e.dataTransfer.files.length > 0) {handleFiles(e.dataTransfer.files);}};const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {if (e.target.files && e.target.files.length > 0) {handleFiles(e.target.files);}};return (<section className="max-w-7xl mx-auto px-6 mb-24 relative z-10" id="upload"><div className={`grid ${localResults ? 'grid-cols-1 lg:grid-cols-3' : 'grid-cols-1 max-w-2xl mx-auto'} gap-8`}><div className="space-y-6 lg:col-span-1"><h3 className="text-3xl font-display font-bold">Upload Zone</h3><divonDragOver={(e) => e.preventDefault()}onDrop={onFileDrop}onClick={() => fileInputRef.current?.click()}className="cursor-target border-2 border-dashed border-primary/30 rounded-3xl p-12 flex flex-col items-center justify-center text-center bg-background-light/50 dark:bg-background-dark/50 backdrop-blur-md hover:bg-primary/10 transition-colors group cursor-pointer h-64"><inputtype="file"1 unmodified lineonChange={onFileChange}className="hidden"accept="image/*"multiple/><div className="w-16 h-16 rounded-full bg-primary/20 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform"><span className="material-symbols-outlined text-primary text-3xl">cloud_upload</span></div><h4 className="text-lg font-bold mb-2 text-slate-900 dark:text-white">Drag & drop images</h4><p className="text-sm text-slate-500 dark:text-slate-400 mb-4">Supports JPG, PNG up to 20MB.</p><button className="cursor-target bg-primary text-white px-5 py-2 rounded-lg font-bold hover:scale-105 transition-transform text-sm">Browse</button></div>{/* Upload Progress */}{isUploading && (<div className="bg-slate-100 dark:bg-slate-800/80 p-6 rounded-2xl border border-slate-200 dark:border-slate-700 backdrop-blur-md"><div className="flex items-center justify-between mb-2"><span className="text-sm font-semibold text-slate-900 dark:text-slate-100">Processing {files.length} images</span><span className="text-sm font-bold text-primary">{progress}%</span></div><div className="w-full h-2 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">1 unmodified line</div><p className="text-xs text-slate-500 mt-3 flex items-center gap-1"><span className="material-symbols-outlined text-[14px] animate-spin">sync</span>Analyzing morphological features...</p></div>)}6 unmodified lines)}</div>{localResults && (<div className="space-y-6 lg:col-span-2"><div className="flex items-center justify-between"><h3 className="text-3xl font-display font-bold">Analysis Results</h3><span className="bg-primary/10 text-primary px-3 py-1 rounded-full text-sm font-bold">{localResults.length} processed</span></div><div className="grid grid-cols-1 md:grid-cols-2 gap-6">{localResults.map((res, index) => (<divkey={index}onClick={() => res.success && setSelectedResult(res)}className={`bg-white/80 dark:bg-slate-800/80 backdrop-blur-md p-6 rounded-3xl border border-slate-200 dark:border-slate-700 shadow-xl flex flex-col ${res.success ? 'cursor-pointer hover:scale-[1.02] hover:border-primary/50 transition-all' : ''}`}title={res.success ? "Click for detailed summary" : ""}><div className="flex gap-4 mb-4"><div className="w-24 h-24 rounded-2xl overflow-hidden border border-primary/20 flex-shrink-0 bg-black">{res.previewUrl ? (<img className="w-full h-full object-cover" alt={`Upload ${index}`} src={res.previewUrl} />) : (<div className="w-full h-full flex items-center justify-center bg-slate-800"><span className="material-symbols-outlined text-slate-500">image</span></div>)}</div><div className="flex-1 min-w-0"><p className="text-xs text-slate-500 dark:text-slate-400 truncate mb-1" title={res.filename}>{res.filename}</p>{res.success && res.prediction ? (<><h4 className="text-lg font-bold italic text-slate-900 dark:text-slate-100 leading-tight mb-2 truncate" title={res.prediction}>{res.prediction}</h4><div className={`inline-flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-full whitespace-nowrap ${(res.confidence || 0) > 80 ? 'bg-green-500/10 text-green-500' : 'bg-yellow-500/10 text-yellow-500'}`}><span className="material-symbols-outlined text-[14px]">{(res.confidence || 0) > 80 ? 'verified' : 'warning'}</span>{(res.confidence || 0).toFixed(1)}% Conf</div></>) : (<div className="text-red-500 text-sm font-bold flex items-center gap-1"><span className="material-symbols-outlined text-sm">error</span> Failed</div>)}</div></div>{res.success && res.details && (<div className="flex-1 flex flex-col justify-end"><div className="grid grid-cols-2 gap-2 p-3 bg-slate-50 dark:bg-slate-900/50 rounded-xl"><div className="text-xs text-slate-900 dark:text-slate-100"><span className="text-slate-500 block mb-0.5 mt-0">Morphology</span><span className="font-semibold">{res.details.shape}</span></div><div className="text-xs text-slate-900 dark:text-slate-100"><span className="text-slate-500 block mb-0.5 mt-0">Stain</span><span className="font-semibold">{res.details.gram_stain}</span></div></div></div>)}</div>))}</div></div>)}</div>{/* Modal Dialog Box */}{selectedResult && (<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm" onClick={() => setSelectedResult(null)}><divclassName="bg-white dark:bg-slate-900 rounded-3xl max-w-2xl w-full max-h-[90vh] overflow-y-auto shadow-2xl border border-slate-200 dark:border-slate-700"onClick={e => e.stopPropagation()}><div className="p-6 md:p-8 flex flex-col gap-6"><div className="flex items-start justify-between"><h3 className="text-2xl font-bold font-display text-slate-900 dark:text-white">Detailed Classification Summary</h3><button onClick={() => setSelectedResult(null)} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 transition-colors"><span className="material-symbols-outlined">close</span></button></div><div className="flex flex-col md:flex-row gap-6"><div className="w-full md:w-48 h-48 rounded-2xl overflow-hidden bg-black flex-shrink-0 border-4 border-slate-100 dark:border-slate-800">{selectedResult.previewUrl ? (<img src={selectedResult.previewUrl} alt="Analyzed bacteria" className="w-full h-full object-cover" />) : (<div className="w-full h-full flex items-center justify-center text-slate-500"><span className="material-symbols-outlined text-4xl">image</span></div>)}</div><div className="flex-1 space-y-4"><div><span className="text-sm font-bold text-slate-500 uppercase tracking-wider">Predicted Species</span><h4 className="text-3xl font-bold italic text-primary mt-1">{selectedResult.prediction}</h4></div><div className="grid grid-cols-2 gap-4"><div className="bg-slate-50 dark:bg-slate-800/50 p-3 rounded-xl"><span className="text-xs text-slate-500 block mb-1">Confidence</span><span className="text-lg font-bold text-slate-900 dark:text-white">{(selectedResult.confidence || 0).toFixed(1)}%</span></div><div className="bg-slate-50 dark:bg-slate-800/50 p-3 rounded-xl"><span className="text-xs text-slate-500 block mb-1">Risk Level</span><span className="text-lg font-bold text-slate-900 dark:text-white">{selectedResult.details?.pathogenicity || 'Unknown'}</span></div></div></div></div><div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-2"><div className="space-y-3"><h5 className="font-bold text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-700 pb-2">Microbiology Specifics</h5><ul className="space-y-2 text-sm text-slate-600 dark:text-slate-300"><li className="flex justify-between"><span>Gram Stain:</span> <strong className="text-slate-900 dark:text-white">{selectedResult.details?.gram_stain}</strong></li><li className="flex justify-between"><span>Morphology:</span> <strong className="text-slate-900 dark:text-white">{selectedResult.details?.shape}</strong></li><li className="flex justify-between"><span>Pathogenicity:</span> <strong className="text-slate-900 dark:text-white">{selectedResult.details?.pathogenicity}</strong></li></ul></div><div className="space-y-3"><h5 className="font-bold text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-700 pb-2">Precautions & Actions</h5><div className="bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-200 dark:border-yellow-500/20 rounded-xl p-4 text-sm text-yellow-800 dark:text-yellow-200 shadow-inner"><div className="flex gap-2 items-start whitespace-pre-line"><span className="material-symbols-outlined text-[18px] mt-0.5">warning</span><p className="leading-relaxed m-0">{selectedResult.prediction ? (PRECAUTIONS[selectedResult.prediction] || "Standard water safety protocols apply. Heat above 70°C before any consumption.") : "Unknown"}</p></div></div></div></div><div className="mt-4 flex justify-end"><button className="px-6 py-2 bg-slate-900 dark:bg-white text-white dark:text-slate-900 font-bold rounded-xl hover:scale-105 transition-transform" onClick={() => setSelectedResult(null)}>Close Details</button></div></div></div></div>)}</section>);};
12345678{ "rewrites": [ { "source": "/(.*)", "destination": "/index.html" } ]}BacSense_v2_Technical_Documentation.docx.txtAdded+628
bacsense_v2_package/class_names.pklAdded+3
bacsense_v2_package/example_usage.pyAdded+48
bacsense_v2_package/inference.pyAdded+268
bacsense_v2_package/pca_model.pklAdded+3
bacsense_v2_package/requirements.txtAdded+7
bacsense_v2_package/specialist_metadata.jsonAdded+38
bacsense_v2_package/specialist_pca.pklAdded+3
bacsense_v2_package/specialist_scaler.pklAdded+3
bacsense_v2_package/specialist_svm.pklAdded+3
bacsense_v2_package/standard_scaler.pklAdded+3
bacsense_v2_package/svm_classifier.pklAdded+3
bacsense_v2_package/vgg16_feature_extractor.kerasAdded+3
frontend/.gitignore+1
frontend/run_frontend.ps1Added+2
frontend/src/App.tsx+6-2
frontend/src/components/Results.tsx+32-37
frontend/src/components/UploadZone.tsx+196-63
frontend/vercel.jsonAdded+8