Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234456725 unmodified lines333435363637383910 unmodified lines50515253535455567 unmodified lines646566676768697069717273717475767377787975808182838477858687881 unmodified line909192859394959697989192939910010110210395104105106107108109110111112113114115981161171181191201031211221231241071251261271281111121291301311321331341351361371381181191201391401411421431441231451461471261481491501514 unmodified lines1561571581591601611621 unmodified line1641651661441671681692 unmodified lines1721731741751761771781791801811821591601611621631831841851861871881891901911921931941701951961971986 unmodified lines205206207183208209210211212213189214215216217218219196220221222223224225226227228229from flask import Flask, request, jsonifyfrom flask_cors import CORSfrom huggingface_hub import InferenceClientimport os, math, randomimport os, mathfrom collections import defaultdict
app = Flask(__name__)25 unmodified linesfood_affinity = defaultdict(lambda: defaultdict(float))
# -----------------------------# π DISTANCE# π DISTANCE (REALISTIC)# -----------------------------def haversine(lat1, lon1, lat2, lon2): R = 637110 unmodified lines return R * (2 * math.atan2(math.sqrt(a), math.sqrt(1-a)))
# -----------------------------# π§ SCORING ENGINE# π§ SCORING ENGINE (FIXED + BALANCED)# -----------------------------def score(meals, ngo, foodType, expiry, lat, lon):
7 unmodified lines ft = foodType.lower() nt = ngo["type"].lower()
# FOOD MATCHING # ---------------- FOOD LOGIC ---------------- food_bonus = 0
if "cooked" in ft: urgency += 40 if "elderly" in nt or "refugee" in nt else 20 food_bonus = 25 if "elderly" in nt or "refugee" in nt else 10
elif "baked" in ft: urgency += 30 if "elderly" in nt else 15 food_bonus = 20 if "elderly" in nt else 8
elif "raw" in ft: urgency += 40 if "kitchen" in nt else 20 food_bonus = 25 if "kitchen" in nt else 10
elif "packaged" in ft: urgency += 35 if "food bank" in nt else 20 food_bonus = 22 if "food bank" in nt else 12
elif "vegetarian" in ft: food_bonus = 18
# PORTION IMPACT # ---------------- PORTION IMPACT ---------------- if meals <= 40: urgency += 50 elif meals <= 100:1 unmodified line else: urgency += 15
# EXPIRY IMPACT # ---------------- EXPIRY IMPACT ---------------- if int(expiry) <= 6: urgency += 55 elif int(expiry) <= 24: urgency += 30
# π₯ SELF-LEARNING BOOST urgency += ngo_weights[ngo["name"]] urgency += food_affinity[ngo["name"]][foodType] # ---------------- LEARNING BOOST ---------------- learning = ngo_weights[ngo["name"]] * 2
food_learning = food_affinity[ngo["name"]][foodType]
return round(dist_score * 0.25 + cap_score * 0.2 + urgency * 0.55, 2) # ---------------- 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# π€ AI REASONING (NO REPETITION)# -----------------------------def explain(ngo, meals, foodType, score_value, rank):
prompt = f"""You are NourishNet AI.You are NourishNet AI, a humanitarian logistics intelligence system.
Rank: {rank}NGO: {ngo['name']} ({ngo['type']})Food: {foodType}Food Type: {foodType}Meals: {meals}Score: {score_value}
Explain WHY this match is selected in 1β2 lines.Make it unique, human-like, non-repetitive.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=80, temperature=1.2, top_p=0.95 max_new_tokens=90, temperature=0.8, top_p=0.9 ).strip()
except: return "Selected based on optimal urgency and demand match." return "Selected based on urgency, capacity, and food-type compatibility."
# -----------------------------# π‘ ANALYZE# π‘ ANALYZE ENDPOINT# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():4 unmodified lines foodType = data["foodType"] expiry = data["expiry"]
# fixed location (can upgrade later to real GPS) lat, lon = 25.2048, 55.2708
results = []1 unmodified line for 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) })
# sort by score results.sort(key=lambda x: x["score"], reverse=True)
# assign AI reasoning + priority 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" ) 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 i + 1 )
return jsonify(results)6 unmodified lines
data = request.json recipient = data["recipient"] foodType = data.get("foodType","") foodType = data.get("foodType", "") action = data["action"]
if action == "accept": ngo_weights[recipient] += 2 food_affinity[recipient][foodType] += 1.5
else: ngo_weights[recipient] -= 2 food_affinity[recipient][foodType] -= 1
ngo_weights[recipient] = max(-10, min(25, ngo_weights[recipient]))
return jsonify({"status":"updated"}) 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