import os import json import datetime from flask import Flask, request, jsonify import firebase_admin from firebase_admin import credentials, firestore app = Flask(__name__) # ------------------------------------------------------- # Firebase Initialization (SECURE: Loads from ENV) # ------------------------------------------------------- service_json = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS_JSON") if not service_json: raise Exception( "Firebase service account JSON not found. " "Please set GOOGLE_APPLICATION_CREDENTIALS_JSON in Hugging Face Secrets." ) cred = credentials.Certificate(json.loads(service_json)) firebase_admin.initialize_app(cred) db = firestore.client() # ------------------------------------------------------- # Scheme Scoring Logic # ------------------------------------------------------- def compute_scheme_score(scheme, user): score = 0 # AGE REQUIREMENT age_min = scheme.get("eligibility", {}).get("age_min", 0) if user.get("age", 0) >= age_min: score += 25 # CATEGORY MATCH (SC → SCFAMILIES target) if scheme.get("target_group") == "SCFAMILIES" and user.get("category") == "SC": score += 40 # LOCATION MATCH loc = scheme.get("locations", {}) if isinstance(loc, dict): if user.get("district", "").lower() == loc.get("district", "").lower(): score += 15 if user.get("state", "").lower() == loc.get("state", "").lower(): score += 10 # DOCUMENT MATCH required_docs = scheme.get("eligibility", {}).get("required_documents", []) user_docs = user.get("documents", []) matched = len(set(required_docs).intersection(user_docs)) score += matched * 5 # LIVESTOCK / INTEREST MATCH if user.get("interest") in scheme.get("livestock_types", []): score += 20 # SUBSIDY STRENGTH if scheme.get("subsidy_percent", 0) >= 50: score += 10 # TRAINING ADVANTAGE if scheme.get("training_days", 0) == 0: score += 5 return score # ------------------------------------------------------- # Recommendation Endpoint # ------------------------------------------------------- @app.route("/recommend", methods=["POST"]) def recommend_schemes(): user = request.json parent_id = "qo3JakPyOUWzdEOFYWbv" schemes_ref = db.collection("data").document(parent_id).collection("Schemes") output = [] for doc in schemes_ref.stream(): scheme = doc.to_dict() score = compute_scheme_score(scheme, user) output.append({ "scheme_id": scheme.get("scheme_id"), "title": scheme.get("title"), "short_description": scheme.get("short_description"), "full_description": scheme.get("full_description"), "score": score, "livestock_types": scheme.get("livestock_types"), "subsidy_percent": scheme.get("subsidy_percent"), "locations": scheme.get("locations"), "eligibility": scheme.get("eligibility"), "application_process": scheme.get("application_process"), "contact": scheme.get("contact") }) # Sort recommendations by highest score output = sorted(output, key=lambda x: x["score"], reverse=True) return jsonify({ "timestamp": datetime.datetime.utcnow().isoformat(), "recommendations": output }) # ------------------------------------------------------- # Health Check Endpoint # ------------------------------------------------------- @app.route("/") def index(): return jsonify({"status": "OK", "message": "Scheme Recommendation API Active"}) # ------------------------------------------------------- # HF Spaces uses port 7860 automatically # ------------------------------------------------------- if __name__ == "__main__": app.run(host="0.0.0.0", port=7860)