Spaces:
Runtime error
Runtime error
Download app.py from ShoaibAI/apiweb-local: direct link, hf CLI and curl.
- Browser
- Download file 19.7 kB
-
https://huggingface.co/spaces/ShoaibAI/apiweb-local/resolve/main/app.py
- Command line
-
hf download hf://spaces/ShoaibAI/apiweb-local/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ShoaibAI/apiweb-local/resolve/main/app.py
19.7 kB
| 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 | |
| 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) |