Spaces:
Runtime error
Runtime error
File size: 19,688 Bytes
f42f43e b541e92 f42f43e b541e92 f42f43e b541e92 f42f43e b541e92 f42f43e b541e92 0ecf6ae f42f43e b541e92 f42f43e 0ecf6ae f42f43e b541e92 f42f43e b541e92 f42f43e 0ecf6ae f42f43e 0ecf6ae f42f43e 0ecf6ae f42f43e 0ecf6ae f42f43e 0ecf6ae f42f43e b541e92 f42f43e b541e92 f42f43e | 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 | 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("""
<style>
.main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 10px;
margin-bottom: 2rem;
color: white;
text-align: center;
}
.test-card {
background: #f8f9fa;
padding: 10px;
border-radius: 8px;
text-align: center;
margin: 5px;
border: 1px solid #e0e0e0;
}
.result-card {
background: white;
padding: 1rem;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-bottom: 1rem;
border-left: 4px solid #667eea;
}
.confidence-high {
color: #28a745;
font-weight: bold;
}
.confidence-medium {
color: #ffc107;
font-weight: bold;
}
.confidence-low {
color: #dc3545;
font-weight: bold;
}
.stButton > button {
width: 100%;
}
div[data-testid="column"] {
padding: 0 5px;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown("""
<div class="main-header">
<h1>๐ฌ MicroID System</h1>
<p>APIยฎ-style Bacterial Identification using Biochemical Profiles</p>
<p style="font-size: 0.9rem; opacity: 0.9;">Based on APIยฎ 20E strip methodology</p>
</div>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.markdown("## ๐ About")
st.info("""
**MicroID** simulates the identification process used in clinical microbiology labs.
- Enter 20 biochemical reactions
- System matches against database
- Returns top species matches with confidence scores
*Educational purpose - Not for clinical use*
""")
st.markdown("## ๐งช Quick Examples")
col1, col2 = st.columns(2)
with col1:
if st.button("๐ฆ E. coli", use_container_width=True):
st.session_state['example'] = 'E. coli'
if st.button("๐ก S. aureus", use_container_width=True):
st.session_state['example'] = 'S. aureus'
with col2:
if st.button("๐งซ P. aeruginosa", use_container_width=True):
st.session_state['example'] = 'P. aeruginosa'
if st.button("๐ Reset All", use_container_width=True):
st.session_state['example'] = 'reset'
st.markdown("---")
st.markdown("### ๐ Database Stats")
conn = init_db()
species_count = pd.read_sql_query("SELECT COUNT(*) as count FROM species", conn)['count'][0]
test_count = pd.read_sql_query("SELECT COUNT(*) as count FROM biochemical_tests", conn)['count'][0]
profile_count = pd.read_sql_query("SELECT COUNT(*) as count FROM species_profiles", conn)['count'][0]
st.metric("Species in Database", species_count)
st.metric("Biochemical Tests", test_count)
st.metric("Profile Entries", profile_count)
# Main content - Two columns for layout
left_col, right_col = st.columns([2, 1])
with left_col:
st.markdown("## ๐งฌ Biochemical Test Reactions")
st.markdown("Select the reaction results for each test (20 positions)")
tests_df = load_tests()
# Initialize session state for reactions
if 'reactions' not in st.session_state:
st.session_state.reactions = ['-'] * 20
# Handle example loading
examples = {
'E. coli': ['+','-','+','+','-','-','-','-','+','-','-','+','+','-','+','+','+','+','-','+'],
'P. aeruginosa': ['-','+','-','-','+','-','-','-','-','-','+','+','-','-','-','-','-','-','-','-'],
'S. aureus': ['+','-','-','-','V','-','+','-','-','+','V','+','+','-','+','V','+','-','V','-']
}
if 'example' in st.session_state:
if st.session_state.example == 'reset':
st.session_state.reactions = ['-'] * 20
elif st.session_state.example in examples:
st.session_state.reactions = examples[st.session_state.example]
del st.session_state.example
st.rerun()
# Create grid of test buttons - 4 columns
for i in range(0, 20, 4):
cols = st.columns(4)
for j in range(4):
idx = i + j
if idx < 20:
test = tests_df.iloc[idx]
with cols[j]:
st.markdown(f"**{test['test_code']}**")
st.caption(test['test_name'])
# Use radio buttons instead of nested columns to avoid nesting issues
reaction = st.radio(
"Reaction",
options=['-', '+'],
index=0 if st.session_state.reactions[idx] == '-' else 1,
key=f"test_{idx}",
label_visibility="collapsed",
horizontal=True
)
if reaction != st.session_state.reactions[idx]:
st.session_state.reactions[idx] = reaction
st.rerun()
# Current profile display
st.markdown("---")
current_profile = ''.join(st.session_state.reactions)
st.markdown(f"**Current Profile Code:** `{current_profile}`")
# Identify button
if st.button("๐ IDENTIFY ORGANISM", type="primary", use_container_width=True):
with st.spinner("Analyzing biochemical profile..."):
results = identify_organism(st.session_state.reactions)
st.session_state.results = results
with right_col:
st.markdown("## ๐ฏ Identification Results")
if 'results' in st.session_state and st.session_state.results:
results = st.session_state.results
# Main identification
top_result = results[0]
if top_result['confidence'] > 70:
confidence_class = "confidence-high"
confidence_text = "High Confidence"
elif top_result['confidence'] > 40:
confidence_class = "confidence-medium"
confidence_text = "Medium Confidence"
else:
confidence_class = "confidence-low"
confidence_text = "Low Confidence"
st.markdown(f"""
<div class="result-card">
<h3>๐ Top Match</h3>
<h2>{top_result['species']}</h2>
<p><strong>Gram Stain:</strong> {top_result['gram_stain'] or 'N/A'}</p>
<p><strong>Morphology:</strong> {top_result['morphology'] or 'N/A'}</p>
<p><strong>Match Score:</strong> {top_result['match_score']:.1f}%</p>
<p><strong>Confidence:</strong> <span class="{confidence_class}">{top_result['confidence']:.1f}% ({confidence_text})</span></p>
<p><strong>Tests Matched:</strong> {top_result['matches']}/{top_result['total_tests']}</p>
{f'<p>โ ๏ธ Variable reactions: {top_result["variable_tests"]}</p>' if top_result['variable_tests'] > 0 else ''}
</div>
""", unsafe_allow_html=True)
# Other matches
st.markdown("### ๐ Other Possible Matches")
for result in results[1:4]:
st.markdown(f"""
<div class="result-card">
<strong>{result['species']}</strong><br>
Match: {result['match_score']:.1f}% | Confidence: {result['confidence']:.1f}%
</div>
""", unsafe_allow_html=True)
# Create simple bar chart using Streamlit
st.markdown("### ๐ Match Scores")
match_data = pd.DataFrame(results[:5])
st.bar_chart(match_data.set_index('species')['match_score'])
else:
st.info("๐ Enter biochemical reactions and click 'IDENTIFY ORGANISM' to see results")
# Show example of what results look like
st.markdown("""
### ๐ How it works:
1. Select + or - for each of the 20 tests
2. Click "IDENTIFY ORGANISM"
3. System compares against database
4. Returns ranked matches with confidence scores
**Try the example buttons in the sidebar!**
""")
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666; font-size: 0.8rem;">
๐ฌ MicroID - Educational Bacterial Identification System | Based on APIยฎ 20E methodology
</div>
""", unsafe_allow_html=True) |