File size: 10,228 Bytes
a1a73b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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/<path:filename>')
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)