Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345678910 unmodified lines202122222324252623242526272829301 unmodified line323334353637382 unmodified lines4142434244454647484949505152535455565556575958615960616263676465663 unmodified lines707172777374751 unmodified line77787985808182838491858687888990989192100939495969798991001011021031021031051061071081091041051111121131061071081091101111121131141151161171181191161201211221191201231241251261271281291301311231321331341351361371381391401411421431441451461301471321481491501361371511521531541551561571581591601611621631401641421431441451651661671681691701711721501731741751761771781791561801581811821831841851641861661671681691701871881891901913 unmodified lines1951961971801981991832002012022032042051892062072082092102112122132142152162172182192202212222232242252262272282291962302312322332342352362372382392402 unmodified linesfrom huggingface_hub import InferenceClientimport os, math, randomfrom collections import defaultdictfrom datetime import datetime
app = Flask(__name__)CORS(app)10 unmodified lines# 🏥 NGO DATASET# -----------------------------NGOS = [ {"name":"Dubai Food Bank","type":"Food Bank","lat":25.20,"lon":55.27,"capacity":500}, {"name":"Sharjah Elderly Care Home","type":"Elderly Home","lat":25.34,"lon":55.42,"capacity":120}, {"name":"UAE Refugee Support Center","type":"Refugee Camp","lat":25.27,"lon":55.29,"capacity":800}, {"name":"Abu Dhabi Community Kitchen","type":"Community Kitchen","lat":24.45,"lon":54.37,"capacity":300}, {"name":"Ajman Senior Support Home","type":"Elderly Home","lat":25.41,"lon":55.51,"capacity":140} {"name":"Dubai Food Bank","type":"Food Bank","lat":25.20,"lon":55.27,"capacity":500,"city":"Dubai","serves":"general public, families in need"}, {"name":"Sharjah Elderly Care Home","type":"Elderly Home","lat":25.34,"lon":55.42,"capacity":120,"city":"Sharjah","serves":"senior citizens, elderly residents"}, {"name":"UAE Refugee Support Center","type":"Refugee Camp","lat":25.27,"lon":55.29,"capacity":800,"city":"Dubai","serves":"displaced families, refugees"}, {"name":"Abu Dhabi Community Kitchen","type":"Community Kitchen","lat":24.45,"lon":54.37,"capacity":300,"city":"Abu Dhabi","serves":"community members, low-income families"}, {"name":"Ajman Senior Support Home","type":"Elderly Home","lat":25.41,"lon":55.51,"capacity":140,"city":"Ajman","serves":"elderly residents requiring daily care"}]
# -----------------------------1 unmodified line# -----------------------------ngo_weights = defaultdict(float)food_affinity = defaultdict(lambda: defaultdict(float))donation_log = []
# -----------------------------# 🌍 DISTANCE2 unmodified lines R = 6371 dlat = math.radians(lat2 - lat1) dlon = math.radians(lon2 - lon1)
a = ( math.sin(dlat/2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon/2)**2 )
return R * (2 * math.atan2(math.sqrt(a), math.sqrt(1-a)))
# -----------------------------# 🧠 SCORING ENGINE# -----------------------------def score(meals, ngo, foodType, expiry, lat, lon):
def score_ngo(meals, ngo, foodType, expiry, lat, lon): dist = haversine(lat, lon, ngo["lat"], ngo["lon"]) dist_score = max(0, 100 - dist * 6)
cap_score = min(100, ngo["capacity"] / max(meals, 1) * 40)
urgency = 20
ft = foodType.lower() nt = ngo["type"].lower()
# FOOD MATCHING if "cooked" in ft: urgency += 40 if "elderly" in nt or "refugee" in nt else 20 elif "baked" in ft:3 unmodified lines elif "packaged" in ft: urgency += 35 if "food bank" in nt else 20
# PORTION IMPACT if meals <= 40: urgency += 50 elif meals <= 100:1 unmodified line else: urgency += 15
# 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]
return round(dist_score * 0.25 + cap_score * 0.2 + urgency * 0.55, 2)
# -----------------------------# 🤖 AI REASONING# 🤖 AI REASONING — RICH PROMPT# -----------------------------def explain(ngo, meals, foodType, score_value, rank):def explain(ngo, meals, foodType, expiry_hrs, score_value, rank, dist_km, donor_city):
urgency_label = "CRITICAL" if int(expiry_hrs) <= 6 else "MODERATE" time_left = f"{expiry_hrs} hours" portion_context = "small batch" if meals <= 40 else ("medium batch" if meals <= 100 else "large batch") top_pick = "top recommended match" if rank == 1 else f"#{rank} recommended match" capacity_util = round((meals / ngo["capacity"]) * 100, 1)
prompt = f"""You are NourishNet AI. prompt = f"""You are NourishNet AI, an intelligent food redistribution system operating in the UAE.
Rank: {rank}NGO: {ngo['name']} ({ngo['type']})Food: {foodType}Meals: {meals}Score: {score_value}A donor in {donor_city} has {meals} portions of {foodType.lower()} food expiring in {time_left} ({urgency_label} urgency).
Explain WHY this match is selected in 1–2 lines.Make it unique, human-like, non-repetitive."""You matched this donation to: {ngo['name']} ({ngo['type']}, {ngo['city']})- Match rank: {top_pick}- Distance: {dist_km} km from donor- AI match score: {score_value}/100- This NGO serves: {ngo['serves']}- Capacity utilization: {capacity_util}% (this donation uses {capacity_util}% of their capacity)- Donation size: {portion_context} ({meals} portions)
Write 1-2 sentences explaining specifically WHY this is a good match. Reference the food type ({foodType}), expiry urgency, and who will benefit.Be direct, specific, and human. No filler phrases like "this match is ideal because". Start with an action verb or the NGO name. Max 40 words."""
try: return client.text_generation( response = client.text_generation( prompt, max_new_tokens=80, temperature=1.2, top_p=0.95 temperature=0.85, top_p=0.92, repetition_penalty=1.15 ).strip() # Clean up any prompt leakage if len(response) < 10 or "You are" in response: raise ValueError("Bad response") return response except: return "Selected based on optimal urgency and demand match." type_map = { "cooked": "hot meals need immediate distribution", "baked": "baked goods stay fresh only briefly", "raw": "raw ingredients suit kitchen processing", "packaged": "packaged food fits bulk storage well" } ft_lower = foodType.lower() reason = next((v for k,v in type_map.items() if k in ft_lower), "food matches recipient needs") return f"{ngo['name']} prioritized: {reason} and {meals} portions fit their {ngo['type'].lower()} capacity perfectly."
# -----------------------------# 📡 ANALYZE# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():
data = request.json
meals = int(data["meals"]) foodType = data["foodType"] expiry = data["expiry"]
lat, lon = 25.2048, 55.2708 donor_city = data.get("city", "Dubai")
# City coordinates city_coords = { "Dubai": (25.2048, 55.2708), "Sharjah": (25.3462, 55.4212), "Abu Dhabi": (24.4539, 54.3773), "Ajman": (25.4052, 55.5136), "RAK": (25.7895, 55.9432) } lat, lon = city_coords.get(donor_city, (25.2048, 55.2708))
results = []
for ngo in NGOS:
s = score(meals, ngo, foodType, expiry, lat, lon) s += random.uniform(-1.5, 1.5)
s = score_ngo(meals, ngo, foodType, expiry, lat, lon) s += random.uniform(-1.0, 1.0) dist_km = round(haversine(lat, lon, ngo["lat"], ngo["lon"]), 1) results.append({ "recipient": ngo["name"], "type": ngo["type"], "city": ngo["city"], "score": round(s, 2), "km": round(haversine(lat, lon, ngo["lat"], ngo["lon"]), 1) "km": dist_km, "capacity": ngo["capacity"] })
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 ngo_obj, meals, foodType, expiry, r["score"], i+1, r["km"], donor_city )
return jsonify(results)3 unmodified lines# -----------------------------@app.route("/feedback", methods=["POST"])def feedback():
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"})
# -----------------------------# 📋 LOG DONATION# -----------------------------@app.route("/log", methods=["POST"])def log_donation(): data = request.json entry = { "id": f"DON-{len(donation_log)+1:04d}", "timestamp": datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"), "city": data.get("city", "Dubai"), "foodType": data.get("foodType", ""), "portions": data.get("portions", 0), "expiry": data.get("expiry", ""), "recipients": data.get("recipients", []), "wasteKg": round(int(data.get("portions", 0)) * 0.4, 1) } donation_log.append(entry) return jsonify({"status":"updated"}) return jsonify({"status": "logged", "id": entry["id"]})
# -----------------------------# 📊 GET LOG# -----------------------------@app.route("/logs", methods=["GET"])def get_logs(): return jsonify(donation_log)
# -----------------------------@app.route("/")app.py+94-53