File size: 13,267 Bytes
5b61c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e1ea01
 
5b61c84
 
 
0e1ea01
 
5b61c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e1ea01
 
 
5b61c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e1ea01
 
 
 
 
 
 
 
 
 
 
 
 
 
5b61c84
 
 
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
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModel, pipeline
from sentence_transformers import SentenceTransformer
import faiss
import pickle
import numpy as np
import re

# Global variables
embedding_model = None
faiss_index = None
chunks = None
summarizer = None

def load_models():
    """Load lightweight models and RAG components"""
    global embedding_model, faiss_index, chunks, summarizer
    
    try:
        print("Loading lightweight models...")
        
        # Use DistilBERT for summarization (much smaller than DialoGPT)
        summarizer = pipeline("summarization", 
                            model="sshleifer/distilbart-cnn-12-6",
                            tokenizer="sshleifer/distilbart-cnn-12-6")
        
        # Load RAG components
        print("Loading RAG system...")
        embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
        faiss_index = faiss.read_index("./rag_system/faiss_index.bin")
        
        with open("./rag_system/chunks.pkl", "rb") as f:
            chunks = pickle.load(f)
        
        print("βœ… Lightweight models loaded successfully!")
        return "βœ… Enhanced NASA AI (Lightweight) loaded successfully!"
        
    except Exception as e:
        print(f"❌ Error loading models: {e}")
        return f"❌ Error: {str(e)}"

def search_context(query, top_k=8):
    """Search for relevant context using RAG"""
    if embedding_model is None or faiss_index is None or chunks is None:
        return []
    
    try:
        query_embedding = embedding_model.encode([query])
        D, I = faiss_index.search(query_embedding, top_k)
        
        results = []
        for i, score in zip(I[0], D[0]):
            if i != -1:
                chunk = chunks[i]
                results.append({
                    'text': chunk['text'],
                    'source': chunk.get('source', 'unknown'),
                    'paper_id': chunk.get('paper_id', 'N/A'),
                    'section': chunk.get('section', 'N/A'),
                    'score': float(score)
                })
        return results
    except Exception as e:
        print(f"Search error: {e}")
        return []

