Spaces:
Sleeping
Sleeping
Update app.py
Browse files11 unmodified lines12131415151617181920202122232425262627282930313032333435363738394041424344454647484950515253545556575834355960613762633964654166676844697071727374757677787980818283848586878889909146929394959651979899100101102561031041055859106107108616210911011111211366114115116117118701191207273121122123124125126761271281291302 unmodified lines13313413513613713887139140141142143144145146931471489514915015115215315415515615715815916016110010116216316410316516616710616816917017117217317417517617717817911 unmodified lines# π€ LLaMA MODEL# -----------------------------client = InferenceClient( model="meta-llama/llama-3.1-8b-instant", model="meta-llama/Meta-Llama-3.1-8B-Instruct", token=os.getenv("HF_TOKEN"))
# -----------------------------# π₯ NGO DATASET# π₯ LIVE 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":"Food Bank","lat":24.45,"lon":54.37,"capacity":300} {"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 Shelter Hub","type":"Refugee Camp","lat":25.18,"lon":55.31,"capacity":600}]
# -----------------------------# π§ SCORING ENGINE# π HISTORICAL DATASET (AI MEMORY)# -----------------------------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)
# -----------------------------# π§ BASE SCORE# -----------------------------def score(meals, ngo):
dist = math.sqrt((ngo["lat"]-25.2)**2 + (ngo["lon"]-55.27)**2)*100 dist_score = max(0, 100 - dist*10) dist = math.sqrt((ngo["lat"] - 25.20)**2 + (ngo["lon"] - 55.27)**2) * 100 dist_score = max(0, 100 - dist * 10)
cap_score = min(100, ngo["capacity"]/max(meals,1)*100) cap_score = min(100, ngo["capacity"] / max(meals, 1) * 100)
urgency = 100 if ngo["type"] in ["Refugee Camp","Elderly Home"] else 70 urgency = 100 if ngo["type"] in ["Refugee Camp", "Elderly Home"] else 75
return round(dist_score*0.4 + cap_score*0.4 + urgency*0.2, 2) return dist_score * 0.35 + cap_score * 0.45 + urgency * 0.20
# -----------------------------# π€ DYNAMIC LLM REASONING# π§ DATASET BOOST# -----------------------------def history_boost(city, foodType, meals, ngo_name):
boost = 0
for row in HISTORY:
if row["recipient"] == ngo_name: if row["city"] == city: boost += 8
if row["food"].lower() == foodType.lower(): boost += 10
if abs(row["meals"] - meals) <= 40: boost += 7
return boost
# -----------------------------# π€ LLM REASONING# -----------------------------def explain(ngo, meals, foodType, expiry):def explain(ngo, meals, foodType, expiry, city):
styles = [ "focus on urgency and humanitarian impact", "focus on logistics efficiency", "focus on waste reduction", "focus on food freshness", "focus on historical success patterns", "focus on capacity optimization" ]
prompt = f"""You are a humanitarian AI.You are NourishNet AI helping redistribute surplus food.
Donation city: {city}NGO: {ngo['name']}Type: {ngo['type']}Recipient: {ngo['name']}Recipient type: {ngo['type']}Meals: {meals}Food: {foodType}Expiry: {expiry}Food type: {foodType}Expiry: {expiry} hours
Instruction: {random.choice(styles)}
Give a short unique explanation. Do NOT repeat wording.Give ONE short professional reason (max 25 words).Be specific. Do not repeat generic phrases."""
try: return client.text_generation( output = client.text_generation( prompt, max_new_tokens=120, temperature=0.9 max_new_tokens=60, temperature=0.95 ) return output.strip()
except: return f"{ngo['name']} is suitable based on demand and capacity." return f"{ngo['name']} is recommended based on nearby demand and capacity."
# -----------------------------# π‘ API2 unmodified linesdef analyze():
data = request.json
meals = int(data["meals"]) foodType = data["foodType"] expiry = data["expiry"] expiry = int(data["expiry"])
city = detect_city()
results = []
for ngo in NGOS:
s = score(meals, ngo) base = score(meals, ngo)
priority = "High" if s > 80 else "Medium" if s > 60 else "Low" memory = history_boost(city, foodType, meals, ngo["name"])
expiry_bonus = 12 if expiry <= 6 and ngo["type"] in ["Elderly Home", "Refugee Camp"] else 0
final_score = round(base + memory + expiry_bonus, 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"], "type": ngo["type"], "score": s, "km": round(s/10,1), "score": final_score, "km": km, "priority": priority, "reason": explain(ngo, meals, foodType, expiry) "reason": explain(ngo, meals, foodType, expiry, city) })
return jsonify(sorted(results, key=lambda x: x["score"], reverse=True)) results = sorted(results, key=lambda x: x["score"], reverse=True)
return jsonify(results)
# -----------------------------@app.route("/")def home(): return "NourishNet AI Running π"
# -----------------------------if __name__ == "__main__": app.run(host="0.0.0.0", port=7860)app.py+94-29