Sepideh2027 commited on
Commit
71c307e
·
verified ·
1 Parent(s): 2c54f3b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -0
app.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ================================================================
2
+ # 🧬 PathogenAgent: Agentic AI for Pathogen Genomic Analysis
3
+ # Hugging Face Space – Gradio + LangChain + BioGPT
4
+ # ================================================================
5
+
6
+ import gradio as gr
7
+ import requests
8
+ import json
9
+ import re
10
+ from Bio import Entrez, SeqIO
11
+ from io import StringIO
12
+ import torch
13
+ from transformers import AutoTokenizer, AutoModelForCausalLM
14
+
15
+ # ================================================================
16
+ # 1. تنظیمات
17
+ # ================================================================
18
+
19
+ Entrez.email = "public@example.com"
20
+ Entrez.tool = "PathogenAgent"
21
+
22
+ # بارگذاری BioGPT (مدل شما یا مدل پایه)
23
+ MODEL_NAME = "Sepideh2027/biogpt-clinvar-finetuned" # یا "microsoft/biogpt"
24
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
25
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
26
+ model.eval()
27
+
28
+ if torch.cuda.is_available():
29
+ model = model.to("cuda")
30
+
31
+ # ================================================================
32
+ # 2. ابزارها (Tools)
33
+ # ================================================================
34
+
35
+ def search_pubmed(query):
36
+ """جستجوی PubMed"""
37
+ try:
38
+ url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
39
+ params = {"db": "pubmed", "term": query, "retmax": 3, "retmode": "json"}
40
+ resp = requests.get(url, params=params, timeout=10)
41
+ ids = resp.json().get("esearchresult", {}).get("idlist", [])
42
+ if not ids:
43
+ return "No articles found."
44
+
45
+ url2 = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi"
46
+ params2 = {"db": "pubmed", "id": ",".join(ids[:3]), "retmode": "json"}
47
+ resp2 = requests.get(url2, params=params2, timeout=10)
48
+ results = []
49
+ for uid, rec in resp2.json().get("result", {}).items():
50
+ if uid == "uids": continue
51
+ results.append(f"- {rec.get('title', 'No title')}")
52
+ return "📄 **PubMed Articles:**\n" + "\n".join(results)
53
+ except Exception as e:
54
+ return f"Error: {str(e)}"
55
+
56
+ def search_genbank(organism):
57
+ """دریافت توالی ژنومی از GenBank"""
58
+ try:
59
+ handle = Entrez.esearch(db="nucleotide", term=f"{organism}[Organism] AND complete genome", retmax=1)
60
+ record = Entrez.read(handle)
61
+ handle.close()
62
+ if not record["IdList"]:
63
+ return f"No sequence found for '{organism}'."
64
+ seq_id = record["IdList"][0]
65
+ handle = Entrez.efetch(db="nucleotide", id=seq_id, rettype="fasta", retmode="text")
66
+ seq_data = handle.read()
67
+ handle.close()
68
+ seq = SeqIO.read(StringIO(seq_data), "fasta")
69
+ return f"🧬 **GenBank:**\n- {organism}\n- Length: {len(seq.seq):,} bp\n- {str(seq.seq[:200])}..."
70
+ except Exception as e:
71
+ return f"Error: {str(e)}"
72
+
73
+ def search_clinvar(variant):
74
+ """دریافت اطلاعات بالینی از ClinVar"""
75
+ try:
76
+ url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
77
+ params = {"db": "clinvar", "term": variant, "retmax": 2, "retmode": "json"}
78
+ resp = requests.get(url, params=params, timeout=10)
79
+ ids = resp.json().get("esearchresult", {}).get("idlist", [])
80
+ if not ids:
81
+ return f"No ClinVar records for '{variant}'."
82
+ url2 = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi"
83
+ params2 = {"db": "clinvar", "id": ",".join(ids[:2]), "retmode": "json"}
84
+ resp2 = requests.get(url2, params=params2, timeout=10)
85
+ results = []
86
+ for uid, rec in resp2.json().get("result", {}).items():
87
+ if uid == "uids": continue
88
+ sig = rec.get("clinicalsignificance", [{}])[0].get("description", "Unknown")
89
+ results.append(f"- {rec.get('title', '')} → **{sig}**")
90
+ return "🧬 **ClinVar:**\n" + "\n".join(results)
91
+ except Exception as e:
92
+ return f"Error: {str(e)}"
93
+
94
+ # ================================================================
95
+ # 3. Agent Planner (ساده اما هوشمند)
96
+ # ================================================================
97
+
98
+ def pathogen_agent(query):
99
+ """
100
+ Agent اصلی که بر اساس سوال کاربر تصمیم می‌گیرد از کدام ابزارها استفاده کند
101
+ """
102
+ query_lower = query.lower()
103
+
104
+ # تصمیم‌گیری ساده بر اساس کلمات کلیدی
105
+ if "pubmed" in query_lower or "article" in query_lower or "paper" in query_lower:
106
+ return search_pubmed(query)
107
+
108
+ elif "genbank" in query_lower or "genome" in query_lower or "sequence" in query_lower:
109
+ # استخراج نام موجودیت
110
+ words = query.split()
111
+ organism = " ".join(words[-2:]) if len(words) > 2 else query
112
+ return search_genbank(organism)
113
+
114
+ elif "clinvar" in query_lower or "variant" in query_lower or "mutation" in query_lower:
115
+ # استخراج نام واریانت
116
+ return search_clinvar(query)
117
+
118
+ else:
119
+ # ترکیب چند ابزار
120
+ pubmed_result = search_pubmed(query)
121
+ genbank_result = search_genbank(query)
122
+ clinvar_result = search_clinvar(query)
123
+
124
+ # خلاصه‌سازی با BioGPT
125
+ summary = f"""
126
+ **Query:** {query}
127
+
128
+ **PubMed Summary:**
129
+ {pubmed_result}
130
+
131
+ **GenBank Summary:**
132
+ {genbank_result}
133
+
134
+ **ClinVar Summary:**
135
+ {clinvar_result}
136
+
137
+ ---
138
+ **Generated by PathogenAgent v1.0**
139
+ """
140
+
141
+ return summary
142
+
143
+ # ================================================================
144
+ # 4. BioGPT برای تفسیر نهایی (اختیاری)
145
+ # ================================================================
146
+
147
+ def interpret_with_biogpt(text):
148
+ """خلاصه‌سازی نهایی با BioGPT"""
149
+ prompt = f"Summarize the following genomic information:\n{text}\nSummary:"
150
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
151
+ if torch.cuda.is_available():
152
+ inputs = {k: v.to("cuda") for k, v in inputs.items()}
153
+ with torch.no_grad():
154
+ outputs = model.generate(**inputs, max_new_tokens=150, temperature=0.3)
155
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
156
+
157
+ # ================================================================
158
+ # 5. رابط کاربری Gradio
159
+ # ================================================================
160
+
161
+ def process_query(query):
162
+ if not query.strip():
163
+ return "⚠️ Please enter a pathogen name, gene, or variant."
164
+
165
+ # اجرای Agent
166
+ result = pathogen_agent(query)
167
+
168
+ # استفاده از BioGPT برای خلاصه‌سازی (اختیاری)
169
+ if len(result) > 500:
170
+ summary = interpret_with_biogpt(result)
171
+ return f"{result}\n\n---\n**🧠 AI Summary:**\n{summary}"
172
+
173
+ return result
174
+
175
+ # رابط Gradio
176
+ with gr.Blocks(title="PathogenAgent - Agentic AI for Genomics", theme=gr.themes.Soft()) as demo:
177
+ gr.Markdown("""
178
+ # 🧬 PathogenAgent: Agentic AI for Pathogen Genomic Analysis
179
+
180
+ **Ask about any pathogen, gene, or variant.**
181
+ The agent will search PubMed, GenBank, and ClinVar to provide a comprehensive report.
182
+
183
+ ---
184
+ """)
185
+
186
+ with gr.Row():
187
+ with gr.Column(scale=4):
188
+ query_input = gr.Textbox(
189
+ label="🔬 Enter your query",
190
+ placeholder="e.g., SARS-CoV-2 spike protein mutations",
191
+ lines=2
192
+ )
193
+ submit_btn = gr.Button("🚀 Analyze", variant="primary")
194
+
195
+ with gr.Column(scale=6):
196
+ output = gr.Markdown(label="📊 Report")
197
+
198
+ submit_btn.click(
199
+ fn=process_query,
200
+ inputs=query_input,
201
+ outputs=output
202
+ )
203
+
204
+ gr.Markdown("""
205
+ ---
206
+ ### 📌 Examples
207
+ - `SARS-CoV-2 genome`
208
+ - `BRCA1 c.68_69delAG`
209
+ - `Ebola virus recent outbreaks`
210
+ - `TP53 R175H`
211
+ """)
212
+
213
+ demo.launch()