diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,1258 +1,1614 @@ -import { useState, useEffect, useRef, useCallback } from "react"; - -// ─── CONSTANTS ──────────────────────────────────────────────────────────────── -const GROQ_MODELS = [ - { id: "llama-3.1-8b-instant", label: "Llama 3.1 8B (Fast)" }, - { id: "llama-3.3-70b-versatile", label: "Llama 3.3 70B (Smart)" }, - { id: "mixtral-8x7b-32768", label: "Mixtral 8x7B" }, - { id: "gemma2-9b-it", label: "Gemma2 9B" }, -]; - -// ─── API HELPERS ────────────────────────────────────────────────────────────── -const API = { - async fetchPDB(id) { - const r = await fetch(`https://files.rcsb.org/download/${id.toUpperCase()}.pdb`); - if (!r.ok) throw new Error("PDB not found"); - return r.text(); - }, - async fetchPDBMeta(id) { - const r = await fetch(`https://data.rcsb.org/rest/v1/core/entry/${id.toUpperCase()}`); - if (!r.ok) return null; - return r.json(); - }, - async searchPDB(query) { - const body = { - query: { type: "terminal", service: "full_text", parameters: { value: query } }, - return_type: "entry", - request_options: { paginate: { start: 0, rows: 8 } }, - }; - const r = await fetch("https://search.rcsb.org/rcsbsearch/v2/query", { - method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), - }); - if (!r.ok) return []; - const d = await r.json(); - return d.result_set || []; - }, - async fetchAlphaFold(uid) { - const r = await fetch(`https://alphafold.ebi.ac.uk/api/prediction/${uid}`); - if (!r.ok) throw new Error("UniProt ID not found in AlphaFold"); - const d = await r.json(); - if (!d.length) throw new Error("No prediction available"); - return d[0]; - }, - async fetchAlphaFoldPDB(url) { - const r = await fetch(url); - if (!r.ok) throw new Error("Failed to download AlphaFold PDB"); - return r.text(); - }, - async searchPubChem(query, type = "name") { - const enc = encodeURIComponent(query); - const r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/${type}/${enc}/JSON`); - if (!r.ok) throw new Error("Compound not found"); - const d = await r.json(); - return d.PC_Compounds || []; - }, - async getPubChemProps(cid) { - const props = "MolecularFormula,MolecularWeight,CanonicalSMILES,InChIKey,XLogP,TPSA,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount,Complexity,Charge"; - const r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/property/${props}/JSON`); - if (!r.ok) throw new Error("Properties not found"); - const d = await r.json(); - return d.PropertyTable?.Properties?.[0] || null; - }, - async getPubChemSDF(cid) { - // Try 3D first, then 2D - let r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/SDF?record_type=3d`); - if (!r.ok) r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/SDF`); - if (!r.ok) throw new Error("SDF not found"); - return r.text(); - }, - async iupacToSMILES(name) { - const r = await fetch(`https://cactus.nci.nih.gov/chemical/structure/${encodeURIComponent(name)}/smiles`); - if (!r.ok) throw new Error("IUPAC conversion failed"); - return (await r.text()).trim(); - }, - async smilesToCID(smiles) { - const r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/${encodeURIComponent(smiles)}/cids/JSON`); - if (!r.ok) throw new Error("SMILES lookup failed"); - const d = await r.json(); - return d.IdentifierList?.CID?.[0] || null; - }, - async callGroq(apiKey, model, messages, maxTokens = 1200) { - const r = await fetch("https://api.groq.com/openai/v1/chat/completions", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` }, - body: JSON.stringify({ model, messages, max_tokens: maxTokens, temperature: 0.7 }), - }); - if (!r.ok) { - const err = await r.json().catch(() => ({})); - throw new Error(err.error?.message || `HTTP ${r.status}`); +# ============================================================ +# QTL-Mapper v3 — Composite Interval Mapping (CIM) + Fixed Flanking +# +# KEY FIXES: +# 1. REPLACED Random Forest QTL mapping with Composite Interval Mapping (CIM) +# - CIM fits lm(pheno ~ marker + cofactors) at each marker position +# - Cofactors = top markers from initial RF screen (controls background) +# - LOD = -log10(p-value of marker term) +# - PVE computed from FULL model including cofactors → MUCH higher PVE +# +# 2. FIXED flanking markers +# - Flanking search now uses the FULL marker list (not post-NZV subset) +# - Correctly finds adjacent markers on same chromosome by sorted position +# +# 3. PVE FORMULA (unchanged, still correct): +# Full model: lm(phenotype ~ a + d) [additive + dominance] +# PVE (%) = R²_full × 100 +# Additive_Effect = beta_a, Dominance_Effect = beta_d +# Reference: Falconer & Mackay (1996); Lynch & Walsh (1998) +# ============================================================ + +options(repos = c(CRAN = "https://cloud.r-project.org")) + +required_packages <- c( + "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly", + "writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite", + "shinyjs", "markdown", "base64enc" +) + +for (pkg in required_packages) { + if (!require(pkg, character.only = TRUE)) { + install.packages(pkg, dependencies = TRUE) + library(pkg, character.only = TRUE) + } +} + +# ============================================================ +# TOKEN / API SETUP +# ============================================================ +token <- Sys.getenv("GROQ_API_KEY") +token_exists <- token != "" +token_length <- if (token_exists) nchar(token) else 0 + +cat("=== GROQ API TOKEN DEBUG ===\n") +cat("Token exists:", token_exists, "\n") +cat("Token length:", token_length, "\n") +if (token_exists) cat("Token starts with:", substr(token, 1, 10), "\n") +cat("===================================\n") + +HF_API_TOKEN <- token +HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions" +default_model <- "llama-3.1-8b-instant" + +available_models <- list( + list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"), + list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"), + list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"), + list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free") +) + +model_choices <- setNames( + sapply(available_models, function(m) m$id), + sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]")) +) + +# ============================================================ +# CIM CORE FUNCTION +# ============================================================ +# +# Composite Interval Mapping (Zeng 1993, 1994): +# For each marker m: +# 1. Select cofactors = top K markers from RF (excluding nearby markers on same chr) +# 2. Fit: Y ~ marker_m + cofactors (additive model) +# 3. LOD = -log10( p-value of marker_m term ) +# 4. PVE = R²_full × 100 (full model including cofactors) +# +# This gives HIGHER PVE because: +# - Cofactors absorb background genetic variance +# - Each marker's contribution is estimated after controlling for rest +# - Much more powerful than single-marker regression +# ============================================================ + +run_cim <- function(genotype_matrix, phenotype_vector, marker_info, + n_cofactors = 10, window_size = 10, + lod_threshold = 2.0) { + + markers <- colnames(genotype_matrix) + n_markers <- length(markers) + n_samples <- length(phenotype_vector) + + cat("CIM: Starting with", n_markers, "markers,", n_samples, "samples\n") + + # ---- Step 1: Select cofactors via RF ---- + valid_rows <- !is.na(phenotype_vector) + X_valid <- genotype_matrix[valid_rows, , drop = FALSE] + y_valid <- phenotype_vector[valid_rows] + + # Remove zero-variance markers before RF + nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) + X_valid <- X_valid[, !nzv, drop = FALSE] + + rf_model <- tryCatch( + randomForest(x = X_valid, y = y_valid, ntree = 500, importance = TRUE), + error = function(e) NULL + ) + + if (!is.null(rf_model)) { + imp_scores <- importance(rf_model, type = 1)[, 1] + top_cofactors <- names(sort(imp_scores, decreasing = TRUE))[1:min(n_cofactors * 2, length(imp_scores))] + } else { + # Fallback: single-marker regression ranking + p_vals <- sapply(colnames(X_valid), function(m) { + fit <- lm(y_valid ~ X_valid[, m]) + coef(summary(fit))[2, 4] + }) + top_cofactors <- names(sort(p_vals))[1:min(n_cofactors * 2, length(p_vals))] + } + + cat("CIM: Selected", length(top_cofactors), "candidate cofactors\n") + + # ---- Step 2: Scan each marker with CIM ---- + results_list <- list() + + for (i in seq_along(markers)) { + m <- markers[i] + + geno <- genotype_matrix[, m] + valid_idx <- !is.na(geno) & !is.na(phenotype_vector) + geno_v <- geno[valid_idx] + pheno_v <- phenotype_vector[valid_idx] + + if (length(unique(geno_v)) < 2 || length(pheno_v) < 5) next + + # Get marker info + m_info <- marker_info[marker_info$Marker == m, ] + if (nrow(m_info) == 0) next + m_chr <- m_info$Chromosome[1] + m_pos <- m_info$Position[1] + + # ---- Exclude cofactors within window_size positions on same chromosome ---- + chr_markers <- marker_info[marker_info$Chromosome == m_chr, ] + chr_markers <- chr_markers[order(chr_markers$Position), ] + m_idx <- which(chr_markers$Marker == m) + + if (length(m_idx) > 0) { + nearby_range <- max(1, m_idx - window_size):min(nrow(chr_markers), m_idx + window_size) + nearby_mks <- chr_markers$Marker[nearby_range] + } else { + nearby_mks <- m + } + + active_cofactors <- setdiff(top_cofactors, c(m, nearby_mks)) + active_cofactors <- active_cofactors[active_cofactors %in% colnames(genotype_matrix)] + active_cofactors <- head(active_cofactors, n_cofactors) + + # ---- Build data frame for model ---- + df_model <- data.frame(y = pheno_v, focal = geno_v[valid_idx]) + + # Add cofactors + if (length(active_cofactors) > 0) { + cof_mat <- genotype_matrix[valid_idx, active_cofactors, drop = FALSE] + # Handle NAs in cofactors + cof_mat[is.na(cof_mat)] <- 0 + df_model <- cbind(df_model, cof_mat) } - const d = await r.json(); - return d.choices?.[0]?.message?.content || ""; - }, - async groqVision(apiKey, model, imageData, mimeType) { - const messages = [{ - role: "user", - content: [ - { type: "text", text: "This is a 2D chemical structure image. Extract and return ONLY the SMILES string for this molecule, nothing else." }, - { type: "image_url", image_url: { url: `data:${mimeType};base64,${imageData}` } }, - ], - }]; - return this.callGroq(apiKey, model, messages, 200); - }, - async submitITasser(apiKey, sequence, jobName) { - const form = new FormData(); - form.append("api_key", apiKey); - form.append("sequence", sequence); - form.append("job_name", jobName || "MolExplorer_Job"); - const r = await fetch("https://zhanggroup.org/I-TASSER/submission/api/submit/", { - method: "POST", body: form, - }); - const text = await r.text(); - try { return JSON.parse(text); } catch { return { raw: text }; } - }, - async checkITasser(apiKey, jobId) { - const r = await fetch(`https://zhanggroup.org/I-TASSER/submission/api/status/?api_key=${apiKey}&job_id=${jobId}`); - return r.json(); - }, -}; - -// ─── LIPINSKI CHECK ─────────────────────────────────────────────────────────── -function checkLipinski(props) { - if (!props) return null; - return [ - { label: "MW ≤ 500 Da", val: props.MolecularWeight, pass: props.MolecularWeight <= 500 }, - { label: "LogP ≤ 5", val: props.XLogP, pass: props.XLogP <= 5 }, - { label: "HBD ≤ 5", val: props.HBondDonorCount, pass: props.HBondDonorCount <= 5 }, - { label: "HBA ≤ 10", val: props.HBondAcceptorCount, pass: props.HBondAcceptorCount <= 10 }, - ]; + + df_model <- df_model[complete.cases(df_model), ] + if (nrow(df_model) < 5) next + + # ---- Fit CIM model ---- + tryCatch({ + if (length(active_cofactors) > 0) { + cof_formula <- paste(active_cofactors, collapse = " + ") + full_formula <- as.formula(paste("y ~ focal +", cof_formula)) + } else { + full_formula <- as.formula("y ~ focal") + } + + fit <- lm(full_formula, data = df_model) + sm <- summary(fit) + coef_t <- sm$coefficients + + if (!"focal" %in% rownames(coef_t)) next + + p_val <- coef_t["focal", "Pr(>|t|)"] + lod <- -log10(p_val + 1e-300) # avoid log(0) + r2_full <- sm$r.squared + + # ---- Additive + Dominance effects (on this marker) ---- + a_code <- df_model$focal + d_code <- as.numeric(a_code == 1) + has_het <- length(unique(d_code)) > 1 + + if (has_het) { + lm_eff <- lm(y ~ a_code + d_code, data = df_model) + sm_eff <- summary(lm_eff) + pve_ad <- sm_eff$r.squared * 100 # PVE from add+dom ALONE (marker only) + c_eff <- coef(lm_eff) + a_eff <- c_eff["a_code"] + d_eff <- c_eff["d_code"] + se_t <- sm_eff$coefficients + se_a <- se_t["a_code", "Std. Error"] + se_d <- se_t["d_code", "Std. Error"] + d_rat <- if (!is.na(a_eff) && a_eff != 0) abs(d_eff / a_eff) else NA + } else { + lm_eff <- lm(y ~ a_code, data = df_model) + sm_eff <- summary(lm_eff) + pve_ad <- sm_eff$r.squared * 100 + c_eff <- coef(lm_eff) + a_eff <- c_eff["a_code"] + d_eff <- NA; se_a <- NA; se_d <- NA; d_rat <- NA + } + + # PVE from full CIM model (marker + cofactors) — this is the HIGH PVE + pve_cim <- r2_full * 100 + + dom_class <- if (is.na(d_rat)) "Additive" + else if (d_rat > 1) "Overdominance" + else if (d_rat > 0.5) "Dominance" + else if (d_rat > 0.2) "Partial Dom." + else "Additive" + + results_list[[m]] <- data.frame( + Marker = m, + Chromosome = m_chr, + Position = m_pos, + LOD = lod, + P_Value = p_val, + PVE_Marker_Percent = pve_ad, # PVE of marker alone (add+dom) + PVE_CIM_Percent = pve_cim, # PVE of full CIM model (marker + cofactors) + Additive_Effect = a_eff, + SE_Additive = se_a, + CI_Lower = ifelse(is.na(se_a), NA, a_eff - 1.96 * se_a), + CI_Upper = ifelse(is.na(se_a), NA, a_eff + 1.96 * se_a), + Dominance_Effect = d_eff, + SE_Dominance = se_d, + Dominance_Ratio = d_rat, + Dominance_Class = dom_class, + N_Cofactors = length(active_cofactors), + N_Samples = nrow(df_model), + N_Heterozygotes = sum(df_model$focal == 1), + stringsAsFactors = FALSE + ) + + }, error = function(e) { + cat("CIM error at marker", m, ":", e$message, "\n") + }) + } + + if (length(results_list) == 0) { + return(data.frame(Message = "CIM produced no results — check data format")) + } + + cim_result <- do.call(rbind, results_list) + cim_result <- cim_result[order(-cim_result$LOD), ] + cat("CIM: Completed scan,", nrow(cim_result), "markers evaluated\n") + return(cim_result) } -// ─── VINA PREPARATION STEPS ─────────────────────────────────────────────────── -const VINA_PROTEIN_STEPS = [ - "Remove water molecules (HETATM HOH records)", - "Remove non-standard ligands/cofactors", - "Add missing hydrogen atoms (e.g., reduce/pdb4amber)", - "Assign Gasteiger charges with AutoDockTools", - "Define active site box coordinates (center_x, center_y, center_z)", - "Convert to PDBQT format: python prepare_receptor4.py -r protein.pdb", -]; -const VINA_LIGAND_STEPS = [ - "Obtain or draw SMILES / SDF structure", - "Generate 3D coordinates (RDKit / OpenBabel)", - "Add hydrogens at physiological pH: obabel -h", - "Minimize geometry (MMFF94 / UFF force field)", - "Assign partial charges: obabel --partialcharge gasteiger", - "Convert to PDBQT: python prepare_ligand4.py -l ligand.sdf", -]; -const ABINITIO_STEPS = [ - "Input: amino acid sequence (FASTA format)", - "Fragment library generation (Rosetta ab initio)", - "Monte Carlo sampling of conformational space", - "Energy landscape exploration with full-atom refinement", - "Cluster low-energy decoys → select representative structure", - "Validate with PROCHECK / MolProbity Ramachandran analysis", -]; - -// ─── MOLECULE DRAW CANVAS ───────────────────────────────────────────────────── -function MolDrawCanvas({ onSmiles }) { - const canvasRef = useRef(); - const [drawing, setDrawing] = useState(false); - const [paths, setPaths] = useState([]); - const [currentPath, setCurrentPath] = useState([]); - const [mode, setMode] = useState("draw"); // draw | erase - const [smilesInput, setSmilesInput] = useState(""); - const [status, setStatus] = useState(""); - const [loading, setLoading] = useState(false); - - const getPos = (e) => { - const rect = canvasRef.current.getBoundingClientRect(); - const clientX = e.touches ? e.touches[0].clientX : e.clientX; - const clientY = e.touches ? e.touches[0].clientY : e.clientY; - return { x: clientX - rect.left, y: clientY - rect.top }; - }; - - const onDown = (e) => { - e.preventDefault(); - setDrawing(true); - const p = getPos(e); - setCurrentPath([p]); - }; - const onMove = (e) => { - if (!drawing) return; - e.preventDefault(); - setCurrentPath(prev => [...prev, getPos(e)]); - }; - const onUp = () => { - if (!drawing) return; - setDrawing(false); - if (mode === "erase") { - setPaths([]); +# ============================================================ +# FLANKING MARKER FUNCTION — FIXED +# Uses the FULL all_markers table (not post-NZV subset) +# ============================================================ + +add_flanking_markers <- function(sig_df, all_markers_df) { + sig_df$Low_Flank <- NA_character_ + sig_df$High_Flank <- NA_character_ + + for (i in 1:nrow(sig_df)) { + focal_marker <- sig_df$Marker[i] + focal_chr <- sig_df$Chromosome[i] + focal_pos <- sig_df$Position[i] + + # Get ALL markers on same chromosome, sorted by position + chr_markers <- all_markers_df[all_markers_df$Chromosome == focal_chr, ] + chr_markers <- chr_markers[order(chr_markers$Position), ] + + if (nrow(chr_markers) == 0) next + + # Find position of focal marker in sorted list + idx <- which(chr_markers$Marker == focal_marker) + + if (length(idx) > 0) { + sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker + sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker } else { - setPaths(prev => [...prev, currentPath]); + # Marker not found by name — find by closest position + dists <- abs(chr_markers$Position - focal_pos) + idx <- which.min(dists) + sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker + sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker } - setCurrentPath([]); - }; - - useEffect(() => { - const canvas = canvasRef.current; - const ctx = canvas.getContext("2d"); - ctx.fillStyle = "#0d1117"; - ctx.fillRect(0, 0, canvas.width, canvas.height); - ctx.strokeStyle = "#00e5ff"; - ctx.lineWidth = 2.5; - ctx.lineCap = "round"; - ctx.lineJoin = "round"; - [...paths, currentPath].forEach(path => { - if (path.length < 2) return; - ctx.beginPath(); - ctx.moveTo(path[0].x, path[0].y); - path.slice(1).forEach(p => ctx.lineTo(p.x, p.y)); - ctx.stroke(); - }); - }, [paths, currentPath]); - - const predictFromDrawing = async () => { - if (paths.length === 0) { setStatus("Draw a molecule first."); return; } - setLoading(true); setStatus("Converting drawing to base64..."); - const canvas = canvasRef.current; - const dataUrl = canvas.toDataURL("image/png"); - const b64 = dataUrl.split(",")[1]; - setSmilesInput(b64.substring(0, 20) + "…"); - setStatus("⚠️ Vision prediction requires Groq API key in AI tab."); - setLoading(false); - onSmiles && onSmiles({ type: "drawing", b64, mimeType: "image/png" }); - }; - - const lookupSmiles = async () => { - if (!smilesInput.trim()) return; - setLoading(true); setStatus("Looking up SMILES in PubChem…"); - try { - const cid = await API.smilesToCID(smilesInput.trim()); - if (!cid) throw new Error("Not found"); - setStatus(`✓ Found CID: ${cid}`); - onSmiles && onSmiles({ type: "smiles", smiles: smilesInput.trim(), cid }); - } catch (e) { - setStatus("✗ " + e.message); - } finally { setLoading(false); } - }; - - return ( -
-
- {["draw","erase"].map(m => ( - - ))} -
- -

