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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from transformers import AutoModel, AutoTokenizer
|
| 5 |
+
from peft import LoraConfig, get_peft_model
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
device = torch.device('cpu') # HF Free Tier uses CPU
|
| 9 |
+
ckpt = torch.load("AyurGenixV9_FULLY_EMBEDDED.pt", map_location=device, weights_only=False)
|
| 10 |
+
|
| 11 |
+
cfg = ckpt['config']
|
| 12 |
+
all_herbs = ckpt['all_herbs']
|
| 13 |
+
|
| 14 |
+
raw_herb_props = ckpt.get('herb_properties', {})
|
| 15 |
+
if isinstance(raw_herb_props, list):
|
| 16 |
+
herb_props = {str(h.get('name', '')).lower(): h for h in raw_herb_props}
|
| 17 |
+
else:
|
| 18 |
+
herb_props = raw_herb_props
|
| 19 |
+
|
| 20 |
+
formulations = ckpt.get('formulations', [])
|
| 21 |
+
interaction_model = ckpt.get('interaction_model', None)
|
| 22 |
+
le_dosha = ckpt['label_encoder_dosha']
|
| 23 |
+
side_effect_keywords = ckpt.get('side_effect_keywords', [])
|
| 24 |
+
CLASSICAL_INTERACTIONS = ckpt.get('classical_interactions', {})
|
| 25 |
+
HERB_ALIASES = ckpt.get('herb_aliases', {})
|
| 26 |
+
|
| 27 |
+
HERB_ALIASES['licorice'] = 'yashtimadhu'
|
| 28 |
+
HERB_ALIASES['mulethi'] = 'yashtimadhu'
|
| 29 |
+
|
| 30 |
+
class AyurGenixV8(nn.Module):
|
| 31 |
+
def __init__(self, encoder, hidden_size, num_herbs, num_doshas, num_severity, num_se):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.encoder = encoder
|
| 34 |
+
h = hidden_size
|
| 35 |
+
self.trunk = nn.Sequential(nn.Linear(h, 512), nn.LayerNorm(512), nn.GELU(), nn.Dropout(0.2))
|
| 36 |
+
self.herb_head = nn.Sequential(nn.Linear(512, 256), nn.LayerNorm(256), nn.GELU(), nn.Dropout(0.1), nn.Linear(256, num_herbs))
|
| 37 |
+
self.dosha_head = nn.Sequential(nn.Linear(512, 128), nn.GELU(), nn.Linear(128, num_doshas))
|
| 38 |
+
self.severity_head = nn.Sequential(nn.Linear(512, 128), nn.GELU(), nn.Linear(128, num_severity))
|
| 39 |
+
self.conflict_head = nn.Sequential(nn.Linear(512, 64), nn.GELU(), nn.Linear(64, 1))
|
| 40 |
+
self.toxicity_head = nn.Sequential(nn.Linear(512, 64), nn.GELU(), nn.Linear(64, 3))
|
| 41 |
+
self.side_effect_head = nn.Sequential(nn.Linear(512, 128), nn.GELU(), nn.Linear(128, num_se))
|
| 42 |
+
self.dosage_head = nn.Sequential(nn.Linear(512, 64), nn.GELU(), nn.Linear(64, 1))
|
| 43 |
+
|
| 44 |
+
def forward(self, input_ids, attention_mask):
|
| 45 |
+
cls = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state[:, 0, :]
|
| 46 |
+
shared = self.trunk(cls)
|
| 47 |
+
return {'herb': self.herb_head(shared), 'dosha': self.dosha_head(shared), 'severity': self.severity_head(shared), 'conflict': self.conflict_head(shared).squeeze(-1), 'toxicity': self.toxicity_head(shared), 'side_effects': self.side_effect_head(shared), 'dosage': self.dosage_head(shared).squeeze(-1)}
|
| 48 |
+
|
| 49 |
+
model_name = cfg.get('backbone', 'ai4bharat/IndicBERTv2-MLM-only')
|
| 50 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 51 |
+
base_encoder = AutoModel.from_pretrained(model_name)
|
| 52 |
+
lora_encoder = get_peft_model(base_encoder, LoraConfig(r=cfg.get('lora_r', 16), lora_alpha=cfg.get('lora_alpha', 32), lora_dropout=0.1, target_modules=cfg.get('lora_targets', ['query', 'value', 'key']), bias='none'))
|
| 53 |
+
model = AyurGenixV8(lora_encoder, cfg['hidden_size'], cfg['num_herbs'], cfg['num_doshas'], cfg['num_severity'], cfg['num_side_effects']).to(device)
|
| 54 |
+
model.load_state_dict(ckpt['v8_model_state_dict'])
|
| 55 |
+
model.eval()
|
| 56 |
+
|
| 57 |
+
SEV_NAMES = ['Mild', 'Mild-Moderate', 'Moderate', 'Moderate-Severe', 'Severe']
|
| 58 |
+
TOX_NAMES = ['Low', 'Medium', 'High']
|
| 59 |
+
LABEL_NAMES = ['SYNERGISTIC', 'CAUTION', 'CONTRAINDICATED']
|
| 60 |
+
VIRYA_CONFLICT = {'ushna': 0, 'sheeta': 1, 'hot': 0, 'cold': 1}
|
| 61 |
+
RASA_GROUPS = {'madhura': 0, 'sweet': 0, 'amla': 1, 'lavana': 2, 'tikta': 3, 'katu': 4, 'kashaya': 5}
|
| 62 |
+
|
| 63 |
+
def resolve_herb_name(name):
|
| 64 |
+
name = str(name).lower().strip()
|
| 65 |
+
if name in herb_props: return name
|
| 66 |
+
if name in HERB_ALIASES:
|
| 67 |
+
if HERB_ALIASES[name] in herb_props: return HERB_ALIASES[name]
|
| 68 |
+
for db_name in herb_props:
|
| 69 |
+
if name in db_name or db_name in name: return db_name
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
def tokenize_indications(text):
|
| 73 |
+
keys = ['kasa', 'cough', 'jwara', 'fever', 'amavata', 'joint', 'arthritis', 'indigestion', 'prameha', 'diabetes', 'liver', 'skin', 'shwasa', 'asthma']
|
| 74 |
+
return {k for k in keys if k in text.lower()}
|
| 75 |
+
|
| 76 |
+
def encode_herb(props):
|
| 77 |
+
features = []
|
| 78 |
+
virya_val = -1
|
| 79 |
+
for key, val in VIRYA_CONFLICT.items():
|
| 80 |
+
if key in props.get('virya', ''):
|
| 81 |
+
virya_val = val
|
| 82 |
+
break
|
| 83 |
+
features.append(virya_val)
|
| 84 |
+
rasa_vec = [0] * 6
|
| 85 |
+
for key, idx in RASA_GROUPS.items():
|
| 86 |
+
if key in props.get('rasa', ''): rasa_vec[idx] = 1
|
| 87 |
+
features.extend(rasa_vec)
|
| 88 |
+
dosha_text = props.get('dosha_effect', '')
|
| 89 |
+
features.extend([int('vata' in dosha_text), int('pitta' in dosha_text), int('kapha' in dosha_text)])
|
| 90 |
+
return np.array(features, dtype=float)
|
| 91 |
+
|
| 92 |
+
def rule_based_reason(props_a, props_b, label_idx):
|
| 93 |
+
va, vb = props_a.get('virya', ''), props_b.get('virya', '')
|
| 94 |
+
if label_idx == 2: return (f'Opposing Virya ({va} vs {vb}): classical Viruddha pattern.', 'Pitta/Vata vitiation, metabolic confusion.')
|
| 95 |
+
if label_idx == 1: return (f'Pharmacological caution: Rasa/Virya overlap ({va}, {vb}).', 'Possible Pitta aggravation, dryness, or excess stimulation.')
|
| 96 |
+
return ('Aligned Rasa/Virya supports combined therapeutic action.', 'Harmonized Agni and profound therapeutic effect.')
|
| 97 |
+
|
| 98 |
+
def predict_pair(herb_a_display, herb_b_display):
|
| 99 |
+
a, b = resolve_herb_name(herb_a_display), resolve_herb_name(herb_b_display)
|
| 100 |
+
if a and b:
|
| 101 |
+
key = tuple(sorted([a, b]))
|
| 102 |
+
dict_key = f"{key[0]}|{key[1]}"
|
| 103 |
+
if dict_key in CLASSICAL_INTERACTIONS:
|
| 104 |
+
info = CLASSICAL_INTERACTIONS[dict_key]
|
| 105 |
+
return {'type': info['type'], 'confidence': '100% (Classical Text)', 'source': 'Charaka Samhita Curated Pair', 'reason': info.get('reason', 'Documented classical interaction.'), 'body': info.get('body', 'Varies based on text.')}
|
| 106 |
+
if not a or not b or interaction_model is None:
|
| 107 |
+
return {'type': 'UNKNOWN', 'confidence': '0%', 'source': 'N/A', 'reason': 'One or both herbs missing from database.', 'body': 'N/A'}
|
| 108 |
+
feat_a, feat_b = encode_herb(herb_props[a]), encode_herb(herb_props[b])
|
| 109 |
+
combined = np.concatenate([feat_a, feat_b, np.abs(feat_a - feat_b), feat_a * feat_b])
|
| 110 |
+
pred = int(interaction_model.predict([combined])[0])
|
| 111 |
+
proba = interaction_model.predict_proba([combined])[0]
|
| 112 |
+
reason, body = rule_based_reason(herb_props[a], herb_props[b], pred)
|
| 113 |
+
return {'type': LABEL_NAMES[pred], 'confidence': f"{proba[pred]*100:.1f}% (ML + Dravyaguna rules)", 'source': 'RandomForest on herb_properties', 'reason': reason, 'body': body}
|
| 114 |
+
|
| 115 |
+
def generate_report(symptoms, season, age, gender):
|
| 116 |
+
clinical_text = f"symptoms: {symptoms} | season: {season} | age: {age} | gender: {gender}"
|
| 117 |
+
enc = tokenizer(clinical_text, return_tensors='pt', max_length=128, padding='max_length', truncation=True)
|
| 118 |
+
with torch.no_grad(): out = model(enc['input_ids'].to(device), enc['attention_mask'].to(device))
|
| 119 |
+
|
| 120 |
+
herb_probs = torch.sigmoid(out['herb']).cpu().numpy()[0]
|
| 121 |
+
top_idx = herb_probs.argsort()[::-1][:4]
|
| 122 |
+
recommended = [(all_herbs[i].capitalize(), float(herb_probs[i])) for i in top_idx]
|
| 123 |
+
|
| 124 |
+
dosha_pred = le_dosha.inverse_transform([torch.argmax(out['dosha'], 1).cpu().item()])[0]
|
| 125 |
+
severity_pred = SEV_NAMES[torch.argmax(out['severity'], 1).cpu().item()]
|
| 126 |
+
conflict = torch.sigmoid(out['conflict']).item() > 0.5
|
| 127 |
+
toxicity_pred = TOX_NAMES[torch.argmax(out['toxicity'], 1).cpu().item()]
|
| 128 |
+
dosage_mg = float(out['dosage'].item() * 1000)
|
| 129 |
+
se_probs = torch.sigmoid(out['side_effects']).cpu().numpy()[0]
|
| 130 |
+
active_se = [side_effect_keywords[i] for i in range(len(se_probs)) if se_probs[i] > 0.5] if side_effect_keywords else []
|
| 131 |
+
|
| 132 |
+
lines = []
|
| 133 |
+
lines.append("=" * 70)
|
| 134 |
+
lines.append(" AYURGENIX V9 — CLINICAL INTELLIGENCE REPORT")
|
| 135 |
+
lines.append("=" * 70)
|
| 136 |
+
lines.append(f"\nPatient: {age} yrs | {gender} | {season}")
|
| 137 |
+
lines.append(f"Symptoms: {symptoms}")
|
| 138 |
+
|
| 139 |
+
lines.append("\n--- MULTI-TASK ANALYSIS (Neural Network Predictions) ---")
|
| 140 |
+
lines.append(f" Dosha imbalance : {dosha_pred}")
|
| 141 |
+
lines.append(f" Disease severity : {severity_pred}")
|
| 142 |
+
lines.append(f" Drug safety : {'CAUTION DETECTED' if conflict else 'No Conflicts'}")
|
| 143 |
+
lines.append(f" Toxicity level : {toxicity_pred}")
|
| 144 |
+
lines.append(f" Safe dosage (model) : {dosage_mg:.0f} mg/day")
|
| 145 |
+
lines.append(f" Side effects : {', '.join(active_se) if active_se else 'None detected'}")
|
| 146 |
+
|
| 147 |
+
lines.append("\n--- RECOMMENDED HERBS (Neural Network Predictions) ---")
|
| 148 |
+
rec_canonical = []
|
| 149 |
+
for h, prob in recommended:
|
| 150 |
+
canon = resolve_herb_name(h) or '?'
|
| 151 |
+
rec_canonical.append(canon)
|
| 152 |
+
preview = f"rasa={herb_props[canon].get('rasa','')} virya={herb_props[canon].get('virya','')}" if canon in herb_props else ""
|
| 153 |
+
lines.append(f" -> {h} ({prob*100:.1f}%) [DB: {canon}]")
|
| 154 |
+
if preview: lines.append(f" {preview}")
|
| 155 |
+
|
| 156 |
+
lines.append("\n--- CLASSICAL FORMULATION MATCH (From Bhaishajya Kosha) ---")
|
| 157 |
+
best, best_score = None, -1
|
| 158 |
+
sym_tokens = tokenize_indications(symptoms)
|
| 159 |
+
herb_set = set([c for c in rec_canonical if c])
|
| 160 |
+
for form in formulations:
|
| 161 |
+
ftokens = tokenize_indications(form.get('indications', ''))
|
| 162 |
+
overlap = len(sym_tokens & ftokens) * 2 + len(herb_set & set([resolve_herb_name(i) for i in form.get('main_ingredients', []) if resolve_herb_name(i)])) * 3
|
| 163 |
+
if overlap > best_score: best_score, best = overlap, form
|
| 164 |
+
|
| 165 |
+
if best:
|
| 166 |
+
lines.append(f" Name : {best.get('name', 'N/A')}")
|
| 167 |
+
lines.append(f" Category : {best.get('category', 'N/A')}")
|
| 168 |
+
lines.append(f" Dosage : {best.get('dosage', 'Standard Dosage')}")
|
| 169 |
+
lines.append(f" Anupana : {best.get('anupana', 'Warm water')}")
|
| 170 |
+
lines.append(f" Reference : {best.get('reference', 'Classical Text')}")
|
| 171 |
+
lines.append(f" Indications: {best.get('indications', '')[:200]}...")
|
| 172 |
+
else: lines.append(" No direct classical formulation match found.")
|
| 173 |
+
|
| 174 |
+
lines.append("\n--- HERB-HERB INTERACTIONS (From KnowledgeBundle & ML) ---")
|
| 175 |
+
names = [h for h, _ in recommended]
|
| 176 |
+
interactions_found = 0
|
| 177 |
+
for i in range(len(names)):
|
| 178 |
+
for j in range(i + 1, len(names)):
|
| 179 |
+
pair_res = predict_pair(names[i], names[j])
|
| 180 |
+
if pair_res['type'] == 'UNKNOWN': continue
|
| 181 |
+
interactions_found += 1
|
| 182 |
+
tag = {'SYNERGISTIC': '[OK]', 'CAUTION': '[WARN]', 'CONTRAINDICATED': '[DANGER]'}.get(pair_res['type'], '[?]')
|
| 183 |
+
lines.append(f"\n {tag} {names[i]} + {names[j]}")
|
| 184 |
+
lines.append(f" Type : {pair_res['type']} | {pair_res['confidence']}")
|
| 185 |
+
lines.append(f" Source : {pair_res['source']}")
|
| 186 |
+
lines.append(f" Reason : {pair_res['reason']}")
|
| 187 |
+
lines.append(f" Body effect: {pair_res['body']}")
|
| 188 |
+
if interactions_found == 0: lines.append(" No documented interactions found in database for the recommended herbs.")
|
| 189 |
+
|
| 190 |
+
lines.append("\n--- DISCLAIMER ---")
|
| 191 |
+
lines.append("AI-assisted Ayurvedic clinical decision support for research and education only.")
|
| 192 |
+
lines.append("=" * 70)
|
| 193 |
+
return "\n".join(lines)
|
| 194 |
+
|
| 195 |
+
interface = gr.Interface(
|
| 196 |
+
fn=generate_report,
|
| 197 |
+
inputs=[gr.Textbox(label="Symptoms"), gr.Dropdown(["Summer", "Winter", "Monsoon", "Autumn", "Spring"], label="Season"), gr.Number(label="Age", value=30), gr.Dropdown(["Male", "Female"], label="Gender")],
|
| 198 |
+
outputs=gr.Textbox(label="Clinical Report")
|
| 199 |
+
)
|
| 200 |
+
interface.launch()
|