import gradio as gr from transformers import pipeline from PIL import Image import pytesseract import matplotlib.pyplot as plt import matplotlib matplotlib.use("Agg") from collections import Counter import re # --------------------------------------------------- # AI MODEL # --------------------------------------------------- pipe = pipeline( "text-generation", model="Qwen/Qwen2.5-1.5B-Instruct" ) # --------------------------------------------------- # OCR + DNA ANALYSIS # --------------------------------------------------- def analyze_sequence(image, question): if image is None: return ( {"error": "No image uploaded. Please upload a DNA/RNA image."}, None, "⚠️ Please upload a DNA/RNA image to begin analysis." ) # OCR Extraction try: extracted_text = pytesseract.image_to_string(image) except Exception as e: return ( {"error": f"OCR failed: {str(e)}"}, None, "⚠️ Could not read the image. Please try a clearer image." ) # Clean Sequence — keep only valid nucleotide characters sequence = re.sub(r'[^ATCGU]', '', extracted_text.upper()) if not sequence: sequence_display = "No nucleotide sequence detected in image." counts = {} confidence_score = 20 else: sequence_display = sequence[:500] counts = Counter(sequence) confidence_score = min(99, 60 + len(sequence) // 5) # Build prompt user_question = question.strip() if question and question.strip() else "Provide a general genomic analysis." prompt = f"""You are VISION-LINK AI, an advanced genomic intelligence system. Sequence: {sequence_display} User Query: {user_question} Provide: 1. Sequence interpretation 2. Mutation insights 3. Diagnostic observations 4. Biotechnology recommendations""" try: result = pipe( prompt, max_new_tokens=220, do_sample=True, temperature=0.7 ) full_output = result[0]["generated_text"] # Strip the prompt — only keep what the model generated after it ai_output = full_output[len(prompt):].strip() if not ai_output: ai_output = full_output.strip() except Exception as e: ai_output = f"AI analysis failed: {str(e)}" # JSON-style report analysis = { "Confidence Score": f"{confidence_score}%", "Detected Sequence (first 500 chars)": sequence_display, "Sequence Length": len(sequence) if sequence and sequence != "No nucleotide sequence detected in image." else 0, "Nucleotide Counts": dict(counts), "AI Diagnostic Summary": ai_output } # --------------------------------------------------- # DARK-THEMED CHART # --------------------------------------------------- fig = None if counts: color_map = { 'A': '#38bdf8', 'T': '#818cf8', 'C': '#34d399', 'G': '#fb923c', 'U': '#f472b6', } bar_colors = [color_map.get(n, '#94a3b8') for n in counts.keys()] fig, ax = plt.subplots(figsize=(5, 4)) fig.patch.set_facecolor('#0f172a') ax.set_facecolor('#1e293b') bars = ax.bar(counts.keys(), counts.values(), color=bar_colors, width=0.5, zorder=3) for bar in bars: ax.text( bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.3, str(int(bar.get_height())), ha='center', va='bottom', color='white', fontsize=11, fontweight='bold' ) ax.set_title("Nucleotide Distribution", color='#67e8f9', fontsize=14, fontweight='bold', pad=12) ax.set_xlabel("Nucleotide", color='#94a3b8', fontsize=11) ax.set_ylabel("Count", color='#94a3b8', fontsize=11) ax.tick_params(colors='#cbd5e1') ax.spines['bottom'].set_color('#334155') ax.spines['left'].set_color('#334155') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.yaxis.grid(True, color='#1e3a5f', linestyle='--', alpha=0.5, zorder=0) ax.set_axisbelow(True) plt.tight_layout() return analysis, fig, ai_output # --------------------------------------------------- # CUSTOM CSS # --------------------------------------------------- custom_css = """ @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@700;900&family=Exo+2:wght@300;400;600&display=swap'); body { background: linear-gradient(135deg, #020617, #0f172a) !important; min-height: 100vh; } .gradio-container { font-family: 'Exo 2', sans-serif !important; max-width: 1200px !important; margin: 0 auto !important; } .main-title { text-align: center; font-family: 'Orbitron', monospace; font-size: 36px; font-weight: 900; background: linear-gradient(90deg, #38bdf8, #818cf8, #38bdf8); background-size: 200% auto; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; animation: shimmer 3s linear infinite; margin-bottom: 8px; letter-spacing: 2px; } @keyframes shimmer { 0% { background-position: 0% center; } 100% { background-position: 200% center; } } .sub-title { text-align: center; color: #94a3b8; margin-bottom: 30px; font-size: 15px; letter-spacing: 1px; } button.primary { background: linear-gradient(135deg, #0ea5e9, #6366f1) !important; border: none !important; border-radius: 10px !important; font-family: 'Orbitron', monospace !important; font-size: 12px !important; font-weight: 700 !important; letter-spacing: 1px !important; color: white !important; padding: 12px 20px !important; width: 100% !important; box-shadow: 0 0 20px rgba(14, 165, 233, 0.35) !important; transition: all 0.3s ease !important; } button.primary:hover { transform: translateY(-2px) !important; box-shadow: 0 0 35px rgba(14, 165, 233, 0.55) !important; } footer { visibility: hidden; } """ # --------------------------------------------------- # UI # --------------------------------------------------- with gr.Blocks( theme=gr.themes.Glass(), css=custom_css, title="VISION-LINK AI" ) as demo: gr.HTML("""