Fix UI: add dark theme, fix AI output, improve error handling

#1
Files changed (1) hide show
  1. app.py +261 -223
app.py CHANGED
@@ -1,224 +1,262 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- from PIL import Image
4
- import pytesseract
5
- import pandas as pd
6
- import matplotlib.pyplot as plt
7
- from collections import Counter
8
- import re
9
-
10
- # ---------------------------------------------------
11
- # AI MODEL
12
- # ---------------------------------------------------
13
- pipe = pipeline(
14
- "text-generation",
15
- model="Qwen/Qwen2.5-1.5B-Instruct"
16
- )
17
-
18
- # ---------------------------------------------------
19
- # OCR + DNA ANALYSIS
20
- # ---------------------------------------------------
21
- def analyze_sequence(image, question):
22
-
23
- if image is None:
24
- return (
25
- {"error": "No image uploaded"},
26
- None,
27
- "Please upload a DNA/RNA image."
28
- )
29
-
30
- # OCR Extraction
31
- extracted_text = pytesseract.image_to_string(image)
32
-
33
- # Clean Sequence
34
- sequence = re.sub(r'[^ATCGU]', '', extracted_text.upper())
35
-
36
- if not sequence:
37
- sequence = "No nucleotide sequence detected."
38
-
39
- # Count nucleotides
40
- counts = Counter(sequence)
41
-
42
- confidence_score = min(
43
- 99,
44
- 60 + len(sequence) // 5
45
- )
46
-
47
- # Diagnostic summary
48
- prompt = f"""
49
- You are VISION-LINK AI,
50
- an advanced genomic intelligence system.
51
-
52
- Sequence:
53
- {sequence}
54
-
55
- User Query:
56
- {question}
57
-
58
- Provide:
59
- 1. Sequence interpretation
60
- 2. Mutation insights
61
- 3. Diagnostic observations
62
- 4. Biotechnology recommendations
63
- """
64
-
65
- result = pipe(
66
- prompt,
67
- max_new_tokens=220,
68
- do_sample=True,
69
- temperature=0.7
70
- )
71
-
72
- ai_output = result[0]["generated_text"]
73
-
74
- # JSON-style output
75
- analysis = {
76
- "Confidence Score": f"{confidence_score}%",
77
- "Identified Sequence": sequence[:500],
78
- "Diagnostic Insights": ai_output
79
- }
80
-
81
- # Plot graph
82
- fig, ax = plt.subplots(figsize=(5, 4))
83
- ax.bar(counts.keys(), counts.values())
84
- ax.set_title("Nucleotide Distribution")
85
- ax.set_xlabel("Nucleotide")
86
- ax.set_ylabel("Count")
87
-
88
- return analysis, fig, ai_output
89
-
90
- # ---------------------------------------------------
91
- # CUSTOM CSS
92
- # ---------------------------------------------------
93
- custom_css = """
94
- body {
95
- background: linear-gradient(135deg, #020617, #0f172a);
96
- }
97
-
98
- .gradio-container {
99
- font-family: 'Segoe UI', sans-serif;
100
- }
101
-
102
- .main-title {
103
- text-align: center;
104
- font-size: 42px;
105
- font-weight: bold;
106
- color: #67e8f9;
107
- margin-bottom: 10px;
108
- }
109
-
110
- .sub-title {
111
- text-align: center;
112
- color: #cbd5e1;
113
- margin-bottom: 30px;
114
- font-size: 18px;
115
- }
116
-
117
- footer {
118
- visibility: hidden;
119
- }
120
- """
121
-
122
- # ---------------------------------------------------
123
- # UI
124
- # ---------------------------------------------------
125
- with gr.Blocks(
126
- theme=gr.themes.Glass(),
127
- css=custom_css,
128
- title="VISION-LINK AI"
129
- ) as demo:
130
-
131
- gr.Markdown(
132
- """
133
- <div class="main-title">
134
- VISION-LINK AI: Advanced Genomic & Molecular Intelligence
135
- </div>
136
-
137
- <div class="sub-title">
138
- Pioneering AI-driven Biotechnology Solutions for Sub-Saharan Africa
139
- </div>
140
- """
141
- )
142
-
143
- with gr.Row():
144
-
145
- # ---------------------------------------------------
146
- # COLUMN 1
147
- # ---------------------------------------------------
148
- with gr.Column():
149
-
150
- gr.Markdown("## 🧬 Molecular Input")
151
-
152
- image_input = gr.Image(
153
- type="pil",
154
- label="Upload DNA/RNA/Nucleotide Sequence Image (JPEG/PNG)"
155
- )
156
-
157
- analyze_btn = gr.Button(
158
- "Analyze Sequence",
159
- variant="primary"
160
- )
161
-
162
- # ---------------------------------------------------
163
- # COLUMN 2
164
- # ---------------------------------------------------
165
- with gr.Column():
166
-
167
- gr.Markdown("## 🤖 Intelligence Engine")
168
-
169
- question_input = gr.Textbox(
170
- lines=6,
171
- placeholder="Explain this genetic mutation or compare RNA strands...",
172
- label="Research Query"
173
- )
174
-
175
- chatbot_output = gr.Textbox(
176
- lines=16,
177
- label="AI Molecular Analysis"
178
- )
179
-
180
- gr.Examples(
181
- examples=[
182
- ["What is the nucleotide sequence of this image?"],
183
- ["Explain this genetic mutation."],
184
- ["Compare these RNA strands."],
185
- ["Identify abnormalities in this sequence."]
186
- ],
187
- inputs=question_input
188
- )
189
-
190
- # ---------------------------------------------------
191
- # COLUMN 3
192
- # ---------------------------------------------------
193
- with gr.Column():
194
-
195
- gr.Markdown("## �� Results & Analytics")
196
-
197
- json_output = gr.JSON(
198
- label="Genomic Analysis Report"
199
- )
200
-
201
- plot_output = gr.Plot(
202
- label="Nucleotide Distribution"
203
- )
204
-
205
- # ---------------------------------------------------
206
- # BUTTON ACTION
207
- # ---------------------------------------------------
208
- analyze_btn.click(
209
- fn=analyze_sequence,
210
- inputs=[
211
- image_input,
212
- question_input
213
- ],
214
- outputs=[
215
- json_output,
216
- plot_output,
217
- chatbot_output
218
- ]
219
- )
220
-
221
- # ---------------------------------------------------
222
- # LAUNCH
223
- # ---------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  demo.launch()
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ from PIL import Image
4
+ import pytesseract
5
+ import matplotlib.pyplot as plt
6
+ import matplotlib
7
+ matplotlib.use("Agg")
8
+ from collections import Counter
9
+ import re
10
+
11
+ # ---------------------------------------------------
12
+ # AI MODEL
13
+ # ---------------------------------------------------
14
+ pipe = pipeline(
15
+ "text-generation",
16
+ model="Qwen/Qwen2.5-1.5B-Instruct"
17
+ )
18
+
19
+ # ---------------------------------------------------
20
+ # OCR + DNA ANALYSIS
21
+ # ---------------------------------------------------
22
+ def analyze_sequence(image, question):
23
+
24
+ if image is None:
25
+ return (
26
+ {"error": "No image uploaded. Please upload a DNA/RNA image."},
27
+ None,
28
+ "⚠️ Please upload a DNA/RNA image to begin analysis."
29
+ )
30
+
31
+ # OCR Extraction
32
+ try:
33
+ extracted_text = pytesseract.image_to_string(image)
34
+ except Exception as e:
35
+ return (
36
+ {"error": f"OCR failed: {str(e)}"},
37
+ None,
38
+ "⚠️ Could not read the image. Please try a clearer image."
39
+ )
40
+
41
+ # Clean Sequence — keep only valid nucleotide characters
42
+ sequence = re.sub(r'[^ATCGU]', '', extracted_text.upper())
43
+
44
+ if not sequence:
45
+ sequence_display = "No nucleotide sequence detected in image."
46
+ counts = {}
47
+ confidence_score = 20
48
+ else:
49
+ sequence_display = sequence[:500]
50
+ counts = Counter(sequence)
51
+ confidence_score = min(99, 60 + len(sequence) // 5)
52
+
53
+ # Build prompt
54
+ user_question = question.strip() if question and question.strip() else "Provide a general genomic analysis."
55
+
56
+ prompt = f"""You are VISION-LINK AI, an advanced genomic intelligence system.
57
+
58
+ Sequence: {sequence_display}
59
+
60
+ User Query: {user_question}
61
+
62
+ Provide:
63
+ 1. Sequence interpretation
64
+ 2. Mutation insights
65
+ 3. Diagnostic observations
66
+ 4. Biotechnology recommendations"""
67
+
68
+ try:
69
+ result = pipe(
70
+ prompt,
71
+ max_new_tokens=220,
72
+ do_sample=True,
73
+ temperature=0.7
74
+ )
75
+ full_output = result[0]["generated_text"]
76
+ # Strip the prompt — only keep what the model generated after it
77
+ ai_output = full_output[len(prompt):].strip()
78
+ if not ai_output:
79
+ ai_output = full_output.strip()
80
+ except Exception as e:
81
+ ai_output = f"AI analysis failed: {str(e)}"
82
+
83
+ # JSON-style report
84
+ analysis = {
85
+ "Confidence Score": f"{confidence_score}%",
86
+ "Detected Sequence (first 500 chars)": sequence_display,
87
+ "Sequence Length": len(sequence) if sequence and sequence != "No nucleotide sequence detected in image." else 0,
88
+ "Nucleotide Counts": dict(counts),
89
+ "AI Diagnostic Summary": ai_output
90
+ }
91
+
92
+ # ---------------------------------------------------
93
+ # DARK-THEMED CHART
94
+ # ---------------------------------------------------
95
+ fig = None
96
+ if counts:
97
+ color_map = {
98
+ 'A': '#38bdf8',
99
+ 'T': '#818cf8',
100
+ 'C': '#34d399',
101
+ 'G': '#fb923c',
102
+ 'U': '#f472b6',
103
+ }
104
+ bar_colors = [color_map.get(n, '#94a3b8') for n in counts.keys()]
105
+
106
+ fig, ax = plt.subplots(figsize=(5, 4))
107
+ fig.patch.set_facecolor('#0f172a')
108
+ ax.set_facecolor('#1e293b')
109
+
110
+ bars = ax.bar(counts.keys(), counts.values(), color=bar_colors, width=0.5, zorder=3)
111
+
112
+ for bar in bars:
113
+ ax.text(
114
+ bar.get_x() + bar.get_width() / 2,
115
+ bar.get_height() + 0.3,
116
+ str(int(bar.get_height())),
117
+ ha='center', va='bottom',
118
+ color='white', fontsize=11, fontweight='bold'
119
+ )
120
+
121
+ ax.set_title("Nucleotide Distribution", color='#67e8f9', fontsize=14, fontweight='bold', pad=12)
122
+ ax.set_xlabel("Nucleotide", color='#94a3b8', fontsize=11)
123
+ ax.set_ylabel("Count", color='#94a3b8', fontsize=11)
124
+ ax.tick_params(colors='#cbd5e1')
125
+ ax.spines['bottom'].set_color('#334155')
126
+ ax.spines['left'].set_color('#334155')
127
+ ax.spines['top'].set_visible(False)
128
+ ax.spines['right'].set_visible(False)
129
+ ax.yaxis.grid(True, color='#1e3a5f', linestyle='--', alpha=0.5, zorder=0)
130
+ ax.set_axisbelow(True)
131
+ plt.tight_layout()
132
+
133
+ return analysis, fig, ai_output
134
+
135
+
136
+ # ---------------------------------------------------
137
+ # CUSTOM CSS
138
+ # ---------------------------------------------------
139
+ custom_css = """
140
+ @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@700;900&family=Exo+2:wght@300;400;600&display=swap');
141
+
142
+ body {
143
+ background: linear-gradient(135deg, #020617, #0f172a) !important;
144
+ min-height: 100vh;
145
+ }
146
+
147
+ .gradio-container {
148
+ font-family: 'Exo 2', sans-serif !important;
149
+ max-width: 1200px !important;
150
+ margin: 0 auto !important;
151
+ }
152
+
153
+ .main-title {
154
+ text-align: center;
155
+ font-family: 'Orbitron', monospace;
156
+ font-size: 36px;
157
+ font-weight: 900;
158
+ background: linear-gradient(90deg, #38bdf8, #818cf8, #38bdf8);
159
+ background-size: 200% auto;
160
+ -webkit-background-clip: text;
161
+ -webkit-text-fill-color: transparent;
162
+ background-clip: text;
163
+ animation: shimmer 3s linear infinite;
164
+ margin-bottom: 8px;
165
+ letter-spacing: 2px;
166
+ }
167
+
168
+ @keyframes shimmer {
169
+ 0% { background-position: 0% center; }
170
+ 100% { background-position: 200% center; }
171
+ }
172
+
173
+ .sub-title {
174
+ text-align: center;
175
+ color: #94a3b8;
176
+ margin-bottom: 30px;
177
+ font-size: 15px;
178
+ letter-spacing: 1px;
179
+ }
180
+
181
+ button.primary {
182
+ background: linear-gradient(135deg, #0ea5e9, #6366f1) !important;
183
+ border: none !important;
184
+ border-radius: 10px !important;
185
+ font-family: 'Orbitron', monospace !important;
186
+ font-size: 12px !important;
187
+ font-weight: 700 !important;
188
+ letter-spacing: 1px !important;
189
+ color: white !important;
190
+ padding: 12px 20px !important;
191
+ width: 100% !important;
192
+ box-shadow: 0 0 20px rgba(14, 165, 233, 0.35) !important;
193
+ transition: all 0.3s ease !important;
194
+ }
195
+
196
+ button.primary:hover {
197
+ transform: translateY(-2px) !important;
198
+ box-shadow: 0 0 35px rgba(14, 165, 233, 0.55) !important;
199
+ }
200
+
201
+ footer { visibility: hidden; }
202
+ """
203
+
204
+ # ---------------------------------------------------
205
+ # UI
206
+ # ---------------------------------------------------
207
+ with gr.Blocks(
208
+ theme=gr.themes.Glass(),
209
+ css=custom_css,
210
+ title="VISION-LINK AI"
211
+ ) as demo:
212
+
213
+ gr.HTML("""
214
+ <div class="main-title">🔬 VISION-LINK AI</div>
215
+ <div class="sub-title">Advanced Genomic & Molecular Intelligence · AI-driven Biotechnology Solutions</div>
216
+ """)
217
+
218
+ with gr.Row():
219
+
220
+ with gr.Column(scale=1):
221
+ gr.Markdown("## 🧬 Molecular Input")
222
+ image_input = gr.Image(
223
+ type="pil",
224
+ label="Upload DNA/RNA/Nucleotide Sequence Image (JPEG/PNG)"
225
+ )
226
+ question_input = gr.Textbox(
227
+ lines=4,
228
+ placeholder="e.g. Explain this genetic mutation or compare RNA strands...",
229
+ label="Research Query"
230
+ )
231
+ analyze_btn = gr.Button("⚡ Analyze Sequence", variant="primary")
232
+ gr.Examples(
233
+ examples=[
234
+ ["What is the nucleotide sequence of this image?"],
235
+ ["Explain this genetic mutation."],
236
+ ["Compare these RNA strands."],
237
+ ["Identify abnormalities in this sequence."]
238
+ ],
239
+ inputs=question_input,
240
+ label="💡 Example Queries"
241
+ )
242
+
243
+ with gr.Column(scale=1):
244
+ gr.Markdown("## 🤖 AI Analysis")
245
+ chatbot_output = gr.Textbox(
246
+ lines=18,
247
+ label="AI Molecular Analysis",
248
+ interactive=False
249
+ )
250
+
251
+ with gr.Column(scale=1):
252
+ gr.Markdown("## 📊 Results & Analytics")
253
+ json_output = gr.JSON(label="Genomic Analysis Report")
254
+ plot_output = gr.Plot(label="Nucleotide Distribution")
255
+
256
+ analyze_btn.click(
257
+ fn=analyze_sequence,
258
+ inputs=[image_input, question_input],
259
+ outputs=[json_output, plot_output, chatbot_output]
260
+ )
261
+
262
  demo.launch()