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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#!/usr/bin/env python3
"""
Comprehensive test script for Enhanced Gaza First Aid RAG Assistant
Tests all major components and validates improvements
"""

import os
import sys
import time
import logging
import traceback
from pathlib import Path
import asyncio

# Configure logging for testing
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def test_imports():
    """Test all required imports"""
    print("πŸ” Testing imports...")
    
    try:
        import torch
        print(f"βœ… PyTorch: {torch.__version__}")
        
        import transformers
        print(f"βœ… Transformers: {transformers.__version__}")
        
        import sentence_transformers
        print(f"βœ… Sentence Transformers: {sentence_transformers.__version__}")
        
        import faiss
        print(f"βœ… FAISS: {faiss.__version__}")
        
        import gradio as gr
        print(f"βœ… Gradio: {gr.__version__}")
        
        from llama_index.core import Document
        print("βœ… LlamaIndex Core")
        
        from llama_index.vector_stores.faiss import FaissVectorStore
        print("βœ… LlamaIndex FAISS")
        
        from llama_index.embeddings.huggingface import HuggingFaceEmbedding
        print("βœ… LlamaIndex HuggingFace Embeddings")
        
        import PyPDF2
        print(f"βœ… PyPDF2: {PyPDF2.__version__}")
        
        return True
        
    except ImportError as e:
        print(f"❌ Import error: {e}")
        return False

def test_data_availability():
    """Test if medical data is available"""
    print("\nπŸ“ Testing data availability...")
    
    data_dir = Path("./data")
    if not data_dir.exists():
        print("❌ Data directory not found")
        return False
    
    pdf_files = list(data_dir.glob("*.pdf"))
    txt_files = list(data_dir.glob("*.txt"))
    
    print(f"βœ… Found {len(pdf_files)} PDF files")
    print(f"βœ… Found {len(txt_files)} text files")
    
    if len(pdf_files) == 0 and len(txt_files) == 0:
        print("❌ No medical documents found")
        return False
    
    # Show sample files
    for i, pdf_file in enumerate(pdf_files[:3]):
        size_mb = pdf_file.stat().st_size / (1024 * 1024)
        print(f"   πŸ“„ {pdf_file.name} ({size_mb:.1f} MB)")
    
    return True

def test_embedding_model():
    """Test embedding model loading and functionality"""
    print("\n🧠 Testing embedding model...")
    
    try:
        from llama_index.embeddings.huggingface import HuggingFaceEmbedding
        
        # Test higher-dimensional model
        print("Loading all-mpnet-base-v2 (768-dim)...")
        embedding_model = HuggingFaceEmbedding(
            model_name="sentence-transformers/all-mpnet-base-v2",
            device='cpu',
            embed_batch_size=2
        )
        
        # Test embedding generation
        test_text = "How to treat burns with limited water supply?"
        start_time = time.time()
        embedding = embedding_model.get_text_embedding(test_text)
        embedding_time = time.time() - start_time
        
        print(f"βœ… Embedding dimension: {len(embedding)}")
        print(f"βœ… Embedding time: {embedding_time:.2f}s")
        print(f"βœ… Sample embedding values: {embedding[:5]}")
        
        return True, embedding_model
        
    except Exception as e:
        print(f"❌ Embedding model error: {e}")
        traceback.print_exc()
        return False, None

def test_faiss_indexing():
    """Test FAISS indexing functionality"""
    print("\nπŸ” Testing FAISS indexing...")
    
    try:
        import faiss
        import numpy as np
        
        # Test different index types
        dimension = 768
        
        # Test flat index
        flat_index = faiss.IndexFlatL2(dimension)
        print(f"βœ… Created IndexFlatL2 (dimension: {dimension})")
        
        # Test IVF index
        nlist = 10  # Small for testing
        quantizer = faiss.IndexFlatL2(dimension)
        ivf_index = faiss.IndexIVFFlat(quantizer, dimension, nlist)
        print(f"βœ… Created IndexIVFFlat (clusters: {nlist})")
        
        # Test with sample data
        sample_vectors = np.random.random((50, dimension)).astype('float32')
        
        # Train IVF index
        ivf_index.train(sample_vectors)
        print("βœ… IVF index training completed")
        
        # Add vectors
        flat_index.add(sample_vectors)
        ivf_index.add(sample_vectors)
        print(f"βœ… Added {len(sample_vectors)} vectors to indices")
        
        # Test search
        query_vector = np.random.random((1, dimension)).astype('float32')
        
        start_time = time.time()
        flat_distances, flat_indices = flat_index.search(query_vector, 5)
        flat_time = time.time() - start_time
        
        start_time = time.time()
        ivf_distances, ivf_indices = ivf_index.search(query_vector, 5)
        ivf_time = time.time() - start_time
        
        print(f"βœ… Flat search time: {flat_time:.4f}s")
        print(f"βœ… IVF search time: {ivf_time:.4f}s")
        print(f"βœ… Speed improvement: {flat_time/ivf_time:.2f}x")
        
        return True
        
    except Exception as e:
        print(f"❌ FAISS indexing error: {e}")
        traceback.print_exc()
        return False