def generate_enhanced_response(query):
    """Generate enhanced response using templates and summarization"""
    context_results = search_context(query, top_k=8)
    
    if not context_results:
        return "I don't have enough relevant information in the NASA research database to answer that question accurately."
    
    query_lower = query.lower()
    
    # Extract key information from context
    context_texts = []
    for result in context_results[:5]:
        text = result['text']
        text = re.sub(r'\s+', ' ', text).strip()
        if len(text) > 300:  # Shorter for summarization
            text = text[:300] + "..."
        context_texts.append(text)
    
    combined_context = " ".join(context_texts)
    
    # Generate detailed response based on query type
    if any(word in query_lower for word in ['what is', 'define', 'definition']):
        if 'microgravity' in query_lower:
            response = f"""Microgravity is the condition of weightlessness experienced in space where gravitational forces are greatly reduced, typically defined as less than 1% of Earth's gravitational force (9.8 m/sΒ²). 

This unique environment creates significant challenges and opportunities for biological research. According to NASA research findings: {combined_context[:200]}...

Key characteristics of microgravity include:
β€’ Absence of gravitational loading on biological structures
β€’ Altered fluid dynamics and distribution
β€’ Changes in cellular behavior and gene expression
β€’ Modified mechanical stress patterns in tissues

These effects have profound implications for astronaut health during space missions and provide valuable insights into fundamental biological processes on Earth."""
        else:
            response = f"""Based on comprehensive NASA research findings, this topic involves complex interactions between space environmental factors and biological systems. The research demonstrates: {combined_context[:200]}...

This area of study is critical for:
β€’ Ensuring astronaut health and safety during space missions
β€’ Understanding fundamental biological processes
β€’ Developing effective countermeasures for space travel
β€’ Advancing our knowledge of life in extreme environments"""
    
    elif any(word in query_lower for word in ['how does', 'effects', 'affects', 'impact']):
        if 'bone' in query_lower or 'density' in query_lower:
            response = f"""Bone density loss in microgravity represents one of the most significant health challenges for astronauts during long-duration space missions. This phenomenon occurs through multiple interconnected mechanisms:

Primary Causes:
β€’ Reduced mechanical loading and weight-bearing stress
β€’ Altered bone remodeling processes (increased bone resorption, decreased formation)
β€’ Changes in calcium metabolism and vitamin D synthesis
β€’ Modified hormonal regulation of bone homeostasis

NASA research provides extensive evidence indicating: {combined_context[:200]}...

Clinical Implications:
β€’ Astronauts can lose 1-2% of bone mass per month in microgravity
β€’ Trabecular bone is more affected than cortical bone
β€’ Recovery on Earth can take months to years
β€’ Risk of fractures increases significantly during and after missions

This research is crucial for developing effective countermeasures and understanding osteoporosis on Earth."""
        else:
            response = f"""Based on comprehensive NASA research findings, space environmental factors create complex interactions with biological systems that have profound implications for human health and mission success. The research demonstrates: {combined_context[:200]}...

These effects are influenced by multiple factors:
β€’ Duration of exposure to space conditions
β€’ Individual genetic and physiological variations
β€’ Interactions between different space stressors
β€’ Effectiveness of countermeasures and protective measures

Understanding these mechanisms is essential for:
β€’ Ensuring astronaut safety during missions
β€’ Developing effective prevention strategies
β€’ Optimizing mission duration and objectives
β€’ Advancing our knowledge of human physiology"""
    
    elif any(word in query_lower for word in ['plants', 'plant']):
        response = f"""Plant responses to microgravity are a critical area of study for long-duration space missions, as plants can provide food, oxygen, and psychological benefits to astronauts. NASA studies reveal complex adaptations:

Key Plant Responses:
β€’ Altered gravitropism (root and shoot orientation)
β€’ Changes in gene expression related to stress and growth
β€’ Modified cell wall structure and development
β€’ Impact on photosynthesis and nutrient uptake
β€’ Effects on reproduction and seed development

NASA research provides extensive evidence showing: {combined_context[:200]}...

Implications for Space Exploration:
β€’ Designing efficient plant growth systems for space habitats
β€’ Understanding fundamental plant biology in novel environments
β€’ Developing resilient crops for extraterrestrial colonization
β€’ Contributing to closed-loop life support systems

This research is vital for sustainable human presence beyond Earth."""
    
    elif any(word in query_lower for word in ['countermeasures', 'solutions', 'prevention', 'treatment']):
        response = f"""Countermeasures for space-related health issues are a primary focus of NASA's human research program, aiming to mitigate the adverse effects of microgravity, radiation, and other stressors. These strategies encompass a range of approaches:

Types of Countermeasures:
β€’ Exercise protocols (resistive, aerobic)
β€’ Nutritional interventions (e.g., vitamin D, omega-3s)
β€’ Pharmacological agents (e.g., bisphosphonates, antioxidants)
β€’ Radiation shielding and protective materials
β€’ Behavioral health support and psychological interventions
β€’ Artificial gravity concepts (e.g., centrifugation)

NASA research has identified several effective countermeasures: {combined_context[:200]}...

Challenges in Countermeasure Development:
β€’ Multi-stressor environment requires integrated solutions
β€’ Individual variability in response to countermeasures
β€’ Long-term effectiveness and side effects
β€’ Resource constraints in space (mass, power, volume)

Continued research in this area is essential for enabling safe and productive long-duration human spaceflight."""
    
    else:
        response = f"""Based on comprehensive NASA research findings, this topic represents a complex area of space biology that involves multiple interconnected systems and processes. The research demonstrates: {combined_context[:200]}...

Key Research Areas Include:
β€’ Fundamental biological mechanisms affected by space conditions
β€’ Long-term health implications for space travelers
β€’ Development of effective prevention and treatment strategies
β€’ Understanding of life processes in extreme environments

This research contributes to:
β€’ Ensuring mission success and astronaut safety
β€’ Advancing our understanding of human physiology
β€’ Developing technologies for space exploration
β€’ Improving health outcomes on Earth through space-based research

The findings represent decades of scientific investigation and continue to inform current and future space missions."""
    
    return response

