File size: 27,502 Bytes
7e4fb15 0398d1e 7e4fb15 cb1dc3c 0398d1e cb1dc3c 0398d1e 7e4fb15 cb1dc3c 0398d1e cb1dc3c 0398d1e 7e4fb15 cb1dc3c 0398d1e cb1dc3c 0398d1e 7e4fb15 cb1dc3c 0398d1e cb1dc3c 0398d1e 7e4fb15 cb1dc3c 0398d1e cb1dc3c 0398d1e 7e4fb15 ecc2bb4 0398d1e 7e4fb15 0398d1e 7e4fb15 cb1dc3c 7e4fb15 0398d1e 7e4fb15 0398d1e cb1dc3c 0398d1e cb1dc3c 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 3564514 0398d1e 7e4fb15 0398d1e 7e4fb15 29ce347 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e ecc2bb4 7e4fb15 ecc2bb4 7e4fb15 0398d1e 7e4fb15 cb1dc3c 0398d1e 7e4fb15 0398d1e cb1dc3c 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 cb1dc3c 7e4fb15 0398d1e cb1dc3c 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e cb1dc3c 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 16c1e8a 0398d1e 16c1e8a 0398d1e 16c1e8a 0398d1e 7e4fb15 0398d1e 7e4fb15 16c1e8a 4fd4c0d 16c1e8a 4fd4c0d bad7e32 7e4fb15 4fd4c0d 7e4fb15 4fd4c0d 0398d1e 4fd4c0d 16c1e8a 0398d1e 16c1e8a 0398d1e 4fd4c0d 7e4fb15 4fd4c0d 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 7e4fb15 bad7e32 7e4fb15 0398d1e bad7e32 0398d1e 7e4fb15 0398d1e 7e4fb15 0398d1e 3564514 7e4fb15 29ce347 cb1dc3c 29ce347 0398d1e 29ce347 0398d1e 29ce347 0398d1e 29ce347 0398d1e 29ce347 0398d1e cb1dc3c 29ce347 7e4fb15 0398d1e 7e4fb15 0398d1e 4fd4c0d 29ce347 cb1dc3c 0398d1e ecc2bb4 0398d1e 29ce347 0398d1e 29ce347 0398d1e 29ce347 ecc2bb4 0398d1e ecc2bb4 29ce347 0398d1e cb1dc3c 0398d1e ecc2bb4 0398d1e ecc2bb4 0398d1e 29ce347 0398d1e 29ce347 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e 7e4fb15 bad7e32 29ce347 bad7e32 29ce347 bad7e32 29ce347 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 0398d1e bad7e32 29ce347 bad7e32 29ce347 0398d1e ecc2bb4 0398d1e ecc2bb4 0398d1e ecc2bb4 0398d1e |
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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 |
import os
import json
from typing import List, Dict, Tuple
import streamlit as st
import requests
# ์ ํ์ ์์กด์ฑ ๊ฐ๋
try:
import torch
TORCH_AVAILABLE = True
except ImportError:
TORCH_AVAILABLE = False
print("[WARNING] torch not available")
try:
from transformers import AutoTokenizer, AutoModel, AutoModelForMaskedLM
TRANSFORMERS_AVAILABLE = True
except ImportError:
TRANSFORMERS_AVAILABLE = False
print("[WARNING] transformers not available")
try:
from datasets import load_dataset
DATASETS_AVAILABLE = True
except ImportError:
DATASETS_AVAILABLE = False
print("[WARNING] datasets not available")
try:
from sentence_transformers import SentenceTransformer
SENTENCE_TRANSFORMERS_AVAILABLE = True
except ImportError:
SENTENCE_TRANSFORMERS_AVAILABLE = False
print("[WARNING] sentence_transformers not available")
try:
import faiss
FAISS_AVAILABLE = True
except ImportError:
FAISS_AVAILABLE = False
print("[WARNING] faiss not available")
try:
from Bio import SeqIO
BIOPYTHON_AVAILABLE = True
except ImportError:
BIOPYTHON_AVAILABLE = False
print("[WARNING] biopython not available")
# PDF ์ง์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
try:
import pdfplumber
PDFPLUMBER_AVAILABLE = True
except ImportError:
PDFPLUMBER_AVAILABLE = False
print("[WARNING] pdfplumber not available")
try:
import PyPDF2
PYPDF2_AVAILABLE = True
except ImportError:
PYPDF2_AVAILABLE = False
print("[WARNING] PyPDF2 not available")
# ์์
APP_TITLE = "BioSeq Chat: Protein & DNA Assistant"
DISCLAIMER = "This tool is for research/education and is not a medical device. Do not use outputs for diagnosis or treatment decisions."
# --------------- Helper Functions ---------------
def get_secret(name: str, fallback: str = "") -> str:
"""Get secret from st.secrets or environment"""
try:
# Streamlit secrets
if hasattr(st, 'secrets') and name in st.secrets:
return st.secrets[name]
except:
pass
# Environment variable
return os.environ.get(name, fallback)
def brave_search(query: str, count: int = 5) -> List[Dict]:
"""Brave Search API"""
key = get_secret("BRAVE_API_KEY", "")
if not key:
return [{
"title": "BRAVE_API_KEY missing",
"url": "",
"snippet": "Set BRAVE_API_KEY in Space secrets or sidebar"
}]
url = "https://api.search.brave.com/res/v1/web/search"
headers = {
"Accept": "application/json",
"X-Subscription-Token": key
}
params = {"q": query, "count": count}
try:
r = requests.get(url, headers=headers, params=params, timeout=15)
r.raise_for_status()
data = r.json()
results = []
for item in data.get("web", {}).get("results", [])[:count]:
results.append({
"title": item.get("title", ""),
"url": item.get("url", ""),
"snippet": item.get("description", "")
})
return results if results else [{"title": "No results", "url": "", "snippet": ""}]
except Exception as e:
return [{"title": "Error", "url": "", "snippet": str(e)}]
def call_llm(messages: List[Dict], temperature: float = 0.6, max_tokens: int = 4000) -> str:
"""Call Fireworks AI API"""
api_key = get_secret("FIREWORKS_API_KEY", "")
if not api_key:
return "FIREWORKS_API_KEY missing. Set it in Secrets or sidebar."
url = "https://api.fireworks.ai/inference/v1/chat/completions"
payload = {
"model": "accounts/fireworks/models/llama-v3p1-70b-instruct",
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
try:
r = requests.post(url, headers=headers, json=payload, timeout=60)
r.raise_for_status()
return r.json()["choices"][0]["message"]["content"]
except Exception as e:
return f"[LLM Error] {e}"
def load_file_text(upload) -> str:
"""Load text from uploaded file (PDF ์ง์ ํฌํจ)"""
name = upload.name.lower()
# PDF ์ฒ๋ฆฌ
if name.endswith(".pdf"):
if PDFPLUMBER_AVAILABLE:
try:
text_parts = []
with pdfplumber.open(upload) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text_parts.append(page_text)
return "\n\n".join(text_parts)
except Exception as e:
st.error(f"PDF ์ฝ๊ธฐ ์ค๋ฅ (pdfplumber): {e}")
return ""
elif PYPDF2_AVAILABLE:
try:
upload.seek(0)
pdf_reader = PyPDF2.PdfReader(upload)
text_parts = []
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
text_parts.append(page.extract_text())
return "\n\n".join(text_parts)
except Exception as e:
st.error(f"PDF ์ฝ๊ธฐ ์ค๋ฅ (PyPDF2): {e}")
return ""
else:
st.error("PDF ํ์ผ์ ์ฝ์ผ๋ ค๋ฉด pdfplumber ๋๋ PyPDF2๊ฐ ํ์ํฉ๋๋ค")
return ""
# ๊ธฐ์กด ํ
์คํธ ํ์ผ ์ฒ๋ฆฌ
try:
content = upload.read()
text = content.decode("utf-8", errors="ignore")
except:
return ""
# FASTA handling
if name.endswith((".fa", ".fasta", ".faa", ".fna")) and BIOPYTHON_AVAILABLE:
try:
upload.seek(0)
records = list(SeqIO.parse(upload, "fasta"))
seqs = [f">{r.id}\n{str(r.seq)}" for r in records]
return "\n\n".join(seqs)
except:
pass
return text
def chunk_text(text: str, size: int = 1200, overlap: int = 200) -> List[str]:
"""Split text into chunks"""
chunks = []
start = 0
text_len = len(text)
while start < text_len:
end = min(start + size, text_len)
chunks.append(text[start:end])
if end >= text_len:
break
start = end - overlap
return chunks
def build_index(texts: List[str]):
"""Build vector index"""
if not SENTENCE_TRANSFORMERS_AVAILABLE or not FAISS_AVAILABLE:
return None, None
try:
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
embeddings = model.encode(texts, show_progress_bar=False)
dim = embeddings.shape[1]
index = faiss.IndexFlatIP(dim)
index.add(embeddings.astype("float32"))
return index, model
except Exception as e:
st.warning(f"Index build failed: {e}")
return None, None
def search_index(query: str, index, model, texts: List[str], k: int = 4) -> List[Dict]:
"""Search vector index"""
if index is None or model is None:
return []
try:
q_emb = model.encode([query])
D, I = index.search(q_emb.astype("float32"), k)
results = []
for idx, score in zip(I[0], D[0]):
if 0 <= idx < len(texts):
results.append({
"score": float(score),
"text": texts[idx]
})
return results
except:
return []
def esm2_embed(seq: str, model_name: str = "facebook/esm2_t6_8M_UR50D") -> Dict:
"""ESM-2 protein embedding"""
if not TORCH_AVAILABLE or not TRANSFORMERS_AVAILABLE:
return {"error": "PyTorch/Transformers not available"}
try:
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForMaskedLM.from_pretrained(model_name)
model.eval()
with torch.no_grad():
inputs = tokenizer(seq, return_tensors="pt", truncation=True, max_length=1024)
outputs = model(**inputs, output_hidden_states=True)
hidden = outputs.hidden_states[-1].mean(dim=1).squeeze(0)
vec = hidden.cpu().numpy()
# ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
del model
del tokenizer
if torch.cuda.is_available():
torch.cuda.empty_cache()
return {
"embedding": vec.tolist()[:10], # ๋ฏธ๋ฆฌ๋ณด๊ธฐ์ฉ ์ฒซ 10๊ฐ๋ง
"size": vec.shape[0]
}
except Exception as e:
return {"error": str(e)}
def dna_embed(seq: str, model_name: str = "zhihan1996/DNABERT-2-117M") -> Dict:
"""DNA embedding"""
if not TORCH_AVAILABLE or not TRANSFORMERS_AVAILABLE:
return {"error": "PyTorch/Transformers not available"}
try:
# einops ์ฒดํฌ
try:
import einops
except ImportError:
return {"error": "einops package required. Please wait for installation and refresh the page."}
# ๊ฐ๋จํ ๋์: ๋ ์์ ์ ์ธ ๋ชจ๋ธ ์ฌ์ฉ
# DNABERT-2๊ฐ ๋ฌธ์ ๋ฅผ ์ผ์ผํค๋ฉด ๊ธฐ๋ณธ BERT ์ฌ์ฉ
try:
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
except Exception as model_error:
# ๋์ฒด ๋ชจ๋ธ ์ฌ์ฉ
try:
from transformers import BertTokenizer, BertModel
# ๊ธฐ๋ณธ BERT ๋ชจ๋ธ๋ก ํด๋ฐฑ
fallback_model = "bert-base-uncased"
tokenizer = BertTokenizer.from_pretrained(fallback_model)
model = BertModel.from_pretrained(fallback_model)
st.warning(f"DNABERT-2 ๋ก๋ฉ ์คํจ. ๋์ฒด ๋ชจ๋ธ ์ฌ์ฉ์ค: {fallback_model}")
except:
return {"error": f"๋ชจ๋ธ ๋ก๋ฉ ์คํจ: {str(model_error)}"}
model.eval()
# DNA ์์ด์ k-mer๋ก ๋ณํ (DNABERT ์คํ์ผ)
def seq_to_kmer(seq, k=6):
"""DNA ์์ด์ k-mer๋ก ๋ณํ"""
kmers = []
for i in range(len(seq) - k + 1):
kmers.append(seq[i:i+k])
return ' '.join(kmers)
# k-mer ๋ณํ ๋๋ ์ง์ ์ฌ์ฉ
if len(seq) > 6:
input_seq = seq_to_kmer(seq, k=6)
else:
input_seq = seq
with torch.no_grad():
inputs = tokenizer(
input_seq,
return_tensors="pt",
truncation=True,
max_length=512,
padding=True
)
outputs = model(**inputs)
# last_hidden_state ๋๋ pooler_output ์ฌ์ฉ
if hasattr(outputs, 'pooler_output') and outputs.pooler_output is not None:
vec = outputs.pooler_output.squeeze(0).cpu().numpy()
else:
hidden = outputs.last_hidden_state.mean(dim=1).squeeze(0)
vec = hidden.cpu().numpy()
# ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
del model
del tokenizer
if torch.cuda.is_available():
torch.cuda.empty_cache()
return {
"embedding": vec.tolist()[:10], # ๋ฏธ๋ฆฌ๋ณด๊ธฐ์ฉ ์ฒซ 10๊ฐ๋ง
"size": vec.shape[0]
}
except Exception as e:
return {"error": f"๋ถ์ ์ค ์ค๋ฅ ๋ฐ์: {str(e)[:200]}"}
def build_context(query: str, docs: List[str], index, model, use_web: bool, web_k: int) -> Tuple[str, List[Dict]]:
"""Build context from sources"""
pieces = []
sources = []
# File search
if index and model and docs:
hits = search_index(query, index, model, docs, k=4)
for h in hits:
pieces.append(f"[FILE] {h['text'][:500]}")
sources.append({"type": "file", "text": h['text'][:100]})
# Web search
if use_web:
results = brave_search(query, count=web_k)
for r in results:
pieces.append(f"[WEB] {r['title']}\n{r['snippet']}")
sources.append({"type": "web", "title": r['title'], "url": r['url']})
context = "\n\n---\n\n".join(pieces)[:4000]
return context, sources
def answer_question(query: str, context: str) -> str:
"""Generate answer"""
system = (
"You are an expert bioinformatics assistant who explains complex biological concepts in an accessible way. "
"Your responses should be:\n"
"1. Comprehensive yet easy to understand\n"
"2. Well-structured with clear sections\n"
"3. Include relevant examples and analogies\n"
"4. Provide actionable insights when appropriate\n"
"5. Use Korean if the user writes in Korean, otherwise English\n"
"6. Never provide medical diagnosis or treatment advice\n"
"7. Format your response with headers, bullet points, and clear paragraphs\n"
"8. Aim for 300-500 words minimum for complex questions"
)
user_msg = f"""Context information:\n{context}\n\n
User Question: {query}
Please provide a detailed, well-structured response that:
- Directly answers the question
- Explains the biological background
- Includes practical implications when relevant
- Uses simple analogies to explain complex concepts
- Cites the context when appropriate"""
messages = [
{"role": "system", "content": system},
{"role": "user", "content": user_msg}
]
return call_llm(messages, temperature=0.4, max_tokens=4000)
# --------------- Streamlit UI ---------------
st.set_page_config(page_title=APP_TITLE, page_icon="๐งฌ", layout="wide")
st.title(APP_TITLE)
st.caption(DISCLAIMER)
# Session state init
if "docs" not in st.session_state:
st.session_state.docs = []
if "index" not in st.session_state:
st.session_state.index = None
if "model" not in st.session_state:
st.session_state.model = None
# Sidebar
with st.sidebar:
st.header("Configuration")
fw_key = st.text_input(
"FIREWORKS_API_KEY",
value=get_secret("FIREWORKS_API_KEY", ""),
type="password"
)
brave_key = st.text_input(
"BRAVE_API_KEY",
value=get_secret("BRAVE_API_KEY", ""),
type="password"
)
if fw_key:
os.environ["FIREWORKS_API_KEY"] = fw_key
if brave_key:
os.environ["BRAVE_API_KEY"] = brave_key
st.divider()
esm_model = st.text_input(
"ESM-2 Model",
value="facebook/esm2_t6_8M_UR50D"
)
dna_model = st.text_input(
"DNA Model",
value="bert-base-uncased", # ๋ ์์ ์ ์ธ ๊ธฐ๋ณธ ๋ชจ๋ธ
help="Options: bert-base-uncased (stable), zhihan1996/DNABERT-2-117M (specialized but may require more memory)"
)
use_web = st.checkbox("Enable web search", value=True)
web_results = st.slider("Web results", 1, 10, 3)
# Tabs
tab1, tab2, tab3, tab4 = st.tabs(["Chat", "Protein", "DNA", "About"])
# File upload
with st.expander("๐ Upload Files", expanded=True):
files = st.file_uploader(
"Upload text/FASTA/PDF files", # PDF ์ถ๊ฐ
type=["txt", "fa", "fasta", "csv", "json", "pdf"], # PDF ์ถ๊ฐ
accept_multiple_files=True
)
if files:
docs = []
for f in files:
try:
# PDF ํ์ผ์ธ ๊ฒฝ์ฐ ๊ฒฝ๊ณ ๋ฉ์์ง ์ถ๊ฐ
if f.name.lower().endswith(".pdf"):
if not (PDFPLUMBER_AVAILABLE or PYPDF2_AVAILABLE):
st.warning(f"โ ๏ธ PDF ์ง์์ ์ํด pdfplumber ์ค์น ํ์: pip install pdfplumber")
continue
text = load_file_text(f)
if text:
docs.extend(chunk_text(text))
st.success(f"โ
{f.name} ๋ก๋ ์๋ฃ")
except Exception as e:
st.error(f"Error reading {f.name}: {e}")
if docs:
st.session_state.docs = docs
st.success(f"์ด {len(docs)}๊ฐ ์ฒญํฌ ์์ฑ ์๋ฃ")
if SENTENCE_TRANSFORMERS_AVAILABLE and FAISS_AVAILABLE:
with st.spinner("์ธ๋ฑ์ค ๊ตฌ์ถ ์ค..."):
index, model = build_index(docs)
if index:
st.session_state.index = index
st.session_state.model = model
# Chat tab
with tab1:
st.subheader("๐ฌ Chat Assistant")
question = st.text_area(
"Ask about proteins, DNA, or bioinformatics:",
value="What is the role of ESM-2 embeddings in protein analysis?",
height=100
)
if st.button("Get Answer", type="primary"):
if not get_secret("FIREWORKS_API_KEY"):
st.error("Please set FIREWORKS_API_KEY")
else:
with st.spinner("Thinking..."):
context, sources = build_context(
question,
st.session_state.docs,
st.session_state.index,
st.session_state.model,
use_web,
web_results
)
answer = answer_question(question, context)
st.markdown("### Answer")
st.write(answer)
if sources:
st.markdown("### Sources")
for s in sources:
if s["type"] == "web":
st.write(f"- ๐ [{s['title']}]({s['url']})")
elif s["type"] == "file":
st.write(f"- ๐ File: {s['text'][:80]}...")
# Protein tab
with tab2:
st.subheader("๐งฌ Protein Analysis")
st.info("""
**๋จ๋ฐฑ์ง ์์ด ๋ถ์์ด๋?**
- ๋จ๋ฐฑ์ง์ ์๋ฏธ๋
ธ์ฐ ์์ด์ AI๊ฐ ๋ถ์ํ์ฌ ๊ธฐ๋ฅ๊ณผ ๊ตฌ์กฐ๋ฅผ ์์ธกํฉ๋๋ค
- ESM-2๋ Meta๊ฐ ๊ฐ๋ฐํ AI๋ก, 6์ต 5์ฒ๋ง๊ฐ ๋จ๋ฐฑ์ง์ ํ์ตํ์ต๋๋ค
- ์ฉ๋: ์ ์ฝ ๊ฐ๋ฐ, ์ง๋ณ ์ฐ๊ตฌ, ์งํ ๋ถ์ ๋ฑ
""")
protein_seq = st.text_area(
"๋จ๋ฐฑ์ง ์์ด ์
๋ ฅ (๋ณต์ฌ-๋ถ์ฌ๋ฃ๊ธฐ ๊ฐ๋ฅ):",
value="MKTIIALSYIFCLVFA",
help="๋จ๋ฐฑ์ง ์์ด์ 20๊ฐ ์๋ฏธ๋
ธ์ฐ ๋ฌธ์(A,C,D,E,F,G,H,I,K,L,M,N,P,Q,R,S,T,V,W,Y)๋ก ๊ตฌ์ฑ๋ฉ๋๋ค",
height=100
)
st.markdown("**์์ ์์ด (ํด๋ฆญํด์ ๋ณต์ฌ):**")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("์ธ์๋ฆฐ", key="ins"):
st.code("FVNQHLCGSHLVEALYLVCGERGFFYTPKT", language=None)
with col2:
if st.button("์๋ํ", key="end"):
st.code("YGGFMTSEKSQTPLVTLFKNAIIKNAYKKGE", language=None)
with col3:
if st.button("์ฅ์ํ ์ ", key="oxy"):
st.code("CYIQNCPLG", language=None)
if st.button("๐ฌ ๋จ๋ฐฑ์ง ๋ถ์ ์์", type="primary"):
seq = protein_seq.strip().upper()
# Basic stats
st.markdown("### ๐ ๊ธฐ๋ณธ ๋ถ์ ๊ฒฐ๊ณผ")
col1, col2 = st.columns(2)
with col1:
st.metric("์์ด ๊ธธ์ด", f"{len(seq)} ์๋ฏธ๋
ธ์ฐ")
st.metric("๋ถ์๋ (์ถ์ )", f"~{len(seq) * 110} Da")
with col2:
unique_aa = len(set(seq))
st.metric("์ฌ์ฉ๋ ์๋ฏธ๋
ธ์ฐ ์ข
๋ฅ", f"{unique_aa}๊ฐ")
hydrophobic = sum(1 for aa in seq if aa in "AVILMFYW")
st.metric("์์์ฑ ๋น์จ", f"{hydrophobic/len(seq)*100:.1f}%")
# AI Analysis
if TORCH_AVAILABLE and TRANSFORMERS_AVAILABLE:
st.markdown("### ๐ค AI ์๋ฒ ๋ฉ ๋ถ์")
with st.spinner("AI ๋ชจ๋ธ์ด ๋จ๋ฐฑ์ง์ ๋ถ์์ค... (10-30์ด)"):
result = esm2_embed(seq, esm_model)
if "error" in result:
st.error(result["error"])
else:
st.success("โ
AI ๋ถ์ ์๋ฃ!")
col1, col2 = st.columns(2)
with col1:
st.metric("๋ฒกํฐ ์ฐจ์", result['size'])
st.caption("์ด ์ซ์๋ค์ ๋จ๋ฐฑ์ง์ ํน์ฑ์ ์์นํํ ๊ฒ์
๋๋ค")
with col2:
st.markdown("**์๋ฒ ๋ฉ ๋ฒกํฐ ๋ฏธ๋ฆฌ๋ณด๊ธฐ:**")
st.code(result["embedding"][:5])
st.markdown("""
**๐ฏ ์ด ๋ถ์์ ํ์ฉ:**
- ์ ์ฌํ ๊ธฐ๋ฅ์ ๋จ๋ฐฑ์ง ์ฐพ๊ธฐ
- ๊ตฌ์กฐ ์์ธก์ ๊ธฐ์ด ๋ฐ์ดํฐ
- ๋์ฐ๋ณ์ด ์ํฅ ์์ธก
- ์ ์ฝ ํ๊ฒ ๋ฐ๊ตด
""")
else:
st.warning("โ ๏ธ AI ๋ชจ๋ธ ๋ก๋ฉ ์ค... ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์")
# DNA tab
with tab3:
st.subheader("๐งฌ DNA Analysis")
st.info("""
**DNA ์์ด ๋ถ์์ด๋?**
- DNA์ ์ผ๊ธฐ์์ด(A,T,G,C)์ AI๊ฐ ๋ถ์ํ์ฌ ๊ธฐ๋ฅ์ ์์ธกํฉ๋๋ค
- DNABERT-2๋ ์ธ๊ฐ ๊ฒ๋ ์ ์ฒด๋ฅผ ํ์ตํ AI ๋ชจ๋ธ์
๋๋ค
- ์ฉ๋: ์ ์ ์ ๊ธฐ๋ฅ ์์ธก, ์ง๋ณ ๋ณ์ด ๋ฐ๊ฒฌ, ์งํ ์ฐ๊ตฌ ๋ฑ
""")
dna_seq = st.text_area(
"DNA ์์ด ์
๋ ฅ (๋ณต์ฌ-๋ถ์ฌ๋ฃ๊ธฐ ๊ฐ๋ฅ):",
value="ATGCGATCGTAGC",
help="DNA๋ 4๊ฐ ์ผ๊ธฐ(A: ์๋ฐ๋, T: ํฐ๋ฏผ, G: ๊ตฌ์๋, C: ์ํ ์ )๋ก ๊ตฌ์ฑ๋ฉ๋๋ค",
height=100
)
st.markdown("**์์ ์์ด (ํด๋ฆญํด์ ๋ณต์ฌ):**")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("TATA ๋ฐ์ค", key="tata"):
st.code("GCGCGATATAAAGGCGCGGGCGCGCG", language=None)
st.caption("์ ์ ์ ๋ฐํ ์์ ์ ํธ")
with col2:
if st.button("ํ๋ก๋ชจํฐ", key="prom"):
st.code("TTGACAGGCTAGCTCAGTCCTAGGTATAATGCTAGC", language=None)
st.caption("์ ์ ์ ์กฐ์ ์์ญ")
with col3:
if st.button("CRISPR ํ๊ฒ", key="crispr"):
st.code("GTCACCTCCAATGACTAGGGTGG", language=None)
st.caption("์ ์ ์ ํธ์ง ๋ถ์")
if st.button("๐ฌ DNA ๋ถ์ ์์", type="primary"):
seq = dna_seq.strip().upper().replace("U", "T") # RNA์ U๋ฅผ T๋ก ๋ณํ
seq = ''.join(c for c in seq if c in 'ATGC') # ATGC๋ง ๋จ๊ธฐ๊ธฐ
if len(seq) < 3:
st.error("์ต์ 3๊ฐ ์ด์์ ์ผ๊ธฐ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์")
else:
st.markdown("### ๐ ๊ธฐ๋ณธ ๋ถ์ ๊ฒฐ๊ณผ")
col1, col2 = st.columns(2)
with col1:
st.metric("์์ด ๊ธธ์ด", f"{len(seq)} bp")
gc = (seq.count("G") + seq.count("C")) / len(seq) * 100
st.metric("GC ํจ๋", f"{gc:.1f}%")
if gc > 60:
st.caption("๐ด ๋์: ์์ ์ ์ด์ง๋ง ๋ณต์ ์ด๋ ค์")
elif gc < 40:
st.caption("๐ต ๋ฎ์: ๋ถ์์ ํ์ง๋ง ๋ณต์ ์ฉ์ด")
else:
st.caption("๐ข ์ ์ : ์ผ๋ฐ์ ์ธ ๋ฒ์")
with col2:
at = (seq.count("A") + seq.count("T")) / len(seq) * 100
st.metric("AT ํจ๋", f"{at:.1f}%")
# ์ฝ๋ ๋ถ์ (3์ ๋ฐฐ์์ธ ๊ฒฝ์ฐ)
if len(seq) % 3 == 0:
st.metric("๊ฐ๋ฅํ ์ฝ๋ ์", f"{len(seq)//3}๊ฐ")
st.caption("๋จ๋ฐฑ์ง๋ก ๋ฒ์ญ ๊ฐ๋ฅ")
# ํน๋ณ ์์ด ์ฐพ๊ธฐ
st.markdown("### ๐ ์ฃผ์ ๋ชจํฐํ ๊ฒ์")
motifs_found = []
if "TATAAAA" in seq or "TATAAA" in seq:
motifs_found.append("โ
TATA box ๋ฐ๊ฒฌ (์ ์ฌ ์์ ์ ํธ)")
if "CAAT" in seq or "CCAAT" in seq:
motifs_found.append("โ
CAAT box ๋ฐ๊ฒฌ (์ ์ฌ ์กฐ์ )")
if "ATG" in seq:
motifs_found.append("โ
์์ ์ฝ๋(ATG) ๋ฐ๊ฒฌ")
if "TAA" in seq or "TAG" in seq or "TGA" in seq:
motifs_found.append("โ
์ ์ง ์ฝ๋ ๋ฐ๊ฒฌ")
if seq.count("CG") > len(seq)/20:
motifs_found.append("โ
CpG ์ฌ ๊ฐ๋ฅ์ฑ (์ ์ ์ ์กฐ์ )")
if motifs_found:
for motif in motifs_found:
st.write(motif)
else:
st.write("ํน๋ณํ ๋ชจํฐํ๊ฐ ๋ฐ๊ฒฌ๋์ง ์์์ต๋๋ค")
# AI Analysis
if TORCH_AVAILABLE and TRANSFORMERS_AVAILABLE:
st.markdown("### ๐ค AI ์๋ฒ ๋ฉ ๋ถ์")
with st.spinner("AI ๋ชจ๋ธ์ด DNA๋ฅผ ๋ถ์์ค... (10-30์ด)"):
result = dna_embed(seq, dna_model)
if "error" in result:
st.error(result["error"])
else:
st.success("โ
AI ๋ถ์ ์๋ฃ!")
col1, col2 = st.columns(2)
with col1:
st.metric("๋ฒกํฐ ์ฐจ์", result['size'])
st.caption("DNA ํน์ฑ์ ์์นํํ ๊ฒฐ๊ณผ์
๋๋ค")
with col2:
st.markdown("**์๋ฒ ๋ฉ ๋ฒกํฐ ๋ฏธ๋ฆฌ๋ณด๊ธฐ:**")
st.code(result["embedding"][:5])
st.markdown("""
**๐ฏ ์ด ๋ถ์์ ํ์ฉ:**
- ์ ์ ์ ๊ธฐ๋ฅ ์์ธก
- ํ๋ก๋ชจํฐ/์ธํธ์ ์ฐพ๊ธฐ
- ์งํ์ ๋ณด์กด ์์ญ ๋ฐ๊ฒฌ
- ์ง๋ณ ๊ด๋ จ ๋ณ์ด ์์ธก
- CRISPR ํ๊ฒ ๋ถ์ ํ๊ฐ
""")
else:
st.warning("โ ๏ธ AI ๋ชจ๋ธ ๋ก๋ฉ ์ค... ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์")
# About tab
with tab4:
st.subheader("โน๏ธ About")
st.markdown("""
### Features
- ๐ฌ RAG-based chat for bioinformatics questions
- ๐งฌ Protein sequence analysis with ESM-2
- ๐งฌ DNA sequence analysis with DNABERT-2
- ๐ Web search integration via Brave API
- ๐ File upload and vector search (including PDF support)
### Models
- **Proteins:** ESM-2 (Facebook)
- **DNA:** DNABERT-2 (Microsoft) / BERT (fallback)
- **LLM:** Llama 3.1 70B (via Fireworks)
### Disclaimer
This tool is for research and educational purposes only.
Not for medical diagnosis or treatment decisions.
""")
# Dependency check
st.divider()
st.subheader("System Status")
deps = {
"PyTorch": TORCH_AVAILABLE,
"Transformers": TRANSFORMERS_AVAILABLE,
"Sentence Transformers": SENTENCE_TRANSFORMERS_AVAILABLE,
"FAISS": FAISS_AVAILABLE,
"BioPython": BIOPYTHON_AVAILABLE,
"Datasets": DATASETS_AVAILABLE,
"PDF Support (pdfplumber)": PDFPLUMBER_AVAILABLE, # PDF ์ง์ ์ถ๊ฐ
"PDF Support (PyPDF2)": PYPDF2_AVAILABLE # PDF ์ง์ ์ถ๊ฐ
}
for name, available in deps.items():
if available:
st.success(f"โ
{name}")
else:
st.warning(f"โ ๏ธ {name} not available") |