def test_knowledge_base():
    """Test knowledge base initialization and search"""
    print("\nπŸ“š Testing knowledge base...")
    
    try:
        # Import the enhanced system
        sys.path.append('.')
        from enhanced_gaza_rag_app import EnhancedGazaKnowledgeBase
        
        # Initialize knowledge base
        print("Initializing knowledge base...")
        kb = EnhancedGazaKnowledgeBase(data_dir="./data")
        
        start_time = time.time()
        kb.initialize()
        init_time = time.time() - start_time
        
        print(f"βœ… Knowledge base initialized in {init_time:.2f}s")
        print(f"βœ… Chunks created: {len(kb.chunk_metadata)}")
        
        # Test search functionality
        test_queries = [
            "How to treat burns?",
            "Managing bleeding wounds",
            "Signs of infection",
            "Emergency care for children"
        ]
        
        for query in test_queries:
            start_time = time.time()
            results = kb.search(query, k=3)
            search_time = time.time() - start_time
            
            print(f"βœ… Query: '{query}' -> {len(results)} results in {search_time:.3f}s")
            
            if results:
                best_result = results[0]
                print(f"   πŸ“„ Best match: {best_result.get('source', 'unknown')}")
                print(f"   🎯 Score: {best_result.get('score', 0):.3f}")
                print(f"   πŸ₯ Priority: {best_result.get('medical_priority', 'general')}")
        
        return True, kb
        
    except Exception as e:
        print(f"❌ Knowledge base error: {e}")
        traceback.print_exc()
        return False, None

def test_llm_loading():
    """Test LLM loading and inference"""
    print("\nπŸ€– Testing LLM loading...")
    
    try:
        from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, pipeline
        import torch
        
        model_name = "microsoft/Phi-3-mini-4k-instruct"
        print(f"Loading {model_name}...")
        
        # Test quantization config
        quantization_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_compute_dtype=torch.float16,
            bnb_4bit_use_double_quant=True,
            bnb_4bit_quant_type="nf4"
        )
        
        start_time = time.time()
        
        tokenizer = AutoTokenizer.from_pretrained(
            model_name,
            trust_remote_code=True
        )
        
        if tokenizer.pad_token is None:
            tokenizer.pad_token = tokenizer.eos_token
        
        model = AutoModelForCausalLM.from_pretrained(
            model_name,
            quantization_config=quantization_config,
            device_map="auto",
            trust_remote_code=True,
            torch_dtype=torch.float16,
            low_cpu_mem_usage=True
        )
        
        loading_time = time.time() - start_time
        print(f"βœ… Model loaded in {loading_time:.2f}s")
        
        # Test pipeline creation
        generation_pipeline = pipeline(
            "text-generation",
            model=model,
            tokenizer=tokenizer,
            device_map="auto",
            torch_dtype=torch.float16,
            return_full_text=False
        )
        
        print("βœ… Generation pipeline created")
        
        # Test inference
        test_prompt = "How to treat a burn injury: "
        start_time = time.time()
        
        response = generation_pipeline(
            test_prompt,
            max_new_tokens=50,
            temperature=0.2,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id
        )
        
        inference_time = time.time() - start_time
        
        if response and len(response) > 0:
            generated_text = response[0]['generated_text']
            print(f"βœ… Inference completed in {inference_time:.2f}s")
            print(f"βœ… Generated text: {generated_text[:100]}...")
        else:
            print("❌ No response generated")
            return False
        
        return True
        
    except Exception as e:
        print(f"❌ LLM loading error: {e}")
        traceback.print_exc()
        return False

def test_full_system():
    """Test the complete enhanced system"""
    print("\nπŸš€ Testing complete enhanced system...")
    
    try:
        # Import the enhanced system
        from enhanced_gaza_rag_app import initialize_enhanced_system, process_medical_query_with_progress
        
        print("Initializing complete system...")
        start_time = time.time()
        system = initialize_enhanced_system()
        init_time = time.time() - start_time
        
        print(f"βœ… Complete system initialized in {init_time:.2f}s")
        
        # Test queries
        test_queries = [
            "How to treat severe burns when water is limited?",
            "Managing gunshot wounds with basic supplies",
            "Signs of wound infection to watch for"
        ]
        
        for query in test_queries:
            print(f"\nπŸ” Testing query: '{query}'")
            
            start_time = time.time()
            response, metadata, status = process_medical_query_with_progress(query)
            query_time = time.time() - start_time
            
            print(f"βœ… Query processed in {query_time:.2f}s")
            print(f"πŸ“ Response length: {len(response)} characters")
            print(f"πŸ“Š Metadata: {metadata}")
            print(f"πŸ›‘οΈ Status: {status}")
            
            # Check response quality
            if len(response) > 50 and "error" not in response.lower():
                print("βœ… Response quality: Good")
            else:
                print("⚠️ Response quality: Needs improvement")
        
        return True
        
    except Exception as e:
        print(f"❌ Full system test error: {e}")
        traceback.print_exc()
        return False

