Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines91011121314151 unmodified line171819202122235 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871887 unmodified lines1961971981992002012022032042052062072082092102112122132142152161 unmodified line2182192202212222232242252262278 unmodified linesCORS(app)# -----------------------------# π€ LLaMA MODEL# -----------------------------client = InferenceClient(model="meta-llama/Meta-Llama-3.1-8B-Instruct",1 unmodified line)# -----------------------------# π₯ LIVE NGO DATABASE# -----------------------------NGOS = [{"name":"Dubai Food Bank","type":"Food Bank","lat":25.20,"lon":55.27,"capacity":500},5 unmodified lines]# -----------------------------# π HISTORICAL DATASET# -----------------------------HISTORY = [{"city":"Dubai","food":"Cooked","meals":180,"recipient":"UAE Refugee Support Center"},{"city":"Dubai","food":"Cooked","meals":55,"recipient":"Dubai Food Bank"},{"city":"Dubai","food":"Packaged","meals":130,"recipient":"Dubai Food Bank"},{"city":"Sharjah","food":"Cooked","meals":65,"recipient":"Sharjah Elderly Care Home"},{"city":"Sharjah","food":"Vegetarian","meals":95,"recipient":"Sharjah Elderly Care Home"},{"city":"Abu Dhabi","food":"Cooked","meals":170,"recipient":"Abu Dhabi Community Kitchen"},{"city":"Ajman","food":"Baked","meals":45,"recipient":"Ajman Senior Support Home"},{"city":"Dubai","food":"Cooked","meals":220,"recipient":"Dubai Shelter Hub"},{"city":"Dubai","food":"Raw Ingredients","meals":80,"recipient":"Dubai Food Bank"},{"city":"Sharjah","food":"Packaged","meals":140,"recipient":"Sharjah Elderly Care Home"}]# -----------------------------# π DETECT CITY# -----------------------------def detect_city():cities = ["Dubai", "Sharjah", "Abu Dhabi", "Ajman"]return random.choice(cities)# -----------------------------# π§ MAIN SCORING ENGINE (UPDATED)# -----------------------------def score(meals, ngo, foodType, expiry):# distance scoredist = math.sqrt((ngo["lat"] - 25.20)**2 + (ngo["lon"] - 55.27)**2) * 100dist_score = max(0, 100 - dist * 10)# capacity scorecap_score = min(100, ngo["capacity"] / max(meals,1) * 100)urgency = 50ngo_type = ngo["type"].lower()ft = foodType.lower()# -----------------------------# π± FOOD SCROLL BAR IMPACT# -----------------------------if "cooked" in ft:if "elderly" in ngo_type:urgency += 30elif "refugee" in ngo_type:urgency += 25elif "baked" in ft:if "elderly" in ngo_type:urgency += 25elif "community" in ngo_type:urgency += 15elif "raw" in ft:if "kitchen" in ngo_type:urgency += 35elif "food bank" in ngo_type:urgency += 10elif "packaged" in ft:if "food bank" in ngo_type:urgency += 30elif "refugee" in ngo_type:urgency += 20# -----------------------------# π½ PORTION SIZE IMPACT# -----------------------------if meals >= 150:urgency += 25if "food bank" in ngo_type:urgency += 15elif meals <= 60:if "elderly" in ngo_type:urgency += 25urgency += 10# -----------------------------# β³ EXPIRY IMPACT# -----------------------------if expiry <= 6:urgency += 30if "elderly" in ngo_type or "refugee" in ngo_type:urgency += 10elif expiry <= 24:urgency += 15else:if "food bank" in ngo_type:urgency += 10# -----------------------------# FINAL SCORE# -----------------------------return round(dist_score * 0.25 +cap_score * 0.25 +urgency * 0.50,2)# -----------------------------# π§ DATASET BOOST# -----------------------------def history_boost(city, foodType, meals, ngo_name):boost = 0for row in HISTORY:if row["recipient"] == ngo_name:if row["city"] == city:boost += 8if row["food"].lower() == foodType.lower():boost += 10if abs(row["meals"] - meals) <= 40:boost += 7return boost# -----------------------------# π€ LLM REASONING# -----------------------------def explain(ngo, meals, foodType, expiry, city):prompt = f"""You are NourishNet AI.Donation City: {city}Recipient: {ngo['name']}Type: {ngo['type']}Meals: {meals}Food Type: {foodType}Expiry: {expiry} hoursExplain in ONE short sentence why this is the best match.Be specific and avoid repetition."""try:return client.text_generation(prompt,max_new_tokens=60,temperature=0.9).strip()except:return f"{ngo['name']} matches based on demand, food type and capacity."# -----------------------------# π‘ API7 unmodified linesfoodType = data["foodType"]expiry = int(data["expiry"])city = detect_city()results = []for ngo in NGOS:base = score(meals, ngo, foodType, expiry)memory = history_boost(city, foodType, meals, ngo["name"])final_score = round(base + memory, 2)priority = "High" if final_score >= 85 else "Medium" if final_score >= 65 else "Low"km = round(max(1.2, 12 - final_score / 10), 1)results.append({"recipient": ngo["name"],1 unmodified line"score": final_score,"km": km,"priority": priority,"reason": explain(ngo, meals, foodType, expiry, city)})return jsonify(sorted(results, key=lambda x: x["score"], reverse=True))# -----------------------------@app.route("/")8 unmodified lines91011121314151 unmodified line171819202122235 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251267 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561 unmodified line1581591601611621631641651661671681691708 unmodified linesCORS(app)# -----------------------------# π€ LLM MODEL# -----------------------------client = InferenceClient(model="meta-llama/Meta-Llama-3.1-8B-Instruct",1 unmodified line)# -----------------------------# π₯ NGO DATABASE# -----------------------------NGOS = [{"name":"Dubai Food Bank","type":"Food Bank","lat":25.20,"lon":55.27,"capacity":500},5 unmodified lines]# -----------------------------# π SCORE ENGINE (BALANCED)# -----------------------------def score(meals, ngo, foodType, expiry):# distancedist = math.sqrt((ngo["lat"] - 25.20)**2 + (ngo["lon"] - 55.27)**2) * 100dist_score = max(0, 100 - dist * 10)# capacity (reduced dominance!)cap_score = min(100, (ngo["capacity"] / max(meals, 1)) * 60)urgency = 40 # basengo_type = ngo["type"].lower()ft = foodType.lower()# -------------------------# π± FOOD TYPE IMPACT (IMPORTANT)# -------------------------if "cooked" in ft:if "elderly" in ngo_type:urgency += 35elif "refugee" in ngo_type:urgency += 25elif "baked" in ft:if "elderly" in ngo_type:urgency += 30elif "raw" in ft:if "kitchen" in ngo_type:urgency += 35elif "packaged" in ft:if "food bank" in ngo_type:urgency += 30# -------------------------# π½ PORTION IMPACT# -------------------------if meals >= 150:urgency += 25elif meals <= 60:urgency += 20# -------------------------# β³ EXPIRY IMPACT# -------------------------if expiry <= 6:urgency += 30elif expiry <= 24:urgency += 15# final scorereturn round(dist_score * 0.25 +cap_score * 0.20 +urgency * 0.55,2)# -----------------------------# π€ LLM REASONING (1β2 LINES ONLY)# -----------------------------def explain(ngo, meals, foodType, expiry):prompt = f"""You are a logistics AI.Match:- NGO: {ngo['name']}- Type: {ngo['type']}- Food: {foodType}- Meals: {meals}- Expiry: {expiry} hoursGive ONLY 1β2 short clear lines explaining WHY this is a good match.Be specific. Mention food type or urgency or capacity.Avoid generic phrases."""try:out = client.text_generation(prompt,max_new_tokens=60,temperature=1.0,top_p=0.9)return out.strip()except:return f"Best suited for {foodType} based on demand and capacity alignment."# -----------------------------# π‘ API7 unmodified linesfoodType = data["foodType"]expiry = int(data["expiry"])results = []for ngo in NGOS:base = score(meals, ngo, foodType, expiry)# small randomness for realismfinal_score = round(base + random.uniform(-1.2, 1.2), 2)if final_score >= 85:priority = "High"elif final_score >= 65:priority = "Medium"else:priority = "Low"km = round(max(1.5, 12 - final_score / 10), 1)results.append({"recipient": ngo["name"],1 unmodified line"score": final_score,"km": km,"priority": priority,"reason": explain(ngo, meals, foodType, expiry)})# sort final rankingresults.sort(key=lambda x: x["score"], reverse=True)return jsonify(results)# -----------------------------@app.route("/")
app.py+55-112