Spaces:
Sleeping
Sleeping
File size: 6,069 Bytes
62cb8f8 cee0f63 62cb8f8 | 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 | """
Public-facing loader app for Daily Paper Reader.
This app downloads and executes the main application from a private HF Space.
"""
import os
import sys
import importlib.util
from pathlib import Path
from huggingface_hub import snapshot_download
# Configuration - UPDATE THIS WITH YOUR PRIVATE SPACE REPO ID
PRIVATE_SPACE_REPO = "ml-stuff01/daily_paper_reader_code" # e.g., "ml-stuff01/daily-paper-reader-code"
CACHE_DIR = Path("/tmp/private_space_cache")
def setup_cache_directory():
"""Setup and return cache directory for private space files."""
CACHE_DIR.mkdir(exist_ok=True)
print(f"β Cache directory created: {CACHE_DIR}")
return CACHE_DIR
def download_private_space():
"""Download the entire private space repository."""
try:
# Check for HF token
hf_token = os.getenv("HF_TOKEN")
if not hf_token:
print("β HF_TOKEN environment variable is not set!")
print("To fix this:")
print(" 1. Go to https://huggingface.co/settings/tokens")
print(" 2. Create a token with 'read' access")
print(" 3. Add it as a secret named 'HF_TOKEN' in your Space settings")
print(" 4. Or set it locally: export HF_TOKEN='your_token_here'")
return False
print(f"π₯ Downloading private space from {PRIVATE_SPACE_REPO}...")
print(f"π Using authentication token (length: {len(hf_token)} chars)")
snapshot_download(
repo_id=PRIVATE_SPACE_REPO,
repo_type="space",
local_dir=CACHE_DIR,
token=hf_token
)
print("β Private space downloaded successfully!")
return True
except Exception as e:
print(f"β Error downloading private space: {str(e)}")
print("\nTroubleshooting:")
print(f" 1. Verify the space '{PRIVATE_SPACE_REPO}' exists and is spelled correctly")
print(" 2. Ensure your HF token has access to this private space")
print(" 3. Check that the token has 'read' permissions")
print(f" 4. Try accessing the space directly: https://huggingface.co/spaces/{PRIVATE_SPACE_REPO}")
return False
def install_requirements():
"""Install requirements from the private space if requirements.txt exists."""
requirements_path = CACHE_DIR / "requirements.txt"
if not requirements_path.exists():
print("βΉοΈ No requirements.txt found in private space, skipping installation")
return True
try:
print(f"π¦ Installing dependencies from {requirements_path}...")
import subprocess
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", str(requirements_path)],
capture_output=True,
text=True,
timeout=300 # 5 minute timeout
)
if result.returncode == 0:
print("β Dependencies installed successfully!")
return True
else:
print(f"β οΈ Warning during dependency installation:")
print(result.stderr)
print("Continuing anyway - some dependencies might be missing...")
return True # Continue even if some packages fail
except subprocess.TimeoutExpired:
print("β οΈ Dependency installation timed out. Continuing anyway...")
return True
except Exception as e:
print(f"β οΈ Error installing dependencies: {str(e)}")
print("Continuing anyway - some dependencies might be missing...")
return True # Continue even on error
def load_and_run_app():
"""Load the main application from the private space and run it."""
try:
# Path to the main app file in the private space cache
app_path = CACHE_DIR / "app.py"
if not app_path.exists():
print(f"β App file not found at {app_path}")
return False
print(f"π Loading application from {app_path}...")
# Add the cache directory to Python path so imports work
sys.path.insert(0, str(CACHE_DIR))
# Change to the cache directory so relative paths work
os.chdir(str(CACHE_DIR))
# Load the module dynamically
spec = importlib.util.spec_from_file_location("app_main", app_path)
app_module = importlib.util.module_from_spec(spec)
# Execute the module - this will start the Flask server
# The exec_module will block if the app runs a server
spec.loader.exec_module(app_module)
# If we get here, the module loaded but didn't start a blocking server
# Try to find and run the Flask app
if hasattr(app_module, 'app'):
print("β Flask app found, starting server...")
port = int(os.getenv('PORT', 7860))
app_module.app.run(host='0.0.0.0', port=port, debug=False)
else:
print("β Application module loaded successfully!")
return True
except Exception as e:
print(f"β Error loading application: {str(e)}")
import traceback
traceback.print_exc()
return False
if __name__ == "__main__":
print("=" * 60)
print("π Daily Paper Reader")
print("=" * 60)
# Step 1: Setup cache directory
setup_cache_directory()
# Step 2: Download private space
if not download_private_space():
print("\nβ Failed to download private space. Exiting.")
sys.exit(1)
# Step 3: Install requirements from private space
if not install_requirements():
print("\nβ Failed to install requirements. Exiting.")
sys.exit(1)
# Step 4: Load and run the app (this should block if it starts a server)
if not load_and_run_app():
print("\nβ Failed to load application. Exiting.")
sys.exit(1)
# If we reach here, the app finished without error
# This shouldn't normally happen if the app runs a server
|