Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345678910111213141 unmodified line161718192021222324252627282930313233343536373839404114 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071082 unmodified linesimport osimport timeimport foliumfrom folium import Markerfrom geopy.distance import geodesicfrom io import BytesIOimport base64# Load Groq API key from environmentapi_key = os.environ.get("GROQ_API_KEY")if not api_key:print("β GROQ_API_KEY not found. AI reasoning will be disabled.")1 unmodified lineelse:client = Groq(api_key=api_key)# Sample recipients databaserecipients = [{"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"},]# Function to select recipientdef select_recipient(quantity, food_type):if quantity < 20:type_needed = "Elderly Individuals"elif quantity < 100:type_needed = "Care Homes"else:type_needed = "NGOs / Refugee Centers"# pick nearest recipient of that type (simulated)filtered = [r for r in recipients if r["type"] == type_needed]return filtered[0] if filtered else {"name": "No recipient available", "lat": 25.2048, "lon": 55.2708, "contact": "N/A", "type": type_needed}# Function to generate AI reasoningdef get_ai_reasoning(quantity, food_type, expiry_hours, recipient_name, recipient_type):if not client:return "β AI explanation not available (API key missing)"14 unmodified linesexcept Exception as e:return f"β AI request failed: {str(e)}"# Function to generate mapdef generate_map(recipient):m = folium.Map(location=[recipient["lat"], recipient["lon"]], zoom_start=12)Marker([recipient["lat"], recipient["lon"]], popup=f"{recipient['name']} ({recipient['type']})\nContact: {recipient['contact']}").add_to(m)# Convert map to HTML iframedata = BytesIO()m.save(data, close_file=False)return data.getvalue().decode()# Function to simulate delivery progressdef simulate_delivery(quantity, food_type, expiry_hours):recipient = select_recipient(quantity, food_type)ai_reasoning = get_ai_reasoning(quantity, food_type, expiry_hours, recipient["name"], recipient["type"])map_html = generate_map(recipient)# Simulate progress stepssteps = ["π¦ Picked Up", "π En Route", "β Delivered"]progress_output = ""for i, step in enumerate(steps):progress_output += f"{step}\n"time.sleep(0.5) # simulate real-time delay# Simulated gamification badgebadge = "π Zero Waste Champion" if quantity > 50 else "β Community Helper"return f"β Recommended: {recipient['name']} ({recipient['type']})\n\nπ€ AI Reasoning:\n{ai_reasoning}\n\nπ Recipient Map:\n{map_html}\n\nπ Delivery Status:\n{progress_output}\n\nποΈ Badge Earned: {badge}"# Gradio UI with CSSwith gr.Blocks(title="π½οΈ NourishNet AI") as demo:gr.HTML("""<style>body { font-family: 'Poppins', sans-serif; background-color: #fdf6f0; }.gr-button { background: linear-gradient(90deg, #FF7A00, #FFB347); border-radius: 12px; color: white; font-weight: bold; }.gr-textbox { border: 2px solid #FF7A00; border-radius: 10px; padding: 10px; background-color: #FFF8F0; }</style>""")gr.Markdown("# π½οΈ NourishNet AI\nAI-powered food surplus redistribution system")with gr.Row():quantity_input = gr.Number(label="Number of Meals", value=10)food_type_input = gr.Dropdown(["halal", "soft", "packaged"], label="Food Type")expiry_input = gr.Number(label="Hours Until Expiry", value=5)output_text = gr.Textbox(label="Recommendation, AI Reasoning, Map & Delivery Status", lines=20)submit_btn = gr.Button("Get Recommendation")submit_btn.click(fn=simulate_delivery,inputs=[quantity_input, food_type_input, expiry_input],outputs=output_text)if __name__ == "__main__":2 unmodified lines345678910111 unmodified line13141516171819202122232425262728293031323334353614 unmodified lines515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161172 unmodified linesimport osimport timeimport foliumfrom io import BytesIO# --- Groq client ---api_key = os.environ.get("GROQ_API_KEY")if not api_key:print("β GROQ_API_KEY not found. AI reasoning will be disabled.")1 unmodified lineelse:client = Groq(api_key=api_key)# --- Sample recipient 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"},]# --- Functions ---def select_recipient(quantity):if quantity < 20:type_needed = "Elderly Individuals"elif quantity < 100:type_needed = "Care Homes"else:type_needed = "NGOs / Refugee Centers"filtered = [r for r in recipients if r["type"] == type_needed]return filtered[0] if filtered else {"name": "No recipient available", "lat": 25.2048, "lon": 55.2708, "contact": "N/A", "type": type_needed}def get_ai_reasoning(quantity, food_type, expiry_hours, recipient_name, recipient_type):if not client:return "β AI explanation not available (API key missing)"14 unmodified linesexcept Exception as e:return f"β AI request failed: {str(e)}"def generate_map_html(recipient):m = folium.Map(location=[recipient["lat"], recipient["lon"]], zoom_start=12)folium.Marker([recipient["lat"], recipient["lon"]],popup=f"{recipient['name']} ({recipient['type']})<br>Contact: {recipient['contact']}").add_to(m)data = BytesIO()m.save(data, close_file=False)return data.getvalue().decode()def simulate_delivery(quantity, food_type, expiry_hours):recipient = select_recipient(quantity)ai_reasoning = get_ai_reasoning(quantity, food_type, expiry_hours, recipient["name"], recipient["type"])map_html = generate_map_html(recipient)# Simulated delivery progresssteps = ["π¦ Picked Up", "π En Route", "β Delivered"]progress_output = "\n".join(steps)# Badgebadge = "π Zero Waste Champion" if quantity > 50 else "β Community Helper"return {"recipient_name": f"β Recommended: {recipient['name']} ({recipient['type']})","ai_reasoning": ai_reasoning,"map_html": map_html,"delivery_status": progress_output,"badge": badge}# --- Gradio UI ---with gr.Blocks(title="π½οΈ NourishNet AI") as demo:gr.HTML("""<style>body { font-family: 'Poppins', sans-serif; background-color: #fdf6f0; }.gr-button { background: linear-gradient(90deg, #FF7A00, #FFB347); border-radius: 12px; color: white; font-weight: bold; }.gr-textbox { border: 2px solid #FF7A00; border-radius: 10px; padding: 10px; background-color: #FFF8F0; }.container { border: 2px solid #FFB347; border-radius: 12px; padding: 15px; margin-bottom: 20px; background-color: #fffaf0; }</style>""")gr.Markdown("# π½οΈ NourishNet AI\nAI-powered food surplus redistribution system")with gr.Row():quantity_input = gr.Number(label="Number of Meals", value=10)food_type_input = gr.Dropdown(["halal", "soft", "packaged"], label="Food Type")expiry_input = gr.Number(label="Hours Until Expiry", value=5)submit_btn = gr.Button("Get Recommendation")# Output containersrecipient_output = gr.Textbox(label="Recommendation", interactive=False)reasoning_output = gr.Textbox(label="AI Reasoning", interactive=False, lines=4)map_output = gr.HTML(label="Recipient Map")delivery_output = gr.Textbox(label="Delivery Status", interactive=False)badge_output = gr.Textbox(label="Badge Earned", interactive=False)submit_btn.click(fn=simulate_delivery,inputs=[quantity_input, food_type_input, expiry_input],outputs=[recipient_output, reasoning_output, map_output, delivery_output, badge_output])if __name__ == "__main__":
app.py+35-26