- Draw a 2D structural formula above, then predict its 3D structure -

- -
- setSmilesInput(e.target.value)} - placeholder="Or enter SMILES directly…" - style={{ ...inputStyle, flex: 1, fontSize: 12 }} /> - -
- {status &&

{status}

} -
- ); + } + + return(sig_df) +} + +# ============================================================ +# API / AI FUNCTIONS (unchanged) +# ============================================================ + +test_api_connection <- function(model_id = default_model) { + if (!token_exists) return(list(success = FALSE, error = "No token found")) + tryCatch({ + response <- POST( + url = HF_API_URL, + add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"), + body = toJSON(list(model = model_id, messages = list(list(role = "user", content = "Hi")), max_tokens = 10L), auto_unbox = TRUE), + encode = "json", timeout(15)) + if (status_code(response) == 200) return(list(success = TRUE)) + err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response))) + list(success = FALSE, error = paste("Status:", status_code(response), "-", substr(err, 1, 200))) + }, error = function(e) list(success = FALSE, error = e$message)) } -// ─── STYLE HELPERS ──────────────────────────────────────────────────────────── -const inputStyle = { - background: "#1e2736", border: "1px solid #2d3748", borderRadius: 8, - color: "#e2e8f0", padding: "9px 12px", fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box", -}; -const btnStyle = (bg = "#00e5ff", col = "#0d1117") => ({ - background: bg, color: col, border: "none", borderRadius: 8, padding: "9px 16px", - cursor: "pointer", fontWeight: 700, fontSize: 13, width: "100%", -}); -const cardStyle = { background: "#111827", border: "1px solid #1e2736", borderRadius: 12, padding: 16, marginBottom: 12 }; -const labelStyle = { fontSize: 11, color: "#8892a4", textTransform: "uppercase", letterSpacing: 1, marginBottom: 6, display: "block" }; -const propRow = { display: "flex", justifyContent: "space-between", padding: "5px 0", borderBottom: "1px solid #1a2233", fontSize: 12 }; - -// ─── NOTIFICATION ────────────────────────────────────────────────────────────── -function Toast({ msg, type, onClose }) { - useEffect(() => { const t = setTimeout(onClose, 4000); return () => clearTimeout(t); }, [msg]); - const colors = { success: "#4ade80", error: "#f87171", warning: "#f59e0b", info: "#60a5fa" }; - if (!msg) return null; - return ( -
- {msg} - ✕ -
- ); +api_test <- test_api_connection(default_model) +use_hf_api <- token_exists && api_test$success + +cat("API Test:", if (api_test$success) "SUCCESS" else paste("FAILED -", api_test$error), "\n") + +query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) { + if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set")) + tryCatch({ + response <- POST( + url = HF_API_URL, + add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"), + body = toJSON(list( + model = model_id, + messages = list( + list(role = "system", content = "You are an expert bioinformatics assistant specializing in QTL analysis using Composite Interval Mapping. Be concise and helpful."), + list(role = "user", content = prompt)), + max_tokens = as.integer(max_length), temperature = temperature), auto_unbox = TRUE), + encode = "json", timeout(60)) + if (status_code(response) == 200) { + result <- content(response, as = "parsed", encoding = "UTF-8") + return(list(success = TRUE, text = result$choices[[1]]$message$content)) + } + err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response))) + list(success = FALSE, error = paste("API error:", status_code(response), "-", substr(err, 1, 200))) + }, error = function(e) list(success = FALSE, error = e$message)) } -// ─── VIEWER PLACEHOLDER ─────────────────────────────────────────────────────── -function Viewer3D({ pdbText, sdfText, label }) { - // Embed NGL/3Dmol via iframe with postMessage since we can't import them directly - const iframeRef = useRef(); - const [loaded, setLoaded] = useState(false); - - const htmlContent = ` - - - - -
-`; - - const srcUrl = `data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`; - - useEffect(() => { - if (!loaded) return; - const iframe = iframeRef.current; - const sendMsg = (msg) => iframe?.contentWindow?.postMessage(msg, "*"); - if (pdbText && sdfText) sendMsg({ type: "loadBoth", pdb: pdbText, sdf: sdfText }); - else if (pdbText) sendMsg({ type: "loadPDB", data: pdbText }); - else if (sdfText) sendMsg({ type: "loadSDF", data: sdfText }); - }, [pdbText, sdfText, loaded]); - - useEffect(() => { - const handler = (e) => { if (e.data?.type === "ready") setLoaded(true); }; - window.addEventListener("message", handler); - return () => window.removeEventListener("message", handler); - }, []); - - return ( -
-