Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567810 unmodified lines19202122232425262728291 unmodified line3132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869703 unmodified lines747576777879801 unmodified line8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721733 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992 unmodified linesfrom huggingface_hub import InferenceClientimport os, math, randomfrom collections import defaultdictapp = 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}]# -----------------------------1 unmodified line# -----------------------------ngo_weights = defaultdict(float)food_affinity = defaultdict(lambda: defaultdict(float))# -----------------------------# π DISTANCE2 unmodified linesR = 6371dlat = 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):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 = 20ft = 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:3 unmodified lineselif "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():data = request.jsonmeals = int(data["meals"])foodType = data["foodType"]expiry = data["expiry"]lat, lon = 25.2048, 55.2708results = []for ngo in NGOS:s = score(meals, ngo, foodType, expiry, lat, lon)s += random.uniform(-1.5, 1.5)results.append({"recipient": ngo["name"],"type": ngo["type"],"score": round(s, 2),"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)3 unmodified lines# -----------------------------@app.route("/feedback", methods=["POST"])def feedback():data = 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("/")2 unmodified lines345678910 unmodified lines20212223242526272829301 unmodified line323334353637382 unmodified lines41424344454647484950515253545556575859606162636465663 unmodified lines7071727374751 unmodified line77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901913 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402 unmodified linesfrom huggingface_hub import InferenceClientimport os, math, randomfrom collections import defaultdictfrom datetime import datetimeapp = 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,"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 linesR = 6371dlat = 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_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 = 20ft = foodType.lower()nt = ngo["type"].lower()if "cooked" in ft:urgency += 40 if "elderly" in nt or "refugee" in nt else 20elif "baked" in ft:3 unmodified lineselif "packaged" in ft:urgency += 35 if "food bank" in nt else 20if meals <= 40:urgency += 50elif meals <= 100:1 unmodified lineelse:urgency += 15if int(expiry) <= 6:urgency += 55elif int(expiry) <= 24:urgency += 30urgency += 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 β RICH PROMPT# -----------------------------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, an intelligent food redistribution system operating in the UAE.A donor in {donor_city} has {meals} portions of {foodType.lower()} food expiring in {time_left} ({urgency_label} urgency).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:response = client.text_generation(prompt,max_new_tokens=80,temperature=0.85,top_p=0.92,repetition_penalty=1.15).strip()# Clean up any prompt leakageif len(response) < 10 or "You are" in response:raise ValueError("Bad response")return responseexcept: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.jsonmeals = int(data["meals"])foodType = data["foodType"]expiry = data["expiry"]donor_city = data.get("city", "Dubai")# City coordinatescity_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_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": 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, expiry,r["score"], i+1, r["km"], donor_city)return jsonify(results)3 unmodified lines# -----------------------------@app.route("/feedback", methods=["POST"])def feedback():data = 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"})# -----------------------------# π LOG DONATION# -----------------------------@app.route("/log", methods=["POST"])def log_donation():data = request.jsonentry = {"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": "logged", "id": entry["id"]})# -----------------------------# π GET LOG# -----------------------------@app.route("/logs", methods=["GET"])def get_logs():return jsonify(donation_log)# -----------------------------@app.route("/")
app.py+94-53