# app.py # from flask import Flask,request,jsonify # from flask_cors import CORS # app = Flask(__name__) # cors = CORS(app, resources={r"*": {"origins": "*"}}) from fastapi import FastAPI import uvicorn import logging import time # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # loading the data from the csv file to apandas dataframe app = FastAPI(title="Rainwater Harvesting API", version="1.0.0") from huggingface_hub import login from huggingface_hub import hf_hub_download from RoofTopCalculation import RooftTopCalculation from RainFallModel import calculate_rainfall import os # Use /app as primary cache directory for Hugging Face Spaces cache_dir = '/app/hf_cache' # Fallback cache directory if /app is not writable fallback_cache_dir = '/tmp/hf_cache' os.makedirs(cache_dir, exist_ok=True) os.makedirs(fallback_cache_dir, exist_ok=True) repo_id = "Navanihk/rainfallPrediction" import pandas as pd @app.get("/") def read_root(): return {"message": "Rainwater Harvesting API", "status": "running", "version": "1.0"} @app.get("/health") def health_check(): return {"status": "healthy", "timestamp": pd.Timestamp.now().isoformat()} @app.get("/logs") def get_logs(): return {"logs": "Application is running normally", "status": "ok"} @app.post('/api/roofTopCalculation') def roof_top_calculation(data: dict): start_time = time.time() logger.info(f"Received roof top calculation request for location: {data.get('location', 'Unknown')}") try: # Try to download from Hugging Face Hub with fallback cache directories try: csv_path = hf_hub_download(repo_id=repo_id, filename="rainfall_updated.csv", cache_dir=cache_dir) logger.info("Successfully downloaded rainfall data from Hugging Face Hub") except PermissionError: # Try fallback cache directory csv_path = hf_hub_download(repo_id=repo_id, filename="rainfall_updated.csv", cache_dir=fallback_cache_dir) logger.info("Successfully downloaded rainfall data using fallback cache directory") RainFallData = pd.read_csv(csv_path) logger.info(f"Loaded rainfall data with {len(RainFallData)} records") except Exception as e: logger.error(f"Error downloading from Hugging Face Hub: {e}") # Fallback: use a basic DataFrame with essential data for calculations # This ensures the API continues to work even if the download fails RainFallData = pd.DataFrame({ 'state': ['Delhi', 'Maharashtra', 'Karnataka', 'Tamil Nadu'], 'district': ['New Delhi', 'Mumbai', 'Bangalore', 'Chennai'], 'rainfall': [700, 2200, 970, 1400] # Average rainfall in mm/year }) logger.info("Using fallback rainfall data") try: if not data: logger.warning("No data provided in request") return {"error": "No data provided"}, 400 # Perform roof top calculation logic result = RooftTopCalculation(data, RainFallData) end_time = time.time() processing_time = round(end_time - start_time, 2) logger.info(f"Successfully completed calculation in {processing_time} seconds") return result except Exception as e: logger.error(f"Error during calculation: {str(e)}") return {"error": str(e)}, 500 # Run the app if the script is executed directly if __name__ == "__main__": import os port = int(os.environ.get("PORT", 7860)) # Hugging Face Spaces uses port 7860 uvicorn.run(app, host="0.0.0.0", port=port)