def test_ui_components():
    """Test UI components and interface"""
    print("\n🎨 Testing UI components...")
    
    try:
        from enhanced_ui_gaza_rag_app import create_advanced_gradio_interface
        
        print("Creating advanced Gradio interface...")
        start_time = time.time()
        interface = create_advanced_gradio_interface()
        ui_time = time.time() - start_time
        
        print(f"βœ… UI created in {ui_time:.2f}s")
        print("βœ… Advanced CSS styling applied")
        print("βœ… Progress indicators configured")
        print("βœ… Gaza-specific theming applied")
        print("βœ… Interactive elements configured")
        
        return True
        
    except Exception as e:
        print(f"❌ UI components error: {e}")
        traceback.print_exc()
        return False

def run_performance_benchmark():
    """Run performance benchmarks"""
    print("\n⚑ Running performance benchmarks...")
    
    try:
        from enhanced_gaza_rag_app import initialize_enhanced_system
        
        system = initialize_enhanced_system()
        
        # Benchmark queries
        benchmark_queries = [
            "How to treat burns?",
            "Managing bleeding wounds",
            "Signs of infection",
            "Emergency care procedures",
            "Trauma management protocols"
        ]
        
        total_time = 0
        successful_queries = 0
        
        for i, query in enumerate(benchmark_queries):
            try:
                start_time = time.time()
                result = system.generate_response(query)
                query_time = time.time() - start_time
                
                total_time += query_time
                successful_queries += 1
                
                print(f"βœ… Query {i+1}: {query_time:.2f}s")
                
            except Exception as e:
                print(f"❌ Query {i+1} failed: {e}")
        
        if successful_queries > 0:
            avg_time = total_time / successful_queries
            print(f"\nπŸ“Š Performance Summary:")
            print(f"   Average query time: {avg_time:.2f}s")
            print(f"   Successful queries: {successful_queries}/{len(benchmark_queries)}")
            print(f"   Success rate: {successful_queries/len(benchmark_queries)*100:.1f}%")
        
        return True
        
    except Exception as e:
        print(f"❌ Performance benchmark error: {e}")
        traceback.print_exc()
        return False

def main():
    """Run comprehensive test suite"""
    print("πŸ§ͺ Enhanced Gaza First Aid RAG Assistant - Comprehensive Test Suite")
    print("=" * 70)
    
    test_results = {}
    
    # Run all tests
    tests = [
        ("Import Dependencies", test_imports),
        ("Data Availability", test_data_availability),
        ("Embedding Model", lambda: test_embedding_model()[0]),
        ("FAISS Indexing", test_faiss_indexing),
        ("Knowledge Base", lambda: test_knowledge_base()[0]),
        ("LLM Loading", test_llm_loading),
        ("Full System", test_full_system),
        ("UI Components", test_ui_components),
        ("Performance Benchmark", run_performance_benchmark)
    ]
    
    passed_tests = 0
    total_tests = len(tests)
    
    for test_name, test_func in tests:
        print(f"\n{'='*50}")
        print(f"πŸ§ͺ Running: {test_name}")
        print(f"{'='*50}")
        
        try:
            result = test_func()
            test_results[test_name] = result
            
            if result:
                passed_tests += 1
                print(f"βœ… {test_name}: PASSED")
            else:
                print(f"❌ {test_name}: FAILED")
                
        except Exception as e:
            test_results[test_name] = False
            print(f"❌ {test_name}: ERROR - {e}")
    
    # Final summary
    print(f"\n{'='*70}")
    print("🏁 TEST SUMMARY")
    print(f"{'='*70}")
    
    for test_name, result in test_results.items():
        status = "βœ… PASSED" if result else "❌ FAILED"
        print(f"{test_name:.<40} {status}")
    
    print(f"\nOverall Results: {passed_tests}/{total_tests} tests passed")
    print(f"Success Rate: {passed_tests/total_tests*100:.1f}%")
    
    if passed_tests == total_tests:
        print("\nπŸŽ‰ ALL TESTS PASSED! Enhanced system is ready for deployment.")
    elif passed_tests >= total_tests * 0.8:
        print("\n⚠️ Most tests passed. System is functional with minor issues.")
    else:
        print("\n🚨 Multiple test failures. System needs attention before deployment.")
    
    return passed_tests == total_tests

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)