๐ฌ MicroID System
APIยฎ-style Bacterial Identification using Biochemical Profiles
Based on APIยฎ 20E strip methodology
import streamlit as st import sqlite3 import pandas as pd from datetime import datetime import os # Page configuration st.set_page_config( page_title="MicroID - Bacterial Identification System", page_icon="๐ฌ", layout="wide" ) # Initialize database @st.cache_resource def init_db(): """Initialize SQLite database with species and biochemical profiles""" conn = sqlite3.connect('microid.db', check_same_thread=False) cursor = conn.cursor() # Create tables cursor.execute(''' CREATE TABLE IF NOT EXISTS species ( id INTEGER PRIMARY KEY AUTOINCREMENT, genus TEXT NOT NULL, species TEXT NOT NULL, full_name TEXT UNIQUE NOT NULL, gram_stain TEXT, morphology TEXT, notes TEXT ) ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS biochemical_tests ( id INTEGER PRIMARY KEY AUTOINCREMENT, test_code TEXT UNIQUE NOT NULL, test_name TEXT NOT NULL, description TEXT, position INTEGER ) ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS species_profiles ( id INTEGER PRIMARY KEY AUTOINCREMENT, species_id INTEGER, test_id INTEGER, reaction TEXT NOT NULL, probability REAL DEFAULT 0.95, FOREIGN KEY (species_id) REFERENCES species(id), FOREIGN KEY (test_id) REFERENCES biochemical_tests(id) ) ''') # Check if tests already exist cursor.execute("SELECT COUNT(*) FROM biochemical_tests") if cursor.fetchone()[0] == 0: # Insert biochemical tests tests = [ (1, 'ONPG', 'Beta-galactosidase', 1), (2, 'ADH', 'Arginine dihydrolase', 2), (3, 'LDC', 'Lysine decarboxylase', 3), (4, 'ODC', 'Ornithine decarboxylase', 4), (5, 'CIT', 'Citrate utilization', 5), (6, 'H2S', 'Hydrogen sulfide', 6), (7, 'URE', 'Urease', 7), (8, 'TDA', 'Tryptophan deaminase', 8), (9, 'IND', 'Indole production', 9), (10, 'VP', 'Voges-Proskauer', 10), (11, 'GEL', 'Gelatinase', 11), (12, 'GLU', 'Glucose fermentation', 12), (13, 'MAN', 'Mannitol', 13), (14, 'INO', 'Inositol', 14), (15, 'SOR', 'Sorbitol', 15), (16, 'RHA', 'Rhamnose', 16), (17, 'SAC', 'Sucrose', 17), (18, 'MEL', 'Melibiose', 18), (19, 'AMY', 'Amygdalin', 19), (20, 'ARA', 'Arabinose', 20) ] for test in tests: cursor.execute(''' INSERT INTO biochemical_tests (id, test_code, test_name, position) VALUES (?, ?, ?, ?) ''', test) # Check if species already exist cursor.execute("SELECT COUNT(*) FROM species") if cursor.fetchone()[0] == 0: # Insert species species_list = [ ('Escherichia', 'coli', 'Escherichia coli', 'negative', 'rod'), ('Pseudomonas', 'aeruginosa', 'Pseudomonas aeruginosa', 'negative', 'rod'), ('Staphylococcus', 'aureus', 'Staphylococcus aureus', 'positive', 'coccus'), ('Streptococcus', 'pneumoniae', 'Streptococcus pneumoniae', 'positive', 'coccus'), ('Klebsiella', 'pneumoniae', 'Klebsiella pneumoniae', 'negative', 'rod'), ('Proteus', 'mirabilis', 'Proteus mirabilis', 'negative', 'rod'), ('Enterococcus', 'faecalis', 'Enterococcus faecalis', 'positive', 'coccus'), ('Neisseria', 'gonorrhoeae', 'Neisseria gonorrhoeae', 'negative', 'coccus'), ('Haemophilus', 'influenzae', 'Haemophilus influenzae', 'negative', 'rod'), ('Candida', 'albicans', 'Candida albicans', 'yeast', 'yeast'), ('Salmonella', 'typhimurium', 'Salmonella typhimurium', 'negative', 'rod'), ('Shigella', 'flexneri', 'Shigella flexneri', 'negative', 'rod'), ('Bacillus', 'subtilis', 'Bacillus subtilis', 'positive', 'rod'), ('Clostridium', 'perfringens', 'Clostridium perfringens', 'positive', 'rod'), ('Listeria', 'monocytogenes', 'Listeria monocytogenes', 'positive', 'rod'), ('Acinetobacter', 'baumannii', 'Acinetobacter baumannii', 'negative', 'coccus'), ('Enterobacter', 'cloacae', 'Enterobacter cloacae', 'negative', 'rod'), ('Serratia', 'marcescens', 'Serratia marcescens', 'negative', 'rod'), ('Citrobacter', 'freundii', 'Citrobacter freundii', 'negative', 'rod'), ('Morganella', 'morganii', 'Morganella morganii', 'negative', 'rod'), ('Yersinia', 'enterocolitica', 'Yersinia enterocolitica', 'negative', 'rod'), ('Vibrio', 'cholerae', 'Vibrio cholerae', 'negative', 'rod'), ('Campylobacter', 'jejuni', 'Campylobacter jejuni', 'negative', 'curved rod'), ('Bacteroides', 'fragilis', 'Bacteroides fragilis', 'negative', 'rod'), ('Lactobacillus', 'acidophilus', 'Lactobacillus acidophilus', 'positive', 'rod'), ('Streptococcus', 'pyogenes', 'Streptococcus pyogenes', 'positive', 'coccus'), ('Staphylococcus', 'epidermidis', 'Staphylococcus epidermidis', 'positive', 'coccus'), ('Candida', 'glabrata', 'Candida glabrata', 'yeast', 'yeast'), ('Candida', 'parapsilosis', 'Candida parapsilosis', 'yeast', 'yeast'), ('Candida', 'tropicalis', 'Candida tropicalis', 'yeast', 'yeast'), ('Cryptococcus', 'neoformans', 'Cryptococcus neoformans', 'yeast', 'yeast') ] for species in species_list: cursor.execute(''' INSERT INTO species (genus, species, full_name, gram_stain, morphology) VALUES (?, ?, ?, ?, ?) ''', species) # Get species and test IDs cursor.execute('SELECT id, full_name FROM species') species_map = {row[1]: row[0] for row in cursor.fetchall()} cursor.execute('SELECT id, test_code FROM biochemical_tests') test_map = {row[1]: row[0] for row in cursor.fetchall()} # Check if profiles exist cursor.execute("SELECT COUNT(*) FROM species_profiles") if cursor.fetchone()[0] == 0: # Insert profiles for key species profiles = { 'Escherichia coli': { 'ONPG':'+', 'ADH':'-', 'LDC':'+', 'ODC':'+', 'CIT':'-', 'H2S':'-', 'URE':'-', 'TDA':'-', 'IND':'+', 'VP':'-', 'GEL':'-', 'GLU':'+', 'MAN':'+', 'INO':'-', 'SOR':'+', 'RHA':'+', 'SAC':'+', 'MEL':'+', 'AMY':'-', 'ARA':'+' }, 'Pseudomonas aeruginosa': { 'ONPG':'-', 'ADH':'+', 'LDC':'-', 'ODC':'-', 'CIT':'+', 'H2S':'-', 'URE':'-', 'TDA':'-', 'IND':'-', 'VP':'-', 'GEL':'+', 'GLU':'+', 'MAN':'-', 'INO':'-', 'SOR':'-', 'RHA':'-', 'SAC':'-', 'MEL':'-', 'AMY':'-', 'ARA':'-' }, 'Staphylococcus aureus': { 'ONPG':'+', 'ADH':'-', 'LDC':'-', 'ODC':'-', 'CIT':'V', 'H2S':'-', 'URE':'+', 'TDA':'-', 'IND':'-', 'VP':'+', 'GEL':'V', 'GLU':'+', 'MAN':'+', 'INO':'-', 'SOR':'+', 'RHA':'V', 'SAC':'+', 'MEL':'-', 'AMY':'V', 'ARA':'-' }, 'Klebsiella pneumoniae': { 'ONPG':'+', 'ADH':'-', 'LDC':'+', 'ODC':'-', 'CIT':'+', 'H2S':'-', 'URE':'+', 'TDA':'-', 'IND':'-', 'VP':'+', 'GEL':'-', 'GLU':'+', 'MAN':'+', 'INO':'+', 'SOR':'+', 'RHA':'+', 'SAC':'+', 'MEL':'+', 'AMY':'+', 'ARA':'+' }, 'Proteus mirabilis': { 'ONPG':'-', 'ADH':'-', 'LDC':'-', 'ODC':'-', 'CIT':'V', 'H2S':'+', 'URE':'+', 'TDA':'+', 'IND':'-', 'VP':'-', 'GEL':'-', 'GLU':'+', 'MAN':'-', 'INO':'-', 'SOR':'-', 'RHA':'-', 'SAC':'-', 'MEL':'-', 'AMY':'-', 'ARA':'-' }, 'Enterococcus faecalis': { 'ONPG':'+', 'ADH':'+', 'LDC':'-', 'ODC':'-', 'CIT':'-', 'H2S':'-', 'URE':'-', 'TDA':'-', 'IND':'-', 'VP':'-', 'GEL':'V', 'GLU':'+', 'MAN':'+', 'INO':'-', 'SOR':'-', 'RHA':'-', 'SAC':'+', 'MEL':'-', 'AMY':'-', 'ARA':'-' } } for species_name, reactions in profiles.items(): if species_name in species_map: species_id = species_map[species_name] for test_code, reaction in reactions.items(): if test_code in test_map: test_id = test_map[test_code] cursor.execute(''' INSERT INTO species_profiles (species_id, test_id, reaction) VALUES (?, ?, ?) ''', (species_id, test_id, reaction)) conn.commit() return conn def load_tests(): conn = init_db() df = pd.read_sql_query("SELECT id, test_code, test_name, position FROM biochemical_tests ORDER BY position", conn) return df def identify_organism(reactions): conn = init_db() # Get all species profiles query = """ SELECT s.id, s.full_name, s.gram_stain, s.morphology, bt.position, bt.test_code, sp.reaction as expected_reaction FROM species s JOIN species_profiles sp ON s.id = sp.species_id JOIN biochemical_tests bt ON sp.test_id = bt.id ORDER BY s.id, bt.position """ df = pd.read_sql_query(query, conn) # Calculate matches for each species results = [] for species_id in df['id'].unique(): species_data = df[df['id'] == species_id] species_name = species_data['full_name'].iloc[0] gram_stain = species_data['gram_stain'].iloc[0] morphology = species_data['morphology'].iloc[0] matches = 0 total = 0 variable_count = 0 for idx, row in species_data.iterrows(): pos = row['position'] - 1 if pos < len(reactions): expected = row['expected_reaction'] actual = reactions[pos] if expected != 'V': total += 1 if expected == actual: matches += 1 else: total += 1 matches += 1 variable_count += 1 match_percent = (matches / total * 100) if total > 0 else 0 results.append({ 'species': species_name, 'gram_stain': gram_stain, 'morphology': morphology, 'match_score': match_percent, 'matches': matches, 'total_tests': total, 'variable_tests': variable_count }) # Sort by match score results.sort(key=lambda x: x['match_score'], reverse=True) # Calculate confidence (normalized) top_matches = results[:5] total_score = sum(m['match_score'] for m in top_matches) for m in top_matches: m['confidence'] = (m['match_score'] / total_score * 100) if total_score > 0 else 0 return top_matches # Custom CSS st.markdown(""" """, unsafe_allow_html=True) # Header st.markdown("""
APIยฎ-style Bacterial Identification using Biochemical Profiles
Based on APIยฎ 20E strip methodology
Gram Stain: {top_result['gram_stain'] or 'N/A'}
Morphology: {top_result['morphology'] or 'N/A'}
Match Score: {top_result['match_score']:.1f}%
Confidence: {top_result['confidence']:.1f}% ({confidence_text})
Tests Matched: {top_result['matches']}/{top_result['total_tests']}
{f'โ ๏ธ Variable reactions: {top_result["variable_tests"]}
' if top_result['variable_tests'] > 0 else ''}