Spaces:
Sleeping
Sleeping
Commit ·
11256ba
1
Parent(s): 609c209
refactor: migrate architecture to fastapi for hugging face spaces deployment
Browse filesFiles changed (3)
- Dockerfile+27-4
- main.pyAdded+57
- requirements.txt+2
1234FROM nginx:alpineCOPY . /usr/share/nginx/htmlEXPOSE 80CMD ["nginx", "-g", "daemon off;"]123456789101112131415161718192021222324252627FROM mcr.microsoft.com/playwright/python:v1.42.0-jammy# Create the user required by Hugging Face Spaces (user ID 1000)RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \PATH=/home/user/.local/bin:$PATHWORKDIR $HOME/app# Install Python dependencies first (for caching)COPY --chown=user:user requirements.txt $HOME/app/RUN pip install --no-cache-dir -r requirements.txt# Install Playwright browsers (if not already fully packaged)RUN playwright install chromium# Copy the rest of the applicationCOPY --chown=user:user . $HOME/app/# Ensure the cache directory exists and is writableRUN mkdir -p $HOME/app/assets/cache_png# Hugging Face Spaces route traffic to port 7860EXPOSE 7860# Run the FastAPI serverCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import asyncioimport osfrom contextlib import asynccontextmanagerfrom fastapi import FastAPIfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponseimport logging
from scripts import scrapefrom scripts import scrape_crypto
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
async def background_scraper_loop(): logger.info("Background scraper loop started.") while True: try: logger.info("Running market scraper...") await scrape.run_async() logger.info("Running crypto scraper...") # Crypto scraper is synchronous, so we run it in a thread to prevent blocking await asyncio.to_thread(scrape_crypto.run) logger.info("Scraping cycle complete. Sleeping for 10 minutes.") except Exception as e: logger.error(f"Error during scraping cycle: {e}") # Sleep for 10 minutes (600 seconds) await asyncio.sleep(600)
@asynccontextmanagerasync def lifespan(app: FastAPI): # Startup: Start the background task task = asyncio.create_task(background_scraper_loop()) yield # Shutdown: Cancel the task task.cancel()
app = FastAPI(lifespan=lifespan)
# Ensure cache directory exists before mountingos.makedirs('assets/cache_png', exist_ok=True)
# Mount directories as static filesapp.mount("/assets", StaticFiles(directory="assets"), name="assets")app.mount("/css", StaticFiles(directory="css"), name="css")app.mount("/src", StaticFiles(directory="src"), name="src")
@app.get("/")async def root(): return FileResponse("index.html")
if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=7860)1playwright==1.42.0123playwright==1.42.0fastapi>=0.100.0uvicorn>=0.23.0
Dockerfile+27-4
main.pyAdded+57
requirements.txt+2