Download app.py from larxius/larmedix: direct link, hf CLI and curl.
- Browser
- Download file 32.5 kB
-
https://huggingface.co/spaces/larxius/larmedix/resolve/main/app.py
- Command line
-
hf download hf://spaces/larxius/larmedix/app.py
-
curl -L -o app.py https://huggingface.co/spaces/larxius/larmedix/resolve/main/app.py
32.5 kB
| from flask import Flask, redirect, url_for, flash, request, jsonify, render_template | |
| from flask_login import LoginManager | |
| from flask_cors import CORS | |
| from flask_mail import Mail, Message | |
| from models import db, User | |
| import os | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.ensemble import RandomForestClassifier | |
| from sklearn.preprocessing import LabelEncoder | |
| import joblib | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| # Urology AI Model Configurations | |
| # Global variables | |
| model = None | |
| label_encoders = {} | |
| feature_columns = [] | |
| diagnosis_classes = [] | |
| accuracy = 0 | |
| MODEL_FILE = 'urology_model.pkl' | |
| ENCODERS_FILE = 'urology_encoders.pkl' | |
| EXCEL_FILE_PATH = 'Full_Urology_OPD_Form_Dataset_3000.xlsx' | |
| def train_model(): | |
| """Train model from Excel file and save to disk""" | |
| global model, label_encoders, feature_columns, diagnosis_classes, accuracy | |
| # Server/HF: Excel dataset is intentionally excluded from the image. | |
| # Skip retraining gracefully instead of crashing the startup. | |
| if not os.path.exists(EXCEL_FILE_PATH): | |
| print(f"⚠️ Training data not found ({EXCEL_FILE_PATH}). Skipping retrain.") | |
| return False | |
| print("=" * 60) | |
| print("📊 Training model from Excel file...") | |
| print("=" * 60) | |
| # Load Excel | |
| try: | |
| df = pd.read_excel(EXCEL_FILE_PATH, sheet_name='Full_Urology_Form_Dataset') | |
| print(f"✓ Loaded {len(df)} records") | |
| except Exception as e: | |
| print(f"✗ Error: {e}") | |
| return False | |
| # Target column (Special_Investigation contains the actual urology diseases in the Excel dataset) | |
| target_col = 'Special_Investigation' | |
| if target_col not in df.columns: | |
| print(f"✗ Column '{target_col}' not found") | |
| return False | |
| # Remove empty diagnoses | |
| df = df.dropna(subset=[target_col]) | |
| diagnosis_classes = df[target_col].unique().tolist() | |
| print(f"✓ Diagnoses: {diagnosis_classes}") | |
| # Feature columns (exclude ID, diagnosis and treatment plan columns) | |
| exclude_cols = ['Patient_ID', 'OPD_No', 'Special_Investigation', 'Provisional_Diagnosis', 'Plan_Of_Treatment'] | |
| feature_cols = [col for col in df.columns if col not in exclude_cols] | |
| print(f"✓ Features: {len(feature_cols)} columns") | |
| # Prepare features | |
| df_features = df[feature_cols].copy() | |
| df_target = df[target_col].copy() | |
| # Handle missing values | |
| for col in df_features.columns: | |
| if df_features[col].dtype == 'object': | |
| df_features[col] = df_features[col].fillna('None') | |
| else: | |
| df_features[col] = df_features[col].fillna(0) | |
| # Encode categorical features | |
| label_encoders = {} | |
| for col in df_features.select_dtypes(include=['object']).columns: | |
| le = LabelEncoder() | |
| df_features[col] = le.fit_transform(df_features[col].astype(str)) | |
| label_encoders[col] = le | |
| # Encode target | |
| target_encoder = LabelEncoder() | |
| y_encoded = target_encoder.fit_transform(df_target) | |
| label_encoders['_target'] = target_encoder | |
| # Store feature columns | |
| feature_columns = df_features.columns.tolist() | |
| X = df_features.values | |
| y = y_encoded | |
| # Train model | |
| model = RandomForestClassifier( | |
| n_estimators=100, | |
| max_depth=15, | |
| min_samples_split=5, | |
| random_state=42, | |
| class_weight='balanced' | |
| ) | |
| model.fit(X, y) | |
| # Calculate accuracy (using same data for simplicity) | |
| y_pred = model.predict(X) | |
| accuracy = np.mean(y_pred == y) | |
| print(f"\n✅ Model trained!") | |
| print(f"📈 Training accuracy: {accuracy * 100:.2f}%") | |
| # Save model and encoders to disk | |
| joblib.dump(model, MODEL_FILE) | |
| joblib.dump(label_encoders, ENCODERS_FILE) | |
| print(f"💾 Model saved to {MODEL_FILE}") | |
| print("=" * 60) | |
| return True | |
| def load_saved_model(): | |
| """Load pre-trained model from disk""" | |
| global model, label_encoders, feature_columns, diagnosis_classes, accuracy | |
| if os.path.exists(MODEL_FILE) and os.path.exists(ENCODERS_FILE): | |
| print("=" * 60) | |
| print("📂 Loading saved model...") | |
| print("=" * 60) | |
| try: | |
| model = joblib.load(MODEL_FILE) | |
| label_encoders = joblib.load(ENCODERS_FILE) | |
| # Get feature columns from model (store separately or infer) | |
| feature_columns = label_encoders.get('_feature_columns', []) | |
| if not feature_columns: | |
| # Fallback: need to retrain or store this info | |
| print("⚠️ Feature columns not found, please retrain") | |
| return False | |
| target_encoder = label_encoders.get('_target') | |
| if target_encoder: | |
| diagnosis_classes = target_encoder.classes_.tolist() | |
| print(f"✅ Model loaded successfully!") | |
| print(f"📈 Saved accuracy: {accuracy:.2%}") | |
| print("=" * 60) | |
| return True | |
| except Exception as e: | |
| print(f"✗ Error loading model: {e}") | |
| return False | |
| return False | |
| def save_feature_columns(): | |
| """Save feature columns along with encoders""" | |
| global label_encoders, feature_columns | |
| label_encoders['_feature_columns'] = feature_columns | |
| joblib.dump(label_encoders, ENCODERS_FILE) | |
| def predict_single(patient_data): | |
| """Predict diagnosis for a single patient""" | |
| global model, label_encoders, feature_columns | |
| feature_vector = [] | |
| for col in feature_columns: | |
| value = patient_data.get(col, None) | |
| if value is None or value == '': | |
| value = 'None' | |
| if isinstance(value, bool): | |
| value = 'Yes' if value else 'No' | |
| if col in label_encoders: | |
| try: | |
| encoded = label_encoders[col].transform([str(value)])[0] | |
| except ValueError: | |
| encoded = 0 | |
| feature_vector.append(encoded) | |
| else: | |
| try: | |
| feature_vector.append(float(value)) | |
| except: | |
| feature_vector.append(0) | |
| feature_array = np.array(feature_vector).reshape(1, -1) | |
| probabilities = model.predict_proba(feature_array)[0] | |
| target_encoder = label_encoders.get('_target') | |
| if target_encoder: | |
| class_names = target_encoder.classes_ | |
| else: | |
| class_names = model.classes_ | |
| predictions = [] | |
| for i, prob in enumerate(probabilities): | |
| if i < len(class_names): | |
| predictions.append({ | |
| 'diagnosis': class_names[i], | |
| 'confidence': float(prob) | |
| }) | |
| predictions.sort(key=lambda x: x['confidence'], reverse=True) | |
| return predictions | |
| def get_recommendations(diagnosis, patient_data=None): | |
| """Generate structured clinical recommendations""" | |
| if patient_data is None: | |
| patient_data = {} | |
| # Build reasons dynamically based on positive symptoms/vitals | |
| reasons = [] | |
| try: | |
| age = int(patient_data.get('Age', 0)) | |
| except (ValueError, TypeError): | |
| age = 0 | |
| if age > 50 and 'Prostate' in diagnosis: | |
| reasons.append('Age > 50 Risk Factor') | |
| if patient_data.get('Frequency_Nocturia') == 'Yes': | |
| reasons.append('Frequency / Nocturia') | |
| if patient_data.get('Urgency') == 'Yes': | |
| reasons.append('Urgency') | |
| if patient_data.get('Urge_Incontinence') == 'Yes': | |
| reasons.append('Urge Incontinence') | |
| if patient_data.get('Hesitancy') == 'Yes': | |
| reasons.append('Hesitancy') | |
| if patient_data.get('Poor_Urinary_Stream') == 'Yes': | |
| reasons.append('Poor Urinary Stream') | |
| if patient_data.get('Straining_To_Void') == 'Yes': | |
| reasons.append('Straining to Void') | |
| if patient_data.get('Intermittency') == 'Yes': | |
| reasons.append('Intermittency') | |
| if patient_data.get('Post_Void_Dribbling') == 'Yes': | |
| reasons.append('Post Void Dribbling') | |
| if patient_data.get('Incomplete_Emptying') == 'Yes': | |
| reasons.append('Incomplete Emptying') | |
| if patient_data.get('Chief_Complaints') and patient_data.get('Chief_Complaints') != 'None': | |
| reasons.append(f"Complaint: {patient_data.get('Chief_Complaints')}") | |
| if not reasons: | |
| reasons.append('Pattern matched by AI Model based on Vitals and Demographics') | |
| # Mapping for tests, medicines, and specialists | |
| rec_data = { | |
| 'BPH': { | |
| 'tests': ['PSA Test', 'Uroflowmetry', 'USG KUB with PVR'], | |
| 'medicines': ['Alpha Blocker', '5-Alpha Reductase Inhibitor', 'Pain Management'], | |
| 'specialist': 'Urologist' | |
| }, | |
| 'Prostate Cancer': { | |
| 'tests': ['PSA Test', 'Prostate MRI', 'Prostate Biopsy', 'Bone Scan'], | |
| 'medicines': ['Hormone Therapy', 'Pain Management'], | |
| 'specialist': 'Uro-oncologist' | |
| }, | |
| 'UTI': { | |
| 'tests': ['Urine Routine & Micro', 'Urine Culture', 'CBC'], | |
| 'medicines': ['Antibiotic', 'Urinary Alkalizer', 'Pain Management'], | |
| 'specialist': 'Urologist or General Physician' | |
| }, | |
| 'Kidney Stone': { | |
| 'tests': ['CT KUB', 'USG KUB', 'Serum Creatinine', 'Uric Acid'], | |
| 'medicines': ['Alpha Blocker (Medical Expulsive Therapy)', 'Antispasmodic', 'Analgesic'], | |
| 'specialist': 'Urologist' | |
| }, | |
| 'Urethral Stricture': { | |
| 'tests': ['Uroflowmetry', 'RGU/MCU (Urethrogram)', 'USG KUB'], | |
| 'medicines': ['Antibiotic (Prophylaxis)', 'Pain Management'], | |
| 'specialist': 'Urologist' | |
| }, | |
| 'Overactive Bladder': { | |
| 'tests': ['Urine Routine', 'Urodynamics', 'USG KUB'], | |
| 'medicines': ['Anticholinergic', 'Beta-3 Agonist'], | |
| 'specialist': 'Urologist' | |
| }, | |
| 'Hydronephrosis': { | |
| 'tests': ['USG KUB', 'CT KUB/Urogram', 'Serum Creatinine'], | |
| 'medicines': ['Antibiotic (if infected)', 'Pain Management'], | |
| 'specialist': 'Urologist' | |
| }, | |
| 'Neurogenic Bladder': { | |
| 'tests': ['Urodynamics', 'MRI Spine', 'Serum Creatinine'], | |
| 'medicines': ['Anticholinergic', 'Antibiotic (if UTI present)'], | |
| 'specialist': 'Urologist / Neurologist' | |
| }, | |
| 'CKD': { | |
| 'tests': ['Serum Creatinine', 'eGFR', 'Electrolytes', 'Urine Albumin'], | |
| 'medicines': ['Antihypertensive', 'Diuretic', 'Phosphate Binder'], | |
| 'specialist': 'Nephrologist' | |
| }, | |
| 'Epididymo-orchitis': { | |
| 'tests': ['Scrotal Doppler Ultrasound', 'Urine Culture', 'CBC'], | |
| 'medicines': ['Antibiotic', 'NSAID (Pain/Inflammation)'], | |
| 'specialist': 'Urologist' | |
| } | |
| } | |
| # Default fallback | |
| result = { | |
| 'reasons': reasons[:5], | |
| 'tests': ['Complete Blood Count (CBC)', 'Urine Routine', 'USG KUB'], | |
| 'medicines': ['Symptomatic Management', 'Pain Management'], | |
| 'specialist': 'Urologist or General Physician' | |
| } | |
| for key in rec_data: | |
| if key in diagnosis or diagnosis in key: | |
| result['tests'] = rec_data[key]['tests'] | |
| result['medicines'] = rec_data[key]['medicines'] | |
| result['specialist'] = rec_data[key]['specialist'] | |
| break | |
| return result | |
| def create_app(): | |
| app = Flask(__name__) | |
| CORS(app) | |
| # Mail config (all via env so secrets are not hardcoded for HF/GCP) | |
| app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER', 'smtp.gmail.com') | |
| app.config['MAIL_PORT'] = int(os.environ.get('MAIL_PORT', '587')) | |
| app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS', 'true').lower() == 'true' | |
| app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME', 'shms1234@gmail.com') | |
| app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD', '') | |
| app.config['MAIL_DEFAULT_SENDER'] = os.environ.get( | |
| 'MAIL_DEFAULT_SENDER', app.config['MAIL_USERNAME'] | |
| ) | |
| mail = Mail(app) | |
| app.extensions['mail'] = mail # Make it accessible globally | |
| app.jinja_env.globals.update(getattr=getattr) | |
| app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'your_secret_key_here') | |
| # ---- Database: separate GCP PostgreSQL config (see database.py) ---- | |
| # Instance: larmedix-db | Database: larmedix | |
| # Set DATABASE_URL or DB_USER/DB_HOST/... env vars to connect. | |
| # Falls back to local SQLite for dev. Tables auto-created on first init. | |
| from database import get_database_uri, get_engine_options, init_database | |
| app.config['SQLALCHEMY_DATABASE_URI'] = get_database_uri() | |
| app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False | |
| app.config['SQLALCHEMY_ENGINE_OPTIONS'] = get_engine_options( | |
| app.config['SQLALCHEMY_DATABASE_URI'] | |
| ) | |
| app.config['UPLOAD_FOLDER'] = os.environ.get( | |
| 'UPLOAD_FOLDER', os.path.join('static', 'uploads') | |
| ) | |
| # Ensure upload directory exists | |
| os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) | |
| # Optional logo override: place static/logo.png yourself or set LOGO_SRC_PATH. | |
| # (Previous hardcoded Windows path removed for HF/server compatibility.) | |
| try: | |
| from PIL import Image | |
| src_path = os.environ.get('LOGO_SRC_PATH', '') | |
| dst_path = os.path.join(app.static_folder, 'logo.png') | |
| if src_path and os.path.exists(src_path) and not os.path.exists(dst_path): | |
| img = Image.open(src_path) | |
| # Resize preserving aspect ratio (height: 60px) | |
| max_height = 60 | |
| width, height = img.size | |
| new_width = int(width * (max_height / height)) | |
| img = img.resize((new_width, max_height), Image.Resampling.LANCZOS) | |
| # Ensure white background | |
| if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info): | |
| background = Image.new("RGBA", img.size, (255, 255, 255, 255)) | |
| background.paste(img, (0, 0), img.convert("RGBA")) | |
| final_img = background.convert("RGB") | |
| else: | |
| background = Image.new("RGB", img.size, (255, 255, 255)) | |
| background.paste(img, (0, 0)) | |
| final_img = background | |
| final_img.save(dst_path, "PNG") | |
| except Exception as e: | |
| print("Error processing logo image:", e) | |
| db.init_app(app) | |
| login_manager = LoginManager() | |
| login_manager.login_view = 'auth.login' | |
| login_manager.init_app(app) | |
| def load_user(id): | |
| return User.query.get(int(id)) | |
| # Import and register blueprints | |
| from routes.auth import auth_bp | |
| from routes.patient import patient_bp | |
| from routes.doctor import doctor_bp | |
| from routes.reception import reception_bp | |
| from routes.admin import admin_bp | |
| from routes.kiosk import kiosk_bp | |
| from routes.workflow import workflow_bp | |
| from routes.superadmin import superadmin_bp | |
| app.register_blueprint(auth_bp, url_prefix='/auth') | |
| app.register_blueprint(patient_bp, url_prefix='/patient') | |
| app.register_blueprint(doctor_bp, url_prefix='/doctor') | |
| app.register_blueprint(reception_bp, url_prefix='/reception') | |
| app.register_blueprint(admin_bp, url_prefix='/admin') | |
| app.register_blueprint(kiosk_bp, url_prefix='/kiosk') | |
| app.register_blueprint(workflow_bp, url_prefix='/workflow') | |
| app.register_blueprint(superadmin_bp, url_prefix='/superadmin') | |
| from utils.sarvam import translate_text | |
| def translate_filter(text, target_lang): | |
| return translate_text(text, target_lang) | |
| def inject_notifications(): | |
| """Bell dropdown items for the logged-in role (best effort).""" | |
| from flask_login import current_user | |
| items = [] | |
| try: | |
| if not current_user.is_authenticated: | |
| return {'notifications': items} | |
| from models import ( | |
| Appointment, ClinicalWorkflow, FollowUp, Hospital, | |
| PatientProfile, User, WalkInQueue, | |
| ) | |
| role = current_user.role | |
| if role == 'doctor': | |
| crit = ClinicalWorkflow.query.filter( | |
| ClinicalWorkflow.doctor_id == current_user.id, | |
| ClinicalWorkflow.status == 'Active', | |
| ClinicalWorkflow.ai_confidence > 0.8).count() | |
| if crit: | |
| items.append({'icon': 'alert-triangle', 'title': f'{crit} critical alert(s)', | |
| 'sub': 'High AI risk — review now', | |
| 'url': url_for('doctor.dashboard')}) | |
| pend = FollowUp.query.filter_by(doctor_id=current_user.id, status='Pending').count() | |
| if pend: | |
| items.append({'icon': 'calendar-clock', 'title': f'{pend} pending follow-up(s)', | |
| 'sub': 'Scheduled follow-ups', | |
| 'url': url_for('doctor.dashboard')}) | |
| sched = Appointment.query.filter_by(doctor_id=current_user.id, status='Scheduled').count() | |
| if sched: | |
| items.append({'icon': 'users', 'title': f'{sched} scheduled appointment(s)', | |
| 'sub': 'Upcoming consultations', | |
| 'url': url_for('doctor.dashboard') + '#consultation-list'}) | |
| queue = ClinicalWorkflow.query.filter( | |
| ClinicalWorkflow.status == 'Active', | |
| ((ClinicalWorkflow.doctor_id == current_user.id) | | |
| (ClinicalWorkflow.doctor_id == None))).count() | |
| if queue: | |
| items.append({'icon': 'stethoscope', 'title': f'{queue} active consultation(s)', | |
| 'sub': 'In your queue', | |
| 'url': url_for('doctor.dashboard') + '#workflow-queue'}) | |
| elif role == 'reception': | |
| waiting = WalkInQueue.query.filter_by(status='Waiting').count() | |
| if waiting: | |
| items.append({'icon': 'users', 'title': f'{waiting} walk-in(s) waiting', | |
| 'sub': 'Token queue needs attention', | |
| 'url': url_for('reception.dashboard') + '#queue-management'}) | |
| hid = current_user.hospital_id | |
| q = Appointment.query | |
| if hid is not None: | |
| q = q.filter((Appointment.hospital_id == hid) | (Appointment.hospital_id == None)) | |
| unpaid = q.filter_by(status='Completed', billing_status='Pending').count() | |
| if unpaid: | |
| items.append({'icon': 'receipt', 'title': f'{unpaid} unpaid bill(s)', | |
| 'sub': 'Billing needs clearing', | |
| 'url': url_for('reception.dashboard') + '#billing-management'}) | |
| elif role == 'patient': | |
| profile = current_user.patient_profile | |
| if profile: | |
| wf = ClinicalWorkflow.query.filter_by( | |
| patient_id=profile.id, status='Active').first() | |
| if wf: | |
| items.append({'icon': 'heart-pulse', | |
| 'title': 'Consultation in progress', | |
| 'sub': f"Step: {wf.current_step.replace('_', ' ')}", | |
| 'url': url_for('patient.dashboard')}) | |
| fu = FollowUp.query.filter_by( | |
| patient_id=profile.id, status='Pending').count() | |
| if fu: | |
| items.append({'icon': 'calendar-clock', 'title': f'{fu} follow-up(s) scheduled', | |
| 'sub': 'Check your dashboard', | |
| 'url': url_for('patient.dashboard')}) | |
| elif role == 'admin': | |
| hid = current_user.hospital_id | |
| staff = User.query.filter_by(hospital_id=hid).filter( | |
| User.role.in_(['doctor', 'reception'])).count() | |
| items.append({'icon': 'users', 'title': f'{staff} staff account(s)', | |
| 'sub': 'Doctors + reception in your hospital', | |
| 'url': url_for('admin.dashboard')}) | |
| elif role == 'superadmin': | |
| total = Hospital.query.count() | |
| dis = Hospital.query.filter_by(status=False).count() | |
| items.append({'icon': 'globe', 'title': f'{total} hospital(s) on platform', | |
| 'sub': f'{dis} disabled' if dis else 'All active', | |
| 'url': url_for('superadmin.dashboard')}) | |
| except Exception: | |
| items = [] | |
| return {'notifications': items[:6]} | |
| def index(): | |
| from flask_login import current_user | |
| if current_user.is_authenticated: | |
| dest = { | |
| 'patient': 'patient.dashboard', | |
| 'doctor': 'doctor.dashboard', | |
| 'reception': 'reception.dashboard', | |
| 'admin': 'admin.dashboard', | |
| 'superadmin': 'superadmin.dashboard', | |
| }.get(current_user.role) | |
| if dest: | |
| return redirect(url_for(dest)) | |
| return render_template('auth/login.html') | |
| # Load/train Urology model on startup | |
| global model, label_encoders, feature_columns, diagnosis_classes, accuracy | |
| print("\n" + "=" * 60) | |
| print("🚀 UROLOGY AI DIAGNOSTIC SYSTEM") | |
| print("=" * 60) | |
| if load_saved_model(): | |
| print("\n✅ Using pre-trained model (fast startup!)") | |
| print("💡 To retrain with new data, delete urology_model.pkl and restart") | |
| else: | |
| print("\n⚠️ No saved model found. Training from Excel...") | |
| if train_model(): | |
| save_feature_columns() | |
| print("\n✅ Model trained and saved for future use!") | |
| else: | |
| print("\n❌ Could not train model. Check your Excel file.") | |
| def predict(): | |
| try: | |
| data = request.json | |
| if model is None: | |
| return jsonify({'success': False, 'error': 'Model not loaded'}), 500 | |
| predictions = predict_single(data) | |
| if not predictions: | |
| return jsonify({'success': False, 'error': 'Prediction failed'}), 500 | |
| return jsonify({ | |
| 'success': True, | |
| 'diagnosis': predictions[0]['diagnosis'], | |
| 'confidence': predictions[0]['confidence'], | |
| 'top_predictions': predictions[:5], | |
| 'recommendations': get_recommendations(predictions[0]['diagnosis'], data) | |
| }) | |
| except Exception as e: | |
| return jsonify({'success': False, 'error': str(e)}), 500 | |
| def predict_gastro(): | |
| try: | |
| data = request.json | |
| workflow_id = data.get('workflow_id') | |
| patient_id = data.get('patient_id') | |
| from models import Report | |
| import os | |
| report = None | |
| if workflow_id: | |
| from models import ClinicalWorkflow | |
| wf = ClinicalWorkflow.query.get(workflow_id) | |
| if wf: | |
| report = Report.query.filter_by(patient_id=wf.patient_id).order_by(Report.id.desc()).first() | |
| elif patient_id: | |
| report = Report.query.filter_by(patient_id=patient_id).order_by(Report.id.desc()).first() | |
| if not report: | |
| return jsonify({'success': False, 'error': 'No document uploaded for this patient.'}) | |
| from utils.firebase_storage import resolve_to_local | |
| try: | |
| file_path = resolve_to_local( | |
| report.filepath, app.config['UPLOAD_FOLDER'], app.root_path) | |
| except Exception as e: | |
| return jsonify({'success': False, 'error': f'Could not fetch document: {e}'}) | |
| if not os.path.exists(file_path): | |
| # Legacy local file lost (pre-Firebase upload). Ask for a fresh upload. | |
| return jsonify({'success': False, 'error': 'Document file missing on server (uploaded before cloud storage). Please re-upload the document, then run analysis again.'}) | |
| from prediction import predict_image | |
| result = predict_image(file_path) | |
| if not result.get('success'): | |
| err = str(result.get('error', '')) | |
| if 'No such file' in err: | |
| return jsonify({'success': False, 'error': 'Document file missing on server (uploaded before cloud storage). Please re-upload the document, then run analysis again.'}) | |
| return jsonify(result) | |
| # Gastro Medicine mapping | |
| disease = result['class'].lower() | |
| meds = "Symptomatic Management" | |
| diet = "General healthy diet, avoid spicy foods." | |
| if "angiectasia" in disease: | |
| meds = "Iron supplements (e.g., Ferrous sulfate 325 mg), Somatostatin analogs if severe." | |
| diet = "High-iron diet, avoid NSAIDs." | |
| elif "barrett" in disease: | |
| meds = "PPIs (e.g., Omeprazole 40mg daily), Antacids." | |
| diet = "Avoid acidic, spicy, and fatty foods. Avoid eating right before bed." | |
| elif "diverticula" in disease: | |
| meds = "Antibiotics if infected (e.g., Ciprofloxacin + Metronidazole), Antispasmodics." | |
| diet = "High-fiber diet (during asymptomatic), Low-residue diet (during acute flare-up)." | |
| elif "colon polyps" in disease or "gastric polyps" in disease: | |
| meds = "Aspirin/COX-2 inhibitors (for prevention). Mainly requires endoscopic removal." | |
| diet = "High-fiber diet, limit red meat and processed foods." | |
| elif "colorectal cancer" in disease: | |
| meds = "Chemotherapy agents (e.g., Fluorouracil, Oxaliplatin) per oncologist." | |
| diet = "Nutrient-dense diet, high protein." | |
| elif "esophagitis" in disease: | |
| meds = "PPIs (e.g., Pantoprazole 40mg), H2 blockers (e.g., Famotidine)." | |
| diet = "Soft foods, avoid acidic, caffeine, and spicy items." | |
| elif "varices" in disease: | |
| meds = "Non-selective beta-blockers (e.g., Propranolol, Nadolol)." | |
| diet = "Soft diet to prevent bleeding, low sodium if cirrhotic." | |
| elif "ulcer" in disease: | |
| meds = "PPIs, Amoxicillin + Clarithromycin (if H. pylori positive)." | |
| diet = "Avoid spicy foods, alcohol, and caffeine." | |
| elif "mucosal inflammation" in disease: | |
| meds = "5-ASAs (e.g., Mesalamine), Corticosteroids for flare-ups." | |
| diet = "Low-FODMAP, avoid dairy if lactose intolerant." | |
| elif "normal" in disease: | |
| meds = "No medications needed." | |
| diet = "Continue regular balanced diet." | |
| return jsonify({ | |
| 'success': True, | |
| 'disease': result['class'], | |
| 'confidence': result['confidence'], | |
| 'medications': meds, | |
| 'diet_notes': diet | |
| }) | |
| except Exception as e: | |
| return jsonify({'success': False, 'error': str(e)}), 500 | |
| def extract_lab_report(): | |
| """OCR a report photo -> 13 lab values (local EasyOCR, no API key).""" | |
| try: | |
| if 'file' not in request.files: | |
| return jsonify({'success': False, 'error': 'No file uploaded.'}) | |
| f = request.files['file'] | |
| if not f.filename: | |
| return jsonify({'success': False, 'error': 'No file selected.'}) | |
| ext = os.path.splitext(f.filename)[1].lower() | |
| if ext not in ('.jpg', '.jpeg', '.png'): | |
| return jsonify({'success': False, 'error': 'Upload a JPG/PNG photo of the report (PDF not supported).'}) | |
| import uuid | |
| from werkzeug.utils import secure_filename | |
| fname = f"{uuid.uuid4().hex}_{secure_filename(f.filename)}" | |
| os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) | |
| local = os.path.join(app.config['UPLOAD_FOLDER'], fname) | |
| f.save(local) | |
| from lab_prediction import process_lab_image | |
| return jsonify(process_lab_image(local)) | |
| except Exception as e: | |
| return jsonify({'success': False, 'error': str(e)}), 500 | |
| def predict_lab_report(): | |
| try: | |
| data = request.json or {} | |
| from lab_prediction import predict_lab_disease, FEATURES | |
| values = {k: (data.get(k) if data.get(k) != '' else None) for k in FEATURES} | |
| missing = [k for k, v in values.items() if v is None] | |
| if missing: | |
| return jsonify({'success': False, 'error': 'Missing values: ' + ', '.join(missing)}) | |
| for k in list(values): | |
| v = values[k] | |
| if k != 'Gender' and v is not None: | |
| try: | |
| values[k] = float(v) | |
| except (ValueError, TypeError): | |
| pass | |
| return jsonify(predict_lab_disease(values)) | |
| except Exception as e: | |
| return jsonify({'success': False, 'error': str(e)}), 500 | |
| def save_gastro_audit(): | |
| try: | |
| data = request.json | |
| patient_id = data.get('patient_id') | |
| ai_prediction = data.get('ai_prediction') | |
| confidence = data.get('confidence') | |
| doctor_diagnosis = data.get('doctor_diagnosis') | |
| if ai_prediction and doctor_diagnosis and ai_prediction.strip().lower() != doctor_diagnosis.strip().lower(): | |
| from models import AIAuditLog, ClinicalWorkflow | |
| import json | |
| wf = ClinicalWorkflow.query.filter_by(patient_id=patient_id).order_by(ClinicalWorkflow.id.desc()).first() | |
| wf_id = wf.id if wf else 0 | |
| audit_log = AIAuditLog( | |
| workflow_id=wf_id, | |
| patient_input_json=json.dumps({"source": "Gastro Document Analysis"}), | |
| ai_prediction=ai_prediction, | |
| confidence_score=float(confidence)/100 if confidence else 0.0, | |
| doctor_diagnosis=doctor_diagnosis, | |
| final_diagnosis=doctor_diagnosis | |
| ) | |
| db.session.add(audit_log) | |
| db.session.commit() | |
| return jsonify({'success': True}) | |
| except Exception as e: | |
| return jsonify({'success': False, 'error': str(e)}), 500 | |
| def retrain(): | |
| """Force retrain the model""" | |
| if train_model(): | |
| save_feature_columns() | |
| return jsonify({'success': True, 'message': 'Model retrained successfully'}) | |
| return jsonify({'success': False, 'error': 'Retraining failed'}), 500 | |
| def get_branches(hospital_id): | |
| from models import Branch | |
| branches = Branch.query.filter_by(hospital_id=hospital_id, status=True).all() | |
| return jsonify({'success': True, 'branches': [{'id': b.id, 'name': b.name} for b in branches]}) | |
| # ---- Init DB: auto-creates tables on first connection (Postgres/SQLite) ---- | |
| # GCP Cloud SQL (larmedix-db / larmedix) credentials come from env vars, | |
| # see database.py. Safe to run on every startup (idempotent). | |
| init_database(app) | |
| return app | |
| if __name__ == '__main__': | |
| app = create_app() | |
| # HuggingFace Spaces requires port 7860 on 0.0.0.0 | |
| port = int(os.environ.get('PORT', '7860')) | |
| app.run(host='0.0.0.0', port=port, debug=os.environ.get('FLASK_DEBUG', 'false').lower() == 'true') | |