Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines91011121314154 unmodified lines2021222324252627282930313233343536373839404142434445464748495010 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881 unmodified line1901911921931941951961971981992002012022032 unmodified lines2062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552568 unmodified linesCORS(app)# -----------------------------# π€ LLM (YOU CAN USE 3.3 70B VERSATILE HERE)# -----------------------------client = InferenceClient(model="meta-llama/Meta-Llama-3.3-70B-Versatile",4 unmodified lines# π₯ NGO DATABASE# -----------------------------NGOS = [{"name":"Dubai Food Bank","type":"Food Bank","lat":25.20,"lon":55.27,"capacity":500, "veg_only":False},{"name":"Sharjah Elderly Care Home","type":"Elderly Home","lat":25.34,"lon":55.42,"capacity":120, "veg_only":True},{"name":"UAE Refugee Support Center","type":"Refugee Camp","lat":25.27,"lon":55.29,"capacity":800, "veg_only":False},{"name":"Abu Dhabi Community Kitchen","type":"Community Kitchen","lat":24.45,"lon":54.37,"capacity":300, "veg_only":False},{"name":"Ajman Senior Support Home","type":"Elderly Home","lat":25.41,"lon":55.51,"capacity":140, "veg_only":True},]# -----------------------------# π YOUR 50-SCENARIO DATASET (SIMPLIFIED BUT EFFECTIVE)# -----------------------------HISTORY = [{"food":"cooked","meals":40,"type":"elderly"},{"food":"cooked","meals":60,"type":"elderly"},{"food":"cooked","meals":200,"type":"shelter"},{"food":"packaged","meals":120,"type":"food bank"},{"food":"packaged","meals":150,"type":"food bank"},{"food":"baked","meals":35,"type":"kitchen"},{"food":"baked","meals":55,"type":"elderly"},{"food":"raw","meals":80,"type":"kitchen"},{"food":"vegetarian","meals":90,"type":"shelter"},{"food":"cooked","meals":28,"type":"elderly"},]# -----------------------------# π DISTANCE (REALISTIC)# -----------------------------def haversine(lat1, lon1, lat2, lon2):R = 637110 unmodified linesreturn R * (2 * math.atan2(math.sqrt(a), math.sqrt(1-a)))# -----------------------------# π§ DATASET ENGINE (REAL USAGE)# -----------------------------def dataset_boost(foodType, meals, ngo_type):ft = foodType.lower()nt = ngo_type.lower()score = 0for row in HISTORY:match = 0if row["food"] == ft:match += 1if abs(row["meals"] - meals) <= 25:match += 1if row["type"] in nt:match += 1if match >= 2:score += 5return min(score, 30)# -----------------------------# π§ CORE SCORING ENGINE (FIXED LOGIC)# -----------------------------def score(meals, ngo, foodType, veg_type, 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 = 10ft = foodType.lower()nt = ngo["type"].lower()# FOOD TYPE LOGICif "cooked" in ft:urgency += 40 if "elderly" in nt or "refugee" in nt else 20elif "baked" in ft:urgency += 35 if "elderly" in nt else 15elif "raw" in ft:urgency += 40 if "kitchen" in nt else 20elif "packaged" in ft:urgency += 30 if "food bank" in nt else 15# VEG LOGICif veg_type.lower() == "vegetarian" and ngo["veg_only"]:urgency += 25elif veg_type.lower() == "non-vegetarian" and ngo["veg_only"]:urgency -= 25# PORTION LOGIC (CRITICAL FIX)if meals <= 40:urgency += 45elif meals <= 100:urgency += 30else:urgency += 15# EXPIRYif expiry <= 6:urgency += 50elif expiry <= 24:urgency += 30# REMOVE FOOD BANK OVERBIASED BEHAVIORif meals < 50 and "food bank" in nt:urgency -= 20# DATASET BOOST (REAL IMPACT NOW)boost = dataset_boost(foodType, meals, ngo["type"])final_score = (dist_score * 0.2 +cap_score * 0.15 +urgency * 0.6 +boost * 1.8)return round(final_score, 2)# -----------------------------# π€ DYNAMIC EXPLANATION (FIXED)# -----------------------------def explain(ngo, meals, foodType, veg_type, expiry, score_value, rank):style = random.choice(["urgency-driven logic","distance optimization","food suitability pattern","capacity balancing","waste reduction strategy"])prompt = f"""You are NourishNet AI trained on a 50-case humanitarian dataset.Rank: {rank}NGO: {ngo['name']} ({ngo['type']})Food: {foodType}Veg Type: {veg_type}Meals: {meals}Expiry: {expiry}Score: {score_value}Instruction:Explain in 1β2 lines WHY this NGO is selected.Focus ONLY on: {style}Be specific, avoid repetition, and refer to real pattern logic."""try:1 unmodified lineprompt,max_new_tokens=80,temperature=1.2,top_p=0.9).strip()except:return "Selected based on optimal humanitarian redistribution match."# -----------------------------# π‘ API# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():2 unmodified linesmeals = int(data["meals"])foodType = data["foodType"]expiry = int(data["expiry"])veg_type = data.get("vegType", "vegetarian")lat = float(data.get("lat", 25.2048))lon = float(data.get("lon", 55.2708))results = []for ngo in NGOS:s = score(meals, ngo, foodType, veg_type, expiry, lat, lon)s += random.uniform(-2, 2)km = round(haversine(lat, lon, ngo["lat"], ngo["lon"]), 1)results.append({"recipient": ngo["name"],"type": ngo["type"],"score": s,"km": km,"priority": "High" if s >= 80 else "Medium" if s >= 60 else "Low"})results.sort(key=lambda x: x["score"], reverse=True)# add LLM reasoning AFTER ranking (VERY IMPORTANT FIX)for i, r in enumerate(results):ngo_obj = next(n for n in NGOS if n["name"] == r["recipient"])r["reason"] = explain(ngo_obj,meals,foodType,veg_type,expiry,r["score"],i + 1)return jsonify(results)# -----------------------------@app.route("/")def home():return "NourishNet AI Running π"if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)8 unmodified lines91011121314154 unmodified lines202122232425262728293031323334353637383910 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141 unmodified line1161171181191201211221231241251261271282 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022038 unmodified linesCORS(app)# -----------------------------# π€ LLM# -----------------------------client = InferenceClient(model="meta-llama/Meta-Llama-3.3-70B-Versatile",4 unmodified lines# π₯ NGO DATABASE# -----------------------------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}]# -----------------------------# π§ SELF-LEARNING MEMORY (KEY PART)# -----------------------------learned_weights = {ngo["name"]: 0 for ngo in NGOS}# -----------------------------# π DISTANCE# -----------------------------def haversine(lat1, lon1, lat2, lon2):R = 637110 unmodified linesreturn R * (2 * math.atan2(math.sqrt(a), math.sqrt(1-a)))# -----------------------------# π§ SCORING ENGINE (NOW LEARNS)# -----------------------------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: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:urgency += 30else:urgency += 15# EXPIRYif int(expiry) <= 6:urgency += 55elif int(expiry) <= 24:urgency += 30# SELF-LEARNING BOOST (IMPORTANT)urgency += learned_weights[ngo["name"]]return round(dist_score * 0.25 + cap_score * 0.2 + urgency * 0.55, 2)# -----------------------------# π€ REASONING# -----------------------------def explain(ngo, meals, foodType, score_value, rank):prompt = f"""You are NourishNet AI improving from real user feedback.Rank: {rank}NGO: {ngo['name']} ({ngo['type']})Food: {foodType}Meals: {meals}Score: {score_value}Explain WHY this is selected in 1β2 lines.Be different from previous responses."""try:1 unmodified lineprompt,max_new_tokens=80,temperature=1.2,top_p=0.95).strip()except:return "Selected based on optimal match and system learning."# -----------------------------# π‘ ANALYZE API# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():2 unmodified linesmeals = int(data["meals"])foodType = data["foodType"]expiry = data["expiry"]lat = 25.2048lon = 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": s,"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)# -----------------------------# π§ LEARNING API (THIS IS THE MAGIC)# -----------------------------@app.route("/feedback", methods=["POST"])def feedback():data = request.jsonrecipient = data["recipient"]action = data["action"] # "accept" or "reject"if action == "accept":learned_weights[recipient] += 2else:learned_weights[recipient] -= 1# clamp valueslearned_weights[recipient] = max(-10, min(20, learned_weights[recipient]))return jsonify({"message": "learning updated","weights": learned_weights})# -----------------------------@app.route("/")def home():return "NourishNet Self-Learning AI Running π"if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)
app.py+68-121