""" BBB Agent Web Server (v3) ========================= /api/predict - structured scoring + per-residue property maps (cards) /api/chat - conversational agent (Gemini function-calling + memory) SETUP: pip install flask flask-cors google-generativeai xgboost numpy set GEMINI_API_KEY=your_key (Windows) / export ... (Mac/Linux) RUN: python bbb_server.py -> open http://localhost:5000 """ import os, json, uuid, glob import numpy as np from flask import Flask, request, jsonify, send_from_directory from flask_cors import CORS from xgboost import XGBClassifier from bbb_features import encode, properties def _find(*patterns): """Find a file by trying several glob patterns; tolerant of (1)/(2) suffixes.""" for pat in patterns: hits = sorted(glob.glob(pat)) if hits: return hits[0] raise FileNotFoundError(f"None of these found: {patterns}") MODEL_FILE = _find('bbb_final_model.json', 'bbb_final_model*.json', '*final_model*.json') META_FILE = _find('model_meta.json', 'model_meta*.json', '*model_meta*.json') INDEX_FILE = os.path.basename(_find('index.html', 'index*.html')) MODEL = XGBClassifier() MODEL.load_model(MODEL_FILE) META = json.load(open(META_FILE)) THRESHOLD = META['threshold'] VALID_AA = set('ACDEFGHIKLMNPQRSTVWY') HYDRO = {'A':1.8,'R':-4.5,'N':-3.5,'D':-3.5,'C':2.5,'Q':-3.5,'E':-3.5,'G':-0.4,'H':-3.2, 'I':4.5,'L':3.8,'K':-3.9,'M':1.9,'F':2.8,'P':-1.6,'S':-0.8,'T':-0.7,'W':-0.9,'Y':-1.3,'V':4.2} CHARGE = {'R':1,'K':1,'H':0.1,'D':-1,'E':-1,'A':0,'C':0,'F':0,'G':0,'I':0,'L':0,'M':0,'N':0, 'P':0,'Q':0,'S':0,'T':0,'V':0,'W':0,'Y':0} GEMINI_KEY = os.environ.get('GEMINI_API_KEY') USE_GEMINI = bool(GEMINI_KEY) if USE_GEMINI: import google.generativeai as genai genai.configure(api_key=GEMINI_KEY) # Optional shared password. Set APP_PASSWORD in the environment to enable the gate. # If APP_PASSWORD is unset or empty, the app is open (no password required). APP_PASSWORD = os.environ.get('APP_PASSWORD', '').strip() def password_ok(req): """Return True if no password is configured, or the request supplies the right one.""" if not APP_PASSWORD: return True supplied = req.headers.get('X-App-Password', '') if not supplied: data = req.get_json(silent=True) or {} supplied = data.get('password', '') return supplied == APP_PASSWORD def predict_one(seq): seq = seq.upper().strip() bad = [a for a in seq if a not in VALID_AA] if bad: return {'sequence': seq, 'valid': False, 'error': f'Invalid residues: {sorted(set(bad))}'} prob = float(MODEL.predict_proba(encode(seq).reshape(1, -1).astype(np.float32))[0, 1]) pred = 'BBB+' if prob >= THRESHOLD else 'BBB-' conf = 'high' if abs(prob - 0.5) > 0.30 else 'moderate' if abs(prob - 0.5) > 0.12 else 'low' p = properties(seq) residues = [{'aa': a, 'hydro': round(HYDRO.get(a, 0), 1), 'charge': CHARGE.get(a, 0)} for a in seq] return {'sequence': seq, 'valid': True, 'prediction': pred, 'probability': round(prob, 4), 'confidence': conf, 'reliable': pred == 'BBB+', 'properties': {'mw': p['molecular_weight_da'], 'charge': p['net_charge'], 'hydrophobic': f"{p['n_hydrophobic']}/{p['length']}", 'aromatic': p['n_aromatic'], 'mean_hydro': p['mean_hydrophobicity']}, 'residues': residues} def predict_bbb(sequences: list) -> dict: """Predict blood-brain barrier permeability (BBB+ permeable / BBB- not) for peptide sequences. Args: sequences: list of amino acid sequences in single-letter code. """ return {'results': [predict_one(s) for s in sequences], 'threshold': THRESHOLD} def analyse_properties(sequence: str) -> dict: """Compute physicochemical properties and BBB-relevant hints for one peptide. Args: sequence: one amino acid sequence in single-letter code. """ p = properties(sequence) hints = [] if p['molecular_weight_da'] < 450: hints.append('MW < 450 Da favours crossing') else: hints.append('MW > 450 Da may limit crossing') if p['net_charge'] == 0: hints.append('neutral net charge favours passive diffusion') elif abs(p['net_charge']) > 1: hints.append(f'net charge {p["net_charge"]:+} may hinder diffusion') if p['n_hydrophobic'] / p['length'] > 0.4: hints.append('high hydrophobicity supports permeability') if p['n_aromatic'] > 0: hints.append(f'{p["n_aromatic"]} aromatic residue(s) may aid membrane interaction') p['bbb_hints'] = hints return p def _prob(seq): return float(MODEL.predict_proba(encode(seq).reshape(1, -1).astype(np.float32))[0, 1]) def suggest_mutations(sequence: str, top_n: int = 5) -> dict: """Suggest single amino-acid substitutions that most increase predicted BBB permeability. Scans every position x every amino acid, scores each variant, returns the changes that raise BBB+ probability most. Use when the user wants to IMPROVE or optimize a peptide. Args: sequence: starting peptide in single-letter code. top_n: how many suggestions to return (default 5, max 10). """ seq = sequence.upper().strip() bad = [a for a in seq if a not in VALID_AA] if bad: return {'error': f'Invalid residues: {sorted(set(bad))}'} base = _prob(seq) cands = [] for i, orig in enumerate(seq): for aa in VALID_AA: if aa == orig: continue variant = seq[:i] + aa + seq[i+1:] d = _prob(variant) - base cands.append({'position': i + 1, 'from': orig, 'to': aa, 'variant': variant, 'new_prob': round(base + d, 4), 'delta': round(d, 4)}) cands.sort(key=lambda c: c['delta'], reverse=True) return {'original': seq, 'original_prob': round(base, 4), 'best_mutations': cands[:max(1, min(top_n, 10))]} SYSTEM = f"""You are the BBB Permeability Agent, an expert bioinformatics assistant for blood-brain barrier peptide screening. You have a trained machine learning model accessible through tools (AUROC={META['auc']:.2f}, F1 BBB+={META['f1p']:.2f}, F1 BBB-={META['f1n']:.2f}). Rules: - Always call predict_bbb for permeability questions about sequences. Never guess. - Use analyse_properties to explain the biological reasoning. - Use suggest_mutations when the user wants to IMPROVE, optimize, or increase a peptide's permeability - it scans single-residue changes and finds the best ones. Present the top suggestions clearly (position, change, new probability) and explain the chemistry. - After tools return, explain clearly using markdown (bold for key terms, bullet lists for multiple peptides): prediction, probability, key physicochemical drivers, confidence. - BE HONEST: BBB+ predictions are strong (F1~0.90); BBB- are weak (F1~0.34) - say so and recommend experimental confirmation for BBB- calls. - You can also answer general questions about the blood-brain barrier and peptide chemistry. - Keep replies focused and well-structured.""" SESSIONS = {} def get_chat(sid): if sid not in SESSIONS: m = genai.GenerativeModel(model_name='gemini-2.5-flash', tools=[predict_bbb, analyse_properties, suggest_mutations], system_instruction=SYSTEM) SESSIONS[sid] = m.start_chat(enable_automatic_function_calling=True) return SESSIONS[sid] app = Flask(__name__) CORS(app) @app.route('/') def home(): return send_from_directory('.', INDEX_FILE) @app.route('/assets/') def assets(filename): return send_from_directory('assets', filename) @app.route('/api/meta') def api_meta(): # meta also reports whether a password is required, so the page can show the lock screen return jsonify({'auc': META['auc'], 'f1_pos': META['f1p'], 'f1_neg': META['f1n'], 'threshold': THRESHOLD, 'gemini': USE_GEMINI, 'cv': META.get('cv'), 'calibrated': META.get('well_calibrated', False), 'password_required': bool(APP_PASSWORD)}) @app.route('/api/verify', methods=['POST']) def api_verify(): return jsonify({'ok': password_ok(request)}) @app.route('/api/predict', methods=['POST']) def api_predict(): if not password_ok(request): return jsonify({'error': 'unauthorized'}), 401 data = request.get_json(force=True) seqs = data.get('sequences', []) if isinstance(seqs, str): seqs = [s.strip() for s in seqs.replace(',', '\n').split('\n') if s.strip()] return jsonify({'results': [predict_one(s) for s in seqs]}) @app.route('/api/chat', methods=['POST']) def api_chat(): if not password_ok(request): return jsonify({'error': 'unauthorized'}), 401 if not USE_GEMINI: return jsonify({'error': 'Chat needs GEMINI_API_KEY. Set it and restart the server.'}), 400 data = request.get_json(force=True) msg = (data.get('message') or '').strip() sid = data.get('session_id') or str(uuid.uuid4()) if not msg: return jsonify({'error': 'empty message'}), 400 try: resp = get_chat(sid).send_message(msg) return jsonify({'reply': resp.text, 'session_id': sid}) except Exception as e: return jsonify({'error': str(e), 'session_id': sid}), 500 @app.route('/api/mutate', methods=['POST']) def api_mutate(): if not password_ok(request): return jsonify({'error': 'unauthorized'}), 401 data = request.get_json(force=True) seq = (data.get('sequence') or '').strip() if not seq: return jsonify({'error': 'empty sequence'}), 400 return jsonify(suggest_mutations(seq, int(data.get('top_n', 6)))) @app.route('/api/reset', methods=['POST']) def api_reset(): sid = (request.get_json(force=True) or {}).get('session_id') SESSIONS.pop(sid, None) return jsonify({'ok': True}) if __name__ == '__main__': port = int(os.environ.get('PORT', 7860)) print(f"Model loaded (AUROC={META['auc']:.3f}). Gemini: {'ON' if USE_GEMINI else 'OFF'}") print(f"Open http://localhost:{port}") app.run(host='0.0.0.0', port=port, debug=False)