Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211222 unmodified linesfrom huggingface_hub import InferenceClientimport osimport mathapp = Flask(__name__)CORS(app)# -----------------------------# π§ LLaMA CLIENT# -----------------------------client = InferenceClient(model="meta-llama/llama-3.1-8b-instant",token=os.getenv("HF_TOKEN"))# -----------------------------# π₯ NGO DATA# -----------------------------NGOS = [{"name": "Dubai Elderly Care Home", "type": "Elderly Home", "lat": 25.2048, "lon": 55.2708, "capacity": 120},{"name": "Sharjah Food Bank", "type": "Food Bank", "lat": 25.3463, "lon": 55.4209, "capacity": 300},{"name": "UAE Refugee Support Center", "type": "Refugee Camp", "lat": 25.2769, "lon": 55.2962, "capacity": 500},{"name": "Abu Dhabi Community Kitchen", "type": "Food Bank", "lat": 24.4539, "lon": 54.3773, "capacity": 200}]# -----------------------------# π§ SCORING ENGINE# -----------------------------def score_ngo(meals, ngo):distance = math.sqrt((ngo["lat"] - 25.2) ** 2 +(ngo["lon"] - 55.27) ** 2) * 100distance_score = max(0, 100 - distance * 10)capacity_score = min(100, (ngo["capacity"] / max(meals, 1)) * 100)if ngo["type"] == "Refugee Camp":urgency = 100elif ngo["type"] == "Elderly Home":urgency = 95else:urgency = 70return round(distance_score * 0.4 + capacity_score * 0.4 + urgency * 0.2, 2)# -----------------------------# π€ LLaMA REASONING# -----------------------------def explain_with_llm(ngo, meals):prompt = f"""You are an AI humanitarian logistics assistant.Explain why this NGO is a good match for surplus food redistribution.NGO: {ngo['name']}Type: {ngo['type']}Meals: {meals}Give a short 2-3 line clear explanation."""try:response = client.text_generation(prompt,max_new_tokens=120,temperature=0.7)return responseexcept:return f"{ngo['name']} is suitable based on capacity and urgent community need."# -----------------------------# π‘ API ENDPOINT# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():data = request.jsonmeals = int(data.get("meals", 50))expiry = int(data.get("expiry", 24))foodType = data.get("foodType", "")results = []for n in NGOS:score = score_ngo(meals, n)if score > 80:priority = "High"elif score > 55:priority = "Medium"else:priority = "Low"reasoning = explain_with_llm(n, meals)results.append({"recipient": n["name"],"type": n["type"],"priority": priority,"score": score,"km": round(score / 10, 1),"reason": reasoning})return jsonify(sorted(results, key=lambda x: x["score"], reverse=True))# -----------------------------# π HEALTH CHECK# -----------------------------@app.route("/")def home():return "NourishNet AI (LLM + Logic Hybrid) Running π"if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131142 unmodified linesfrom huggingface_hub import InferenceClientimport osimport mathimport randomapp = Flask(__name__)CORS(app)# -----------------------------# π€ LLaMA MODEL# -----------------------------client = InferenceClient(model="meta-llama/Llama-3.1-8B-Instruct",token=os.getenv("HF_TOKEN"))# -----------------------------# π₯ 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":"Food Bank","lat":24.45,"lon":54.37,"capacity":300}]# -----------------------------# π§ SCORING ENGINE# -----------------------------def score(meals, ngo):dist = math.sqrt((ngo["lat"]-25.2)**2 + (ngo["lon"]-55.27)**2)*100dist_score = max(0, 100 - dist*10)cap_score = min(100, ngo["capacity"]/max(meals,1)*100)urgency = 100 if ngo["type"] in ["Refugee Camp","Elderly Home"] else 70return round(dist_score*0.4 + cap_score*0.4 + urgency*0.2, 2)# -----------------------------# π€ DYNAMIC LLM REASONING# -----------------------------def explain(ngo, meals, foodType, expiry):styles = ["focus on urgency and humanitarian impact","focus on logistics efficiency","focus on waste reduction","focus on capacity optimization"]prompt = f"""You are a humanitarian AI.NGO: {ngo['name']}Type: {ngo['type']}Meals: {meals}Food: {foodType}Expiry: {expiry}Instruction: {random.choice(styles)}Give a short unique explanation. Do NOT repeat wording."""try:return client.text_generation(prompt,max_new_tokens=120,temperature=0.9)except:return f"{ngo['name']} is suitable based on demand and capacity."# -----------------------------# π‘ API# -----------------------------@app.route("/analyze", methods=["POST"])def analyze():data = request.jsonmeals = int(data["meals"])foodType = data["foodType"]expiry = data["expiry"]results = []for ngo in NGOS:s = score(meals, ngo)priority = "High" if s > 80 else "Medium" if s > 60 else "Low"results.append({"recipient": ngo["name"],"type": ngo["type"],"score": s,"km": round(s/10,1),"priority": priority,"reason": explain(ngo, meals, foodType, expiry)})return jsonify(sorted(results, key=lambda x: x["score"], reverse=True))# -----------------------------@app.route("/")def home():return "NourishNet AI Running π"if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)
app.py+45-53