Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+740
- requirements.txtAdded+7
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740import os
import re
import io
import time
import textwrap
import tempfile
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Tuple
import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import gradio as gr
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.pdfgen import canvas
APP_TITLE = "GeneClean-BLAST"
APP_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = APP_DIR / "outputs"
OUTPUT_DIR.mkdir(exist_ok=True)
NCBI_BLAST_URL = "https://blast.ncbi.nlm.nih.gov/Blast.cgi"
# -----------------------------
# Utility functions
# -----------------------------
def safe_filename(name: str) -> str:
name = re.sub(r"[^A-Za-z0-9._-]+", "_", name.strip())
return name or "output"
def normalize_fasta_text(raw_text: str) -> str:
"""
Accepts either FASTA text or raw sequence text.
Returns normalized FASTA text.
"""
raw_text = (raw_text or "").strip()
if not raw_text:
raise ValueError("No sequence text provided.")
if raw_text.startswith(">"):
return raw_text
seq = re.sub(r"\s+", "", raw_text)
return f">query_1\n{seq}\n"
def read_uploaded_or_text(file_obj, text_input: str) -> str:
if file_obj is not None:
with open(file_obj.name, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
if not content.strip():
raise ValueError("Uploaded file is empty.")
return content
return normalize_fasta_text(text_input)
def parse_fasta(content: str) -> List[SeqRecord]:
handle = io.StringIO(content)
records = list(SeqIO.parse(handle, "fasta"))
if not records:
raise ValueError("No valid FASTA sequence found.")
return records
def wrap_sequence(seq: str, width: int = 80) -> str:
return "\n".join(textwrap.wrap(seq, width))
def base_counts(seq: str) -> Dict[str, int]:
seq = seq.upper()
counts = {b: seq.count(b) for b in "ACGTU"}
counts["N"] = seq.count("N")
return counts
def gc_content(seq: str) -> float:
seq = seq.upper()
valid = [b for b in seq if b in {"A", "C", "G", "T", "U"}]
if not valid:
return 0.0
gc = sum(1 for b in valid if b in {"G", "C"})
return (gc / len(valid)) * 100.0
def low_complexity_fraction(seq: str) -> float:
"""
Simple proxy: frequency of the most common base.
"""
seq = "".join([b for b in seq.upper() if b in "ACGTUN"])
if not seq:
return 0.0
values = [seq.count(b) for b in set(seq)]
return max(values) / len(seq)
def count_ambiguous(seq: str) -> int:
iupac_ambiguous = set("RYSWKMBDHVN")
return sum(1 for b in seq.upper() if b in iupac_ambiguous)
def find_invalid_characters(seq: str) -> List[str]:
allowed = set("ACGTUNRYSWKMBDHVacgtunryswkmbdhv")
invalid = sorted(set([ch for ch in seq if ch not in allowed and not ch.isspace()]))
return invalid
def clean_sequence(seq: str, mode: str) -> Tuple[str, int, int, List[str]]:
"""
mode:
- "Keep ambiguous bases"
- "Mask ambiguous bases to N"
- "Remove ambiguous bases"
"""
original = seq
invalid_chars = find_invalid_characters(original)
# remove whitespace and invalid chars
seq = "".join([ch for ch in original if not ch.isspace()])
seq = "".join([ch for ch in seq if ch.upper() in set("ACGTUNRYSWKMBDHV")])
seq = seq.upper().replace("U", "T")
ambiguous_set = set("RYSWKMBDHVN")
ambiguous_before = sum(1 for b in seq if b in ambiguous_set)
if mode == "Mask ambiguous bases to N":
seq = "".join("N" if b in ambiguous_set else b for b in seq)
elif mode == "Remove ambiguous bases":
seq = "".join(b for b in seq if b not in ambiguous_set)
elif mode == "Keep ambiguous bases":
pass
else:
raise ValueError("Invalid cleaning mode selected.")
ambiguous_after = sum(1 for b in seq if b in ambiguous_set)
return seq, ambiguous_before, ambiguous_after, invalid_chars
def detect_sequence_type(seq: str) -> str:
dna_chars = set("ACGTN")
if all(ch in dna_chars for ch in seq.upper()):
return "DNA"
return "Nucleotide (contains ambiguous bases)"
def build_clean_records(records: List[SeqRecord], mode: str) -> Tuple[List[SeqRecord], pd.DataFrame]:
cleaned_records = []
qc_rows = []
seen_headers = set()
duplicate_header_count = 0
for i, rec in enumerate(records, start=1):
header = rec.id.strip() if rec.id.strip() else f"query_{i}"
if header in seen_headers:
duplicate_header_count += 1
header = f"{header}_dup{i}"
seen_headers.add(header)
raw_seq = str(rec.seq)
raw_len = len(re.sub(r"\s+", "", raw_seq))
raw_amb = count_ambiguous(raw_seq)
raw_gc = gc_content(raw_seq)
invalid_chars = find_invalid_characters(raw_seq)
cleaned_seq, amb_before, amb_after, invalid = clean_sequence(raw_seq, mode)
clean_len = len(cleaned_seq)
clean_gc = gc_content(cleaned_seq)
seq_type = detect_sequence_type(cleaned_seq)
low_complex = low_complexity_fraction(cleaned_seq)
warnings = []
if invalid_chars:
warnings.append(f"Invalid chars removed: {''.join(invalid_chars)}")
if raw_amb > 0:
warnings.append(f"Ambiguous bases present: {raw_amb}")
if clean_len < 50:
warnings.append("Very short sequence (<50 bp)")
if low_complex > 0.80:
warnings.append("Low complexity sequence")
if duplicate_header_count > 0:
warnings.append("Duplicate FASTA header detected and renamed")
cleaned_records.append(
SeqRecord(Seq(cleaned_seq), id=header, description="")
)
qc_rows.append({
"Sequence_ID": header,
"Original_Length": raw_len,
"Cleaned_Length": clean_len,
"Original_GC_%": round(raw_gc, 2),
"Cleaned_GC_%": round(clean_gc, 2),
"Original_Ambiguous_Bases": raw_amb,
"Ambiguous_Bases_Before_Cleaning": amb_before,
"Ambiguous_Bases_After_Cleaning": amb_after,
"Invalid_Characters_Removed": "".join(sorted(set(invalid_chars + invalid))) if (invalid_chars or invalid) else "",
"Sequence_Type": seq_type,
"Low_Complexity_Fraction": round(low_complex, 3),
"Warnings": "; ".join(warnings) if warnings else "None"
})
qc_df = pd.DataFrame(qc_rows)
return cleaned_records, qc_df
def save_clean_fasta(records: List[SeqRecord], out_path: Path) -> Path:
with open(out_path, "w", encoding="utf-8") as f:
SeqIO.write(records, f, "fasta")
return out_path
def build_summary_text(qc_df: pd.DataFrame, cleaning_mode: str) -> str:
n = len(qc_df)
total_original = int(qc_df["Original_Length"].sum())
total_cleaned = int(qc_df["Cleaned_Length"].sum())
mean_gc = round(qc_df["Cleaned_GC_%"].mean(), 2) if n > 0 else 0
total_amb_before = int(qc_df["Ambiguous_Bases_Before_Cleaning"].sum())
total_amb_after = int(qc_df["Ambiguous_Bases_After_Cleaning"].sum())
return (
f"Processed sequences: {n}\n"
f"Cleaning mode: {cleaning_mode}\n"
f"Total original length: {total_original:,} bp\n"
f"Total cleaned length: {total_cleaned:,} bp\n"
f"Mean cleaned GC%: {mean_gc}\n"
f"Ambiguous bases before cleaning: {total_amb_before:,}\n"
f"Ambiguous bases after cleaning: {total_amb_after:,}\n"
f"Run date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
)
def make_qc_figure(qc_df: pd.DataFrame, out_path: Path) -> Path:
fig, ax = plt.subplots(figsize=(10, 5), dpi=300)
x = np.arange(len(qc_df))
ax.bar(x - 0.2, qc_df["Original_Length"], width=0.4, label="Original length")
ax.bar(x + 0.2, qc_df["Cleaned_Length"], width=0.4, label="Cleaned length")
ax.set_xlabel("Sequence index")
ax.set_ylabel("Length (bp)")
ax.set_title("Sequence length before and after cleaning")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
return out_path
def write_pdf_report(summary_text: str, qc_df: pd.DataFrame, figure_path: Path, out_path: Path) -> Path:
c = canvas.Canvas(str(out_path), pagesize=A4)
width, height = A4
y = height - 2 * cm
c.setFont("Helvetica-Bold", 14)
c.drawString(2 * cm, y, "GeneClean-BLAST Report")
y -= 0.8 * cm
c.setFont("Helvetica", 10)
for line in summary_text.splitlines():
c.drawString(2 * cm, y, line)
y -= 0.5 * cm
y -= 0.3 * cm
c.setFont("Helvetica-Bold", 11)
c.drawString(2 * cm, y, "QC Table (first 15 rows)")
y -= 0.6 * cm
c.setFont("Helvetica", 8)
preview_df = qc_df.head(15).copy()
table_lines = preview_df.to_string(index=False).splitlines()
for line in table_lines:
if y < 4 * cm:
c.showPage()
y = height - 2 * cm
c.setFont("Helvetica", 8)
c.drawString(1.2 * cm, y, line[:130])
y -= 0.35 * cm
if figure_path.exists():
c.showPage()
c.setFont("Helvetica-Bold", 11)
c.drawString(2 * cm, height - 2 * cm, "QC Figure")
c.drawImage(str(figure_path), 1.5 * cm, 5 * cm, width=17 * cm, preserveAspectRatio=True, mask='auto')
c.save()
return out_path
# -----------------------------
# BLAST functions
# -----------------------------
def submit_blast(sequence: str, program: str, database: str, entrez_query: str = "") -> str:
payload = {
"CMD": "Put",
"PROGRAM": program,
"DATABASE": database,
"QUERY": sequence,
"FORMAT_TYPE": "XML",
}
if entrez_query.strip():
payload["ENTREZ_QUERY"] = entrez_query.strip()
r = requests.post(NCBI_BLAST_URL, data=payload, timeout=120)
r.raise_for_status()
text = r.text
rid_match = re.search(r"RID = ([A-Z0-9-]+)", text)
rtoe_match = re.search(r"RTOE = (\d+)", text)
if not rid_match:
raise RuntimeError("Could not obtain BLAST RID from NCBI response.")
rid = rid_match.group(1)
rtoe = int(rtoe_match.group(1)) if rtoe_match else 20
return rid, rtoe
def poll_blast_result(rid: str, max_wait: int = 300) -> str:
start = time.time()
while True:
params = {
"CMD": "Get",
"RID": rid,
"FORMAT_TYPE": "XML",
}
r = requests.get(NCBI_BLAST_URL, params=params, timeout=120)
r.raise_for_status()
txt = r.text
if "Status=WAITING" in txt:
if time.time() - start > max_wait:
raise TimeoutError("BLAST job did not complete within the waiting time.")
time.sleep(10)
continue
if "Status=FAILED" in txt:
raise RuntimeError("NCBI BLAST search failed.")
if "Status=UNKNOWN" in txt:
raise RuntimeError("NCBI BLAST RID expired or is unknown.")
if "Status=READY" in txt and "ThereAreHits=yes" in txt:
# fetch final XML
r2 = requests.get(
NCBI_BLAST_URL,
params={"CMD": "Get", "RID": rid, "FORMAT_TYPE": "XML"},
timeout=120
)
r2.raise_for_status()
return r2.text
if "Status=READY" in txt and "ThereAreHits=no" in txt:
return ""
# Sometimes XML may come directly
if txt.lstrip().startswith("<?xml") or "<BlastOutput>" in txt:
return txt
if time.time() - start > max_wait:
raise TimeoutError("BLAST polling exceeded maximum wait time.")
time.sleep(10)
def parse_blast_xml(xml_text: str, query_id: str) -> pd.DataFrame:
if not xml_text.strip():
return pd.DataFrame(columns=[
"Query_ID", "Hit_Number", "Accession", "Hit_Definition", "Organism",
"Alignment_Length", "Identity", "Percent_Identity", "Query_Coverage_Approx_%",
"E_value", "Bit_Score"
])
import xml.etree.ElementTree as ET
root = ET.fromstring(xml_text)
rows = []
hits = root.findall(".//Hit")
for idx, hit in enumerate(hits, start=1):
accession = hit.findtext("Hit_accession", default="")
hit_def = hit.findtext("Hit_def", default="")
hsps = hit.findall(".//Hsp")
if not hsps:
continue
hsp = hsps[0]
align_len = int(hsp.findtext("Hsp_align-len", default="0"))
identity = int(hsp.findtext("Hsp_identity", default="0"))
q_from = int(hsp.findtext("Hsp_query-from", default="0"))
q_to = int(hsp.findtext("Hsp_query-to", default="0"))
evalue = hsp.findtext("Hsp_evalue", default="")
bit_score = hsp.findtext("Hsp_bit-score", default="")
pct_identity = (identity / align_len * 100.0) if align_len > 0 else 0.0
qcov = abs(q_to - q_from) + 1
organism = ""
m = re.search(r"\[(.+?)\]\s*$", hit_def)
if m:
organism = m.group(1)
rows.append({
"Query_ID": query_id,
"Hit_Number": idx,
"Accession": accession,
"Hit_Definition": hit_def,
"Organism": organism,
"Alignment_Length": align_len,
"Identity": identity,
"Percent_Identity": round(pct_identity, 2),
"Query_Coverage_Approx_%": qcov,
"E_value": evalue,
"Bit_Score": bit_score,
})
df = pd.DataFrame(rows)
return df
def run_blast_for_records(records: List[SeqRecord], program: str, database: str, entrez_query: str, top_n: int):
all_hits = []
status_lines = []
for i, rec in enumerate(records, start=1):
seq = str(rec.seq)
if len(seq) < 20:
status_lines.append(f"{rec.id}: skipped (sequence too short for BLAST).")
continue
rid, rtoe = submit_blast(seq, program, database, entrez_query)
status_lines.append(f"{rec.id}: submitted to NCBI BLAST (RID={rid}, estimated wait={rtoe}s).")
xml_text = poll_blast_result(rid)
df = parse_blast_xml(xml_text, rec.id)
if not df.empty:
df = df.head(top_n)
all_hits.append(df)
status_lines.append(f"{rec.id}: {len(df)} hit(s) retrieved.")
else:
status_lines.append(f"{rec.id}: no hits found.")
if all_hits:
final_df = pd.concat(all_hits, ignore_index=True)
else:
final_df = pd.DataFrame(columns=[
"Query_ID", "Hit_Number", "Accession", "Hit_Definition", "Organism",
"Alignment_Length", "Identity", "Percent_Identity", "Query_Coverage_Approx_%",
"E_value", "Bit_Score"
])
return final_df, "\n".join(status_lines)
def make_blast_figure(blast_df: pd.DataFrame, out_path: Path) -> Path:
if blast_df.empty:
fig, ax = plt.subplots(figsize=(8, 4), dpi=300)
ax.text(0.5, 0.5, "No BLAST hits available", ha="center", va="center")
ax.axis("off")
plt.tight_layout()
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
return out_path
top = (
blast_df["Organism"]
.replace("", "Unknown")
.value_counts()
.head(10)
.sort_values(ascending=True)
)
fig, ax = plt.subplots(figsize=(10, 5), dpi=300)
ax.barh(top.index, top.values)
ax.set_xlabel("Number of top hits")
ax.set_ylabel("Organism")
ax.set_title("Top organisms represented in BLAST hits")
ax.grid(True, axis="x", alpha=0.3)
plt.tight_layout()
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
return out_path
# -----------------------------
# Main pipeline
# -----------------------------
def run_pipeline(
uploaded_file,
text_input,
cleaning_mode,
run_blast_flag,
blast_program,
blast_database,
entrez_query,
top_n_hits,
):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
run_dir = OUTPUT_DIR / f"run_{timestamp}"
run_dir.mkdir(parents=True, exist_ok=True)
try:
raw_content = read_uploaded_or_text(uploaded_file, text_input)
records = parse_fasta(raw_content)
cleaned_records, qc_df = build_clean_records(records, cleaning_mode)
clean_fasta_path = save_clean_fasta(cleaned_records, run_dir / "cleaned_sequences.fasta")
qc_csv_path = run_dir / "qc_summary.csv"
qc_df.to_csv(qc_csv_path, index=False)
summary_text = build_summary_text(qc_df, cleaning_mode)
qc_fig_path = make_qc_figure(qc_df, run_dir / "qc_figure.png")
pdf_report_path = write_pdf_report(summary_text, qc_df, qc_fig_path, run_dir / "GeneClean_Report.pdf")
blast_df = pd.DataFrame()
blast_csv_path = run_dir / "blast_results.csv"
blast_fig_path = run_dir / "blast_figure.png"
blast_status = "BLAST not run."
if run_blast_flag:
blast_df, blast_status = run_blast_for_records(
cleaned_records,
blast_program,
blast_database,
entrez_query,
int(top_n_hits)
)
blast_df.to_csv(blast_csv_path, index=False)
make_blast_figure(blast_df, blast_fig_path)
else:
blast_df.to_csv(blast_csv_path, index=False)
make_blast_figure(blast_df, blast_fig_path)
cleaned_preview = ""
for rec in cleaned_records[:5]:
cleaned_preview += f">{rec.id}\n{wrap_sequence(str(rec.seq), 80)}\n"
return (
summary_text + "\n\n" + blast_status,
cleaned_preview.strip(),
qc_df,
blast_df,
str(clean_fasta_path),
str(qc_csv_path),
str(blast_csv_path),
str(pdf_report_path),
str(qc_fig_path),
str(blast_fig_path),
)
except Exception as e:
empty_qc = pd.DataFrame()
empty_blast = pd.DataFrame()
return (
f"Error: {str(e)}",
"",
empty_qc,
empty_blast,
None,
None,
None,
None,
None,
None,
)
def clear_outputs():
return (
"",
"",
pd.DataFrame(),
pd.DataFrame(),
None,
None,
None,
None,
None,
None,
None,
)
# -----------------------------
# Gradio UI
# -----------------------------
with gr.Blocks(title=APP_TITLE) as demo:
gr.Markdown(
"""
# GeneClean-BLAST
**Sequence cleaning, quality control, and NCBI BLAST analysis**
Upload FASTA or paste nucleotide sequence text.
The tool will:
- clean invalid characters and formatting issues
- summarize sequence quality
- generate publication-ready outputs
- optionally run remote NCBI BLAST on cleaned sequences
"""
)
with gr.Row():
with gr.Column(scale=1):
uploaded_file = gr.File(
label="Upload FASTA / TXT file",
file_types=[".fasta", ".fa", ".fna", ".txt"],
type="filepath"
)
text_input = gr.Textbox(
label="Or paste FASTA / raw nucleotide sequence",
lines=12,
placeholder=">seq1\nATGCGTNNNNATCG..."
)
cleaning_mode = gr.Dropdown(
label="Cleaning mode",
choices=[
"Keep ambiguous bases",
"Mask ambiguous bases to N",
"Remove ambiguous bases"
],
value="Mask ambiguous bases to N"
)
run_blast_flag = gr.Checkbox(
label="Run NCBI BLAST on cleaned sequences",
value=True
)
with gr.Accordion("BLAST settings", open=True):
blast_program = gr.Dropdown(
label="BLAST program",
choices=["blastn", "blastx"],
value="blastn"
)
blast_database = gr.Dropdown(
label="BLAST database",
choices=["nt", "core_nt", "refseq_rna"],
value="nt"
)
entrez_query = gr.Textbox(
label="Optional Entrez organism/filter query",
placeholder='Example: "Escherichia coli"[Organism]'
)
top_n_hits = gr.Slider(
label="Top hits per sequence",
minimum=1,
maximum=20,
value=5,
step=1
)
with gr.Row():
run_btn = gr.Button("Run analysis", variant="primary")
clear_btn = gr.Button("Clear")
with gr.Column(scale=1):
summary_output = gr.Textbox(
label="Run summary",
lines=14
)
cleaned_preview = gr.Textbox(
label="Cleaned FASTA preview",
lines=14
)
with gr.Tabs():
with gr.Tab("QC Table"):
qc_table = gr.Dataframe(label="Sequence QC summary", interactive=False)
with gr.Tab("BLAST Table"):
blast_table = gr.Dataframe(label="BLAST results", interactive=False)
with gr.Tab("Figures"):
qc_figure = gr.Image(label="QC figure", type="filepath")
blast_figure = gr.Image(label="BLAST organism figure", type="filepath")
with gr.Tab("Downloads"):
clean_fasta_file = gr.File(label="Download cleaned FASTA")
qc_csv_file = gr.File(label="Download QC CSV")
blast_csv_file = gr.File(label="Download BLAST CSV")
pdf_report_file = gr.File(label="Download PDF report")
run_btn.click(
fn=run_pipeline,
inputs=[
uploaded_file,
text_input,
cleaning_mode,
run_blast_flag,
blast_program,
blast_database,
entrez_query,
top_n_hits,
],
outputs=[
summary_output,
cleaned_preview,
qc_table,
blast_table,
clean_fasta_file,
qc_csv_file,
blast_csv_file,
pdf_report_file,
qc_figure,
blast_figure,
]
)
clear_btn.click(
fn=clear_outputs,
inputs=[],
outputs=[
summary_output,
cleaned_preview,
qc_table,
blast_table,
clean_fasta_file,
qc_csv_file,
blast_csv_file,
pdf_report_file,
qc_figure,
blast_figure,
uploaded_file,
]
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)1234567gradio==5.24.0
biopython==1.84
pandas==2.2.3
numpy==2.1.3
matplotlib==3.9.2
requests==2.32.3
reportlab==4.2.5app.pyAdded+740
requirements.txtAdded+7