#!/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("""
This will help identify why your search isn't working
Next Steps: Once all tests pass, replace this debug app.py with your original app.py