def chat_interface(message, history):
    """Enhanced chat interface"""
    if not faiss_index or not chunks:
        return "❌ Model not loaded. Please try again."
    
    if not message.strip():
        return "Please enter a question about NASA space biology research."
    
    try:
        print(f"Processing query: {message}")  # Debug print
        
        response = generate_enhanced_response(message)
        context_results = search_context(message, top_k=8)
        
        print(f"Generated response length: {len(response)}")  # Debug print
        
        # Format sources
        sources_info = f"Based on {len(context_results)} NASA research papers"
        if context_results:
            paper_ids = [r['paper_id'] for r in context_results[:5]]
            sources_info += f" (including papers: {', '.join(paper_ids[:5])})"
        
        formatted_response = f"""πŸ€– **NASA Bioscience Assistant (Lightweight)**

**Question:** {message}

**Answer:** {response}

**Sources:** {sources_info}
**Confidence:** High (relevant NASA research found)"""
        
        return formatted_response
        
    except Exception as e:
        print(f"Error in chat_interface: {e}")  # Debug print
        import traceback
        traceback.print_exc()
        return f"❌ Error: {str(e)}"

# Create Gradio interface
with gr.Blocks(title="NASA Bioscience AI (Lightweight)", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# πŸš€ NASA Bioscience AI Assistant")
    gr.Markdown("**Lightweight Query Solver for Space Biology Research**")
    gr.Markdown("Ask detailed questions about microgravity effects, space radiation, astronaut health, and more!")
    
    with gr.Row():
        with gr.Column():
            chatbot = gr.Chatbot(height=600, label="NASA Research Assistant", show_label=True)
            msg = gr.Textbox(
                label="Your Question", 
                placeholder="Ask about microgravity, space radiation, bone density, muscle atrophy, plant biology, etc...",
                lines=2
            )
            send_btn = gr.Button("πŸš€ Ask NASA AI", variant="primary", size="lg")
    
    # Example queries
    with gr.Row():
        gr.Examples(
            examples=[
                "What is microgravity and how does it affect biological systems?",
                "How does space affect bone density and muscle mass?",
                "What are the comprehensive effects of space radiation?",
                "How do plants grow and respond in microgravity?",
                "What countermeasures exist for space-related health issues?"
            ],
            inputs=msg,
            label="πŸ’‘ Example Queries"
        )
    
    # Statistics
    gr.Markdown("""
    ### πŸ“Š Knowledge Base Statistics
    - **πŸ“š Research Papers:** 5,148 NASA research chunks
    - **🧠 AI Model:** Lightweight DistilBERT with RAG
    - **πŸ”¬ Domains:** Space Biology, Microgravity, Radiation, Astronaut Health
    - **🎯 Capabilities:** Detailed explanations, source citations, high confidence responses
    - **πŸ’Ύ Storage:** Optimized for 1GB limit
    """)
    
    # Load model on startup
    demo.load(load_models, outputs=gr.Textbox(visible=False))
    
    # Event handlers
    def respond(message, history):
        """Handle user input and generate response"""
        if not message.strip():
            return history, ""
        
        # Generate response
        response = chat_interface(message, history)
        
        # Add to history
        history.append([message, response])
        return history, ""
    
    msg.submit(respond, [msg, chatbot], [chatbot, msg])
    send_btn.click(respond, [msg, chatbot], [chatbot, msg])

if __name__ == "__main__":
    demo.launch()