Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234346567891012111214151617181920212223242526272829303132331314151617183619202122232425262739282930313233424334353637384748394050414243444546475253545556575848495061515263646566676869707172535455755657775859798081828384606162638687646566679091929368697071729596979899100737410210310475767710778791098081828384858687888911912012190911239293125126127128949596979899100130131132133134135136137138101102103141142104105106144145146147148107108109110111151152153154112113114115116117118158119120121122from flask import Flask, request, jsonifyfrom flask_cors import CORSimport randomimport mathfrom huggingface_hub import InferenceClientimport osimport requestsimport math
app = Flask(__name__)CORS(app)
# -----------------------------# π SYNTHETIC DATA# π§ LLaMA CLIENT# -----------------------------
CITIES = ["Dubai", "Sharjah", "Abu Dhabi", "Ajman"]CUISINES = ["Arabic", "Indian", "Fast Food", "Asian", "Buffet", "Cafe"]
def generate_restaurants(n=40): data = [] for i in range(n): data.append({ "name": f"Restaurant {i}", "city": random.choice(CITIES), "lat": 25.2 + random.uniform(-0.5, 0.5), "lon": 55.27 + random.uniform(-0.5, 0.5), "cuisine": random.choice(CUISINES), "rating": round(random.uniform(3.0, 5.0), 1), "capacity": random.randint(50, 300), "waste": random.randint(10, 150) }) return data
RESTAURANTS = generate_restaurants()client = InferenceClient( model="meta-llama/llama-3.1-8b-instant", token=os.getenv("HF_TOKEN"))
# -----------------------------# π§ CORE SCORING AI# π₯ 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}]
def score(food_meals, expiry, r):# -----------------------------# π§ SCORING ENGINE# -----------------------------def score_ngo(meals, ngo):
distance = math.sqrt( (r["lat"] - 25.2) ** 2 + (r["lon"] - 55.27) ** 2 (ngo["lat"] - 25.2) ** 2 + (ngo["lon"] - 55.27) ** 2 ) * 100
distance_score = max(0, 100 - distance * 10) capacity_score = min(100, (r["capacity"] / max(food_meals, 1)) * 100) waste_score = r["waste"] capacity_score = min(100, (ngo["capacity"] / max(meals, 1)) * 100)
urgency_score = 100 if expiry <= 6 else 70 if expiry <= 24 else 40 if ngo["type"] == "Refugee Camp": urgency = 100 elif ngo["type"] == "Elderly Home": urgency = 95 else: urgency = 70
return round( distance_score * 0.4 + capacity_score * 0.3 + waste_score * 0.2 + urgency_score * 0.1, 2 ) return round(distance_score * 0.4 + capacity_score * 0.4 + urgency * 0.2, 2)
# -----------------------------# π€ LLM REASONING (OPTIONAL)# π€ LLaMA REASONING# -----------------------------
HF_TOKEN = os.getenv("HF_TOKEN") # store in HF secrets
def llm_reason(context): """ Uses LLM ONLY for explanation (not decision-making) """
if not HF_TOKEN: return context["fallback_reason"]def explain_with_llm(ngo, meals):
prompt = f""" You are an AI assistant for food redistribution.You are an AI humanitarian logistics assistant.
Explain why this match is suitable:Explain why this NGO is a good match for surplus food redistribution.
Restaurant: {context['name']} Cuisine: {context['cuisine']} Meals: {context['meals']} Distance Score: {context['distance']} Capacity Score: {context['capacity']} Waste Score: {context['waste']}NGO: {ngo['name']}Type: {ngo['type']}Meals: {meals}
Give a short 1-2 sentence explanation. """Give a short 2-3 line clear explanation."""
try: response = requests.post( "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct", headers={"Authorization": f"Bearer {HF_TOKEN}"}, json={"inputs": prompt} response = client.text_generation( prompt, max_new_tokens=120, temperature=0.7 )
result = response.json()
if isinstance(result, list) and "generated_text" in result[0]: return result[0]["generated_text"]
return response except: pass
return context["fallback_reason"] return f"{ngo['name']} is suitable based on capacity and urgent community need."
# -----------------------------# π‘ API# π‘ API ENDPOINT# -----------------------------
@app.route("/analyze", methods=["POST"])def analyze():
data = request.json meals = int(data.get("meals", 50)) expiry = int(data.get("expiry", 24)) foodType = data.get("foodType", "")
results = []
for r in RESTAURANTS:
total_score = score(meals, expiry, r) for n in NGOS:
priority = "High" if total_score > 80 else "Medium" if total_score > 55 else "Low" score = score_ngo(meals, n)
fallback_reason = ( f"Good capacity match with {r['capacity']} meals and " f"{r['waste']} estimated waste availability." ) if score > 80: priority = "High" elif score > 55: priority = "Medium" else: priority = "Low"
context = { "name": r["name"], "cuisine": r["cuisine"], "meals": meals, "distance": "balanced", "capacity": r["capacity"], "waste": r["waste"], "fallback_reason": fallback_reason } reasoning = explain_with_llm(n, meals)
results.append({ "recipient": r["name"], "city": r["city"], "recipient": n["name"], "type": n["type"], "priority": priority, "score": total_score, "km": round(random.uniform(1, 15), 1), "capacity": f"{r['capacity']} meals", "type": r["cuisine"], "reason": llm_reason(context) "score": score, "km": round(score / 10, 1), "reason": reasoning })
results.sort(key=lambda x: x["score"], reverse=True)
return jsonify(results[:5])
return jsonify(sorted(results, key=lambda x: x["score"], reverse=True))
# -----------------------------# π HEALTH CHECK# -----------------------------@app.route("/")def home(): return "Hybrid AI System Running π" return "NourishNet AI (LLM + Logic Hybrid) Running π"
if __name__ == "__main__": app.run(host="0.0.0.0", port=7860)app.py+64-103