from fastapi import FastAPI, HTTPException, BackgroundTasks, Request from fastapi.responses import HTMLResponse, StreamingResponse from curl_cffi import requests import os import time import hashlib import threading from dotenv import load_dotenv from collections import defaultdict load_dotenv() app = FastAPI() # --- Rate Limiting Configuration --- RATE_LIMIT_REQUESTS = 20 RATE_LIMIT_WINDOW = 60 # 60 seconds rate_limit_data = defaultdict(list) # --- Cache Configuration --- CACHE_DIR = "cache" CACHE_MAX_SIZE = 100 * 1024 * 1024 # 100 MB CACHE_MAX_AGE = 3600 # 1 hour in seconds MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB CACHE_CLEANUP_INTERVAL = 600 # 10 minutes # --- Cache Initialization --- if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) # --- Cache Cleanup Functions --- def clean_cache(): """Cleans the cache directory based on size and age. This function is designed to be run in a background thread. """ while True: try: total_size = 0 files = [] for filename in os.listdir(CACHE_DIR): filepath = os.path.join(CACHE_DIR, filename) if not os.path.isfile(filepath): continue stat = os.stat(filepath) total_size += stat.st_size files.append((filepath, stat.st_mtime, stat.st_size)) # 1. Remove expired files now = time.time() for filepath, mtime, _ in files: if now - mtime > CACHE_MAX_AGE: os.remove(filepath) print(f"Removed expired cache file: {filepath}") # 2. Enforce total cache size limit (LRU) if total_size > CACHE_MAX_SIZE: # Sort files by last modification time (oldest first) files.sort(key=lambda x: x[1]) while total_size > CACHE_MAX_SIZE and files: filepath, _, size = files.pop(0) os.remove(filepath) total_size -= size print(f"Removed old cache file to free space: {filepath}") except Exception as e: print(f"Error during cache cleanup: {e}") time.sleep(CACHE_CLEANUP_INTERVAL) # --- Background Thread for Cache Cleanup --- cache_cleanup_thread = threading.Thread(target=clean_cache, daemon=True) cache_cleanup_thread.start() # --- API Endpoints --- @app.get("/", response_class=HTMLResponse) async def root(): return """
To use the proxy, make a GET request to the following URL:
/{api_key}?url={your_url}
Replace {api_key} with your API key and {your_url} with the URL you want to proxy.
curl -X GET "http://your-hugging-face-space-url/your_api_key?url=https://example.com"