File size: 9,081 Bytes
f73929c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Temporary app.py for debugging Hugging Face Space issues
Replace your current app.py with this file temporarily
"""

import os
import pandas as pd
import faiss
import google.generativeai as genai
import numpy as np
import gradio as gr

def run_all_checks():
    """Run all diagnostic checks and return results"""
    results = []
    
    def add_result(text):
        results.append(text)
        print(text)
    
    add_result("πŸš€ DEBUGGING HUGGING FACE SPACE")
    add_result("=" * 50)
    
    # Environment Check
    add_result("\nπŸ” ENVIRONMENT CHECK")
    add_result("=" * 30)
    
    # Check API key variations
    api_keys = {
        "GOOGLE_API_KEY": os.environ.get("GOOGLE_API_KEY"),
        "gemini_api": os.environ.get("gemini_api"),
        "GEMINI_API_KEY": os.environ.get("GEMINI_API_KEY"),
    }
    
    found_key = None
    for key_name, key_value in api_keys.items():
        if key_value:
            add_result(f"βœ… {key_name}: {key_value[:10]}...")
            found_key = key_value
        else:
            add_result(f"❌ {key_name}: Not found")
    
    if not found_key:
        add_result("❌ No API key found in any expected environment variable")
        return "\n".join(results)
    
    # Test Gemini API
    try:
        genai.configure(api_key=found_key)
        add_result("βœ… Gemini API configured successfully")
    except Exception as e:
        add_result(f"❌ Gemini API configuration failed: {e}")
        return "\n".join(results)
    
    # File Check
    add_result("\nπŸ“ FILE CHECK")
    add_result("=" * 30)
    
    add_result(f"Current directory: {os.getcwd()}")
    add_result(f"Directory contents: {os.listdir('.')}")
    
    files_to_check = [
        "research_chunks.faiss",
        "chunk_metadata.csv",
        "requirements.txt"
    ]
    
    all_files_exist = True
    for file_path in files_to_check:
        if os.path.exists(file_path):
            size = os.path.getsize(file_path)
            add_result(f"βœ… {file_path}: {size:,} bytes")
        else:
            add_result(f"❌ {file_path}: NOT FOUND")
            if file_path in ["research_chunks.faiss", "chunk_metadata.csv"]:
                all_files_exist = False
    
    if not all_files_exist:
        add_result("\n❌ CRITICAL: Missing required data files!")
        add_result("You need to upload:")
        add_result("- research_chunks.faiss (FAISS vector index)")
        add_result("- chunk_metadata.csv (document metadata)")
        return "\n".join(results)
    
    # FAISS Index Check
    add_result("\nπŸ” FAISS INDEX CHECK")
    add_result("=" * 30)
    
    try:
        index = faiss.read_index("research_chunks.faiss")
        add_result(f"βœ… FAISS index loaded: {index.ntotal:,} vectors")
        add_result(f"βœ… Index dimension: {index.d}")
        add_result(f"βœ… Index type: {type(index).__name__}")
    except Exception as e:
        add_result(f"❌ FAISS index loading failed: {e}")
        return "\n".join(results)
    
    # Metadata Check
    add_result("\nπŸ“Š METADATA CHECK")
    add_result("=" * 30)
    
    try:
        metadata = pd.read_csv("chunk_metadata.csv")
        add_result(f"βœ… Metadata loaded: {len(metadata):,} rows")
        add_result(f"βœ… Columns ({len(metadata.columns)}): {list(metadata.columns)[:5]}...")
        add_result(f"βœ… Unique records: {metadata['record_id'].nunique():,}")
        
        # Check for required columns
        required_cols = ['record_id', 'text', 'title']
        missing_cols = [col for col in required_cols if col not in metadata.columns]
        if missing_cols:
            add_result(f"⚠️  Missing required columns: {missing_cols}")
        else:
            add_result("βœ… All required columns present")
        
        # Show sample data
        add_result("\nπŸ“ Sample data:")
        for i, row in metadata.head(2).iterrows():
            add_result(f"Row {i}: {row.get('title', 'No title')}")
            add_result(f"  Text preview: {str(row.get('text', 'No text'))[:100]}...")
        
    except Exception as e:
        add_result(f"❌ Metadata loading failed: {e}")
        return "\n".join(results)
    
    # Embedding API Test
    add_result("\n🧠 EMBEDDING API TEST")
    add_result("=" * 30)
    
    try:
        test_query = "agricultural research methods"
        add_result(f"Testing with query: '{test_query}'")
        
        embed_result = genai.embed_content(
            model="models/embedding-001",
            content=test_query,
            task_type="retrieval_query"
        )
        
        embedding = np.array([embed_result['embedding']], dtype="float32")
        add_result(f"βœ… Embedding created: shape {embedding.shape}")
        add_result(f"βœ… First 5 values: {embedding[0][:5]}")
        
    except Exception as e:
        add_result(f"❌ Embedding API test failed: {e}")
        return "\n".join(results)
    
    # Full Search Test
    add_result("\nπŸ” FULL SEARCH TEST")
    add_result("=" * 30)
    
    try:
        distances, indices = index.search(embedding, k=5)
        add_result(f"βœ… Search completed")
        add_result(f"βœ… Indices: {indices[0]}")
        add_result(f"βœ… Distances: {distances[0]}")
        
        # Check results
        valid_indices = [idx for idx in indices[0] if idx != -1 and idx < len(metadata)]
        add_result(f"βœ… Valid results: {len(valid_indices)}/5")
        
        if valid_indices:
            sample_idx = valid_indices[0]
            sample_row = metadata.iloc[sample_idx]
            similarity = 1 / (1 + distances[0][0])
            add_result(f"\nπŸ“‹ Best match (similarity: {similarity:.3f}):")
            add_result(f"  Title: {sample_row.get('title', 'N/A')}")
            add_result(f"  Text: {str(sample_row.get('text', 'N/A'))[:200]}...")
        
    except Exception as e:
        add_result(f"❌ Full search test failed: {e}")
        return "\n".join(results)
    
    # Environment Info
    add_result("\n🐍 PYTHON ENVIRONMENT")
    add_result("=" * 30)
    
    import sys
    add_result(f"Python version: {sys.version}")
    add_result(f"Platform: {sys.platform}")
    
    try:
        import pkg_resources
        installed = [pkg.project_name for pkg in pkg_resources.working_set]
        required = ['gradio', 'faiss-cpu', 'google-generativeai', 'pandas', 'numpy', 'plotly']
        missing = [pkg for pkg in required if pkg not in installed]
        if missing:
            add_result(f"⚠️  Missing packages: {missing}")
        else:
            add_result("βœ… All required packages installed")
    except:
        add_result("⚠️  Could not check installed packages")
    
    add_result("\nπŸŽ‰ ALL TESTS COMPLETED!")
    add_result("\nIf you see this message, your system should be working!")
    add_result("You can now replace this debug app.py with your original app.py")
    
    return "\n".join(results)

def create_debug_interface():
    """Create a simple Gradio interface for debugging"""
    
    with gr.Blocks(title="Debug Hugging Face Space") as app:
        gr.HTML("""
        <div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #ff6b6b, #4ecdc4); color: white; border-radius: 10px;">
            <h1>πŸ”§ Hugging Face Space Debugger</h1>
            <p>This will help identify why your search isn't working</p>
        </div>
        """)
        
        with gr.Row():
            run_btn = gr.Button("πŸš€ Run Full Diagnostic", variant="primary", size="lg")
        
        with gr.Row():
            output = gr.Textbox(
                label="Diagnostic Results",
                lines=30,
                max_lines=50,
                interactive=False,
                show_copy_button=True
            )
        
        # Auto-run diagnostics on load
        app.load(run_all_checks, outputs=output)
        run_btn.click(run_all_checks, outputs=output)
        
        gr.HTML("""
        <div style="margin-top: 20px; padding: 15px; background: #f0f8ff; border-radius: 5px;">
            <h3>πŸ“‹ What This Checks:</h3>
            <ul>
                <li><strong>API Key:</strong> Verifies Google Gemini API key is set correctly</li>
                <li><strong>Files:</strong> Checks if FAISS index and metadata CSV exist</li>
                <li><strong>Data:</strong> Validates file contents and structure</li>
                <li><strong>Search:</strong> Tests the complete search pipeline</li>
                <li><strong>Environment:</strong> Verifies Python packages and setup</li>
            </ul>
            <p><strong>Next Steps:</strong> Once all tests pass, replace this debug app.py with your original app.py</p>
        </div>
        """)
    
    return app

if __name__ == "__main__":
    # Run diagnostics in console first
    print("Running initial diagnostics...")
    run_all_checks()
    
    # Launch Gradio interface
    app = create_debug_interface()
    app.launch(
        share=True,
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True
    )