Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456725 unmodified lines3334353637383910 unmodified lines505152535455567 unmodified lines64656667686970717273747576777879801 unmodified line8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281294 unmodified lines1341351361371381391 unmodified line1411421431441451461472 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721736 unmodified lines180181182183184185186187188189190191192193194195196197198199200201202203204from flask import Flask, request, jsonifyfrom flask_cors import CORSfrom huggingface_hub import InferenceClientimport os, math, randomfrom collections import defaultdictapp = Flask(__name__)25 unmodified linesfood_affinity = defaultdict(lambda: defaultdict(float))# -----------------------------# π DISTANCE# -----------------------------def haversine(lat1, lon1, lat2, lon2):R = 637110 unmodified linesreturn R * (2 * math.atan2(math.sqrt(a), math.sqrt(1-a)))# -----------------------------# π§ SCORING ENGINE# -----------------------------def score(meals, ngo, foodType, expiry, lat, lon):7 unmodified linesft = foodType.lower()nt = ngo["type"].lower()# FOOD MATCHINGif "cooked" in ft:urgency += 40 if "elderly" in nt or "refugee" in nt else 20elif "baked" in ft:urgency += 30 if "elderly" in nt else 15elif "raw" in ft:urgency += 40 if "kitchen" in nt else 20elif "packaged" in ft:urgency += 35 if "food bank" in nt else 20# PORTION IMPACTif meals <= 40:urgency += 50elif meals <= 100:1 unmodified lineelse:urgency += 15# EXPIRY IMPACTif int(expiry) <= 6:urgency += 55elif int(expiry) <= 24:urgency += 30# π₯ SELF-LEARNING BOOSTurgency += ngo_weights[ngo["name"]]urgency += food_affinity[ngo["name"]][foodType]return round(dist_score * 0.25 + cap_score * 0.2 + urgency * 0.55, 2)# -----------------------------# π€ AI REASONING# -----------------------------def explain(ngo, meals, foodType, score_value, rank):prompt = f"""You are NourishNet AI.Rank: {rank}NGO: {ngo['name']} ({ngo['type']})Food: {foodType}Meals: {meals}Score: {score_value}Explain WHY this match is selected in 1β2 lines.Make it unique, human-like, non-repetitive."""try:return client.text_generation(prompt,max_new_tokens=80,temperature=1.2,top_p=0.95).strip()except:return "Selected based on optimal urgency and demand match."# -----------------------------# π‘ ANALYZE# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():4 unmodified linesfoodType = data["foodType"]expiry = data["expiry"]lat, lon = 25.2048, 55.2708results = []1 unmodified linefor ngo in NGOS:s = score(meals, ngo, foodType, expiry, lat, lon)s += random.uniform(-1.5, 1.5)results.append({"recipient": ngo["name"],2 unmodified lines"km": round(haversine(lat, lon, ngo["lat"], ngo["lon"]), 1)})results.sort(key=lambda x: x["score"], reverse=True)for i, r in enumerate(results):ngo_obj = next(n for n in NGOS if n["name"] == r["recipient"])r["priority"] = ("High" if r["score"] >= 80 else"Medium" if r["score"] >= 60 else"Low")r["reason"] = explain(ngo_obj,meals,foodType,r["score"],i+1)return jsonify(results)6 unmodified linesdata = request.jsonrecipient = data["recipient"]foodType = data.get("foodType","")action = data["action"]if action == "accept":ngo_weights[recipient] += 2food_affinity[recipient][foodType] += 1.5else:ngo_weights[recipient] -= 2food_affinity[recipient][foodType] -= 1ngo_weights[recipient] = max(-10, min(25, ngo_weights[recipient]))return jsonify({"status":"updated"})# -----------------------------@app.route("/")def home():return "NourishNet AI Running π"if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)123456725 unmodified lines3334353637383910 unmodified lines505152535455567 unmodified lines646566676869707172737475767778798081828384858687881 unmodified line909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501514 unmodified lines1561571581591601611621 unmodified line1641651661671681692 unmodified lines1721731741751761771781791801811821831841851861871881891901911921931941951961971986 unmodified lines205206207208209210211212213214215216217218219220221222223224225226227228229from flask import Flask, request, jsonifyfrom flask_cors import CORSfrom huggingface_hub import InferenceClientimport os, mathfrom collections import defaultdictapp = Flask(__name__)25 unmodified linesfood_affinity = defaultdict(lambda: defaultdict(float))# -----------------------------# π DISTANCE (REALISTIC)# -----------------------------def haversine(lat1, lon1, lat2, lon2):R = 637110 unmodified linesreturn R * (2 * math.atan2(math.sqrt(a), math.sqrt(1-a)))# -----------------------------# π§ SCORING ENGINE (FIXED + BALANCED)# -----------------------------def score(meals, ngo, foodType, expiry, lat, lon):7 unmodified linesft = foodType.lower()nt = ngo["type"].lower()# ---------------- FOOD LOGIC ----------------food_bonus = 0if "cooked" in ft:food_bonus = 25 if "elderly" in nt or "refugee" in nt else 10elif "baked" in ft:food_bonus = 20 if "elderly" in nt else 8elif "raw" in ft:food_bonus = 25 if "kitchen" in nt else 10elif "packaged" in ft:food_bonus = 22 if "food bank" in nt else 12elif "vegetarian" in ft:food_bonus = 18# ---------------- PORTION IMPACT ----------------if meals <= 40:urgency += 50elif meals <= 100:1 unmodified lineelse:urgency += 15# ---------------- EXPIRY IMPACT ----------------if int(expiry) <= 6:urgency += 55elif int(expiry) <= 24:urgency += 30# ---------------- LEARNING BOOST ----------------learning = ngo_weights[ngo["name"]] * 2food_learning = food_affinity[ngo["name"]][foodType]# ---------------- FINAL SCORE ----------------return round(dist_score * 0.20 +cap_score * 0.20 +urgency * 0.45 +food_bonus * 0.10 +learning +food_learning,2)# -----------------------------# π€ AI REASONING (NO REPETITION)# -----------------------------def explain(ngo, meals, foodType, score_value, rank):prompt = f"""You are NourishNet AI, a humanitarian logistics intelligence system.Rank: {rank}NGO: {ngo['name']} ({ngo['type']})Food Type: {foodType}Meals: {meals}Score: {score_value}Explain WHY this NGO is ranked here.Mention food suitability, urgency, and capacity differences.Make each explanation UNIQUE (do NOT repeat patterns).Return ONLY 1β2 short sentences."""try:return client.text_generation(prompt,max_new_tokens=90,temperature=0.8,top_p=0.9).strip()except:return "Selected based on urgency, capacity, and food-type compatibility."# -----------------------------# π‘ ANALYZE ENDPOINT# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():4 unmodified linesfoodType = data["foodType"]expiry = data["expiry"]# fixed location (can upgrade later to real GPS)lat, lon = 25.2048, 55.2708results = []1 unmodified linefor ngo in NGOS:s = score(meals, ngo, foodType, expiry, lat, lon)results.append({"recipient": ngo["name"],2 unmodified lines"km": round(haversine(lat, lon, ngo["lat"], ngo["lon"]), 1)})# sort by scoreresults.sort(key=lambda x: x["score"], reverse=True)# assign AI reasoning + priorityfor i, r in enumerate(results):ngo_obj = next(n for n in NGOS if n["name"] == r["recipient"])if r["score"] >= 78:r["priority"] = "High"elif r["score"] >= 58:r["priority"] = "Medium"else:r["priority"] = "Low"r["reason"] = explain(ngo_obj,meals,foodType,r["score"],i + 1)return jsonify(results)6 unmodified linesdata = request.jsonrecipient = data["recipient"]foodType = data.get("foodType", "")action = data["action"]if action == "accept":ngo_weights[recipient] += 2food_affinity[recipient][foodType] += 1.5else:ngo_weights[recipient] -= 2food_affinity[recipient][foodType] -= 1ngo_weights[recipient] = max(-10, min(25, ngo_weights[recipient]))return jsonify({"status": "updated"})# -----------------------------@app.route("/")def home():return "NourishNet AI Running π"# -----------------------------if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)
app.py+59-34