Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import gradio as grfrom groq import Groqimport osimport folium# --- Groq ---api_key = os.environ.get("GROQ_API_KEY")client = Groq(api_key=api_key) if api_key else None# --- Data ---recipients = [{"name": "Al Noor Elderly Home", "lat": 25.2048, "lon": 55.2708, "type": "Elderly Individuals", "contact": "+971501234567"},{"name": "Refugee Center Dubai", "lat": 25.0657, "lon": 55.1713, "type": "NGOs / Refugee Centers", "contact": "+971509876543"},{"name": "Care Home Sharjah", "lat": 25.3574, "lon": 55.4031, "type": "Care Homes", "contact": "+971506543210"},]# --- Logic ---def select_recipient(quantity):if quantity < 20:t = "Elderly Individuals"elif quantity < 100:t = "Care Homes"else:t = "NGOs / Refugee Centers"return next(r for r in recipients if r["type"] == t)def get_ai_reasoning(quantity, food_type, expiry, name, rtype):if not client:return "AI unavailable"prompt = f"""{quantity} meals, {food_type}, expires in {expiry} hours.Chosen: {name} ({rtype})Explain briefly."""try:res = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "user", "content": prompt}])return res.choices[0].message.contentexcept:return "AI failed"def generate_map(recipient):m = folium.Map(location=[recipient["lat"], recipient["lon"]], zoom_start=12)folium.Marker([recipient["lat"], recipient["lon"]],popup=f"{recipient['name']}<br>{recipient['contact']}").add_to(m)return m._repr_html_() # THIS FIXES YOUR MAP π₯def delivery_bar():return """<div style="display:flex; align-items:center; justify-content:center; gap:10px; font-size:18px;"><div>π¦</div><div style="flex:1; height:4px; background:#FF7A00;"></div><div>π</div><div style="flex:1; height:4px; background:#FF7A00;"></div><div>β </div></div><div style="display:flex; justify-content:space-between; font-size:12px; margin-top:5px;"><span>Picked</span><span>En Route</span><span>Delivered</span></div>"""def run_app(q, f, e):r = select_recipient(q)ai = get_ai_reasoning(q, f, e, r["name"], r["type"])map_html = generate_map(r)badge = "π Zero Waste Champion" if q > 50 else "β Community Helper"return (f"{r['name']} ({r['type']})",ai,map_html,delivery_bar(),badge)# --- UI ---with gr.Blocks(title="NourishNet AI") as demo:gr.HTML("""<style>body { font-family: 'Poppins'; background:#fdf6f0; }.card {padding:15px;border-radius:12px;background:white;box-shadow:0px 4px 10px rgba(0,0,0,0.1);margin-bottom:15px;}.gr-button {background:linear-gradient(90deg,#FF7A00,#FFB347);color:white;border-radius:10px;font-weight:bold;}</style>""")gr.Markdown("# π½οΈ NourishNet AI")with gr.Row():q = gr.Number(label="Meals", value=10)f = gr.Dropdown(["halal","soft","packaged"], label="Food Type")e = gr.Number(label="Expiry (hrs)", value=5)btn = gr.Button("π Find Recipient")with gr.Column():rec = gr.Textbox(label="Recommended Recipient")reason = gr.Textbox(label="AI Reasoning")map_box = gr.HTML(label="π Map") # FIXED MAPtrack = gr.HTML(label="π Delivery Tracking") # VISUAL BARbadge = gr.Textbox(label="ποΈ Badge")btn.click(fn=run_app,inputs=[q,f,e],outputs=[rec,reason,map_box,track,badge])demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150import gradio as grimport randomimport time# Store postsposts = []# ---------- AI LOGIC ----------def get_ai_recommendation(meals, expiry):if meals > 500:return "NGOs / Refugee Centers", "Large quantity requires mass distribution."elif expiry < 6:return "Nearby Shelters", "Short expiry needs quick distribution."else:return "Community Centers", "Balanced option for moderate supply."# ---------- PROGRESS BAR ----------def generate_tracking():total_time = random.randint(10, 30)elapsed = random.randint(1, total_time)progress = int((elapsed / total_time) * 100)remaining = total_time - elapsedfilled = int(progress / 5)bar = "β" * filled + "β" * (20 - filled)if progress < 30:status = "π‘ Preparing"elif progress < 90:status = "π΅ En Route"else:status = "π’ Delivered"return f"""<div class="tracker"><p><b>{status}</b></p><p>[{bar}] {progress}%</p><p>β±οΈ {remaining} mins remaining</p></div>"""# ---------- ADD POST ----------def add_post(meals, food_type, expiry):rec, reason = get_ai_recommendation(meals, expiry)post = {"meals": meals,"type": food_type,"expiry": expiry,"rec": rec,"reason": reason,"tracking": generate_tracking()}posts.append(post)return display_posts()# ---------- DISPLAY POSTS ----------def display_posts():if not posts:return "<h3>No posts yet</h3>"html = ""for p in posts[::-1]:html += f"""<div class="card"><h2>π± {p['meals']} meals</h2><p><b>Type:</b> {p['type']}</p><p><b>Expiry:</b> {p['expiry']} hrs</p><p class="ai">π€ <b>Recommended:</b> {p['rec']}</p><p class="reason">{p['reason']}</p>{p['tracking']}<button>β Accept Pickup</button></div>"""return html# ---------- UI ----------with gr.Blocks() as demo:gr.HTML("""<style>body {background: linear-gradient(to right, #fff7ed, #ffedd5);font-family: Arial;}h1 {text-align: center;color: #ea580c;}.card {background: white;padding: 20px;margin: 15px;border-radius: 15px;box-shadow: 0 6px 15px rgba(0,0,0,0.1);}.ai {color: #16a34a;font-weight: bold;}.reason {font-size: 14px;color: #555;}button {background: #16a34a;color: white;padding: 10px;border-radius: 10px;border: none;margin-top: 10px;cursor: pointer;}.tracker {background: #f1f5f9;padding: 10px;border-radius: 10px;margin-top: 10px;text-align: center;}</style>""")gr.Markdown("# π½οΈ NourishNet AI")gr.Markdown("### Smart Food Redistribution Platform")with gr.Row():meals = gr.Number(label="Number of Meals")food_type = gr.Textbox(label="Food Type")expiry = gr.Number(label="Hours Until Expiry")submit = gr.Button("π Post Food")output = gr.HTML()submit.click(add_post, inputs=[meals, food_type, expiry], outputs=output)demo.launch()
app.py+124-106