Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091921 unmodified linefrom groq import Groqimport osimport time# -------------------------# Initialize Groq client# -------------------------api_key = os.environ.get("GROQ_API_KEY")client = Groq(api_key=api_key) if api_key else None# -------------------------# Main recommendation function# -------------------------def get_recommendation(quantity, food_type, expiry_hours):if not client:return "β GROQ_API_KEY not found. Please set your API key in Secrets."# Basic routing logicif quantity < 20:base = "Elderly Individuals"elif quantity < 100:base = "Care Homes"else:base = "NGOs / Refugee Centers"prompt = f"""A restaurant has:- {quantity} meals- Food type: {food_type}- Expiry in {expiry_hours} hoursThe system selected: {base}Explain why this is the best recipient in 2-3 lines."""# Retry logic for temporary connection issuesexplanation = "β AI explanation not available."for attempt in range(3):try:response = client.chat.completions.create(model="llama-3.3-70b-versatile", # smaller model for Spacesmessages=[{"role": "user", "content": prompt}])explanation = response.choices[0].message.contentbreakexcept Exception as e:explanation = f"β AI request failed on attempt {attempt+1}: {e}"time.sleep(2) # wait 2 seconds before retryingreturn f"β Recommended: {base}\n\nπ€ AI Reasoning:\n{explanation}"# -------------------------# Gradio Blocks UI# -------------------------with gr.Blocks(title="π½οΈ NourishNet AI") as demo:gr.Markdown("""# π½οΈ NourishNet AIAI-powered food surplus redistribution systemEnter meal count, type, and expiry hours, and get a recommended recipient with AI reasoning.""")gr.HTML("""<style>body { font-family: 'Poppins', sans-serif; }.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>""")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", lines=7)submit_btn = gr.Button("Get Recommendation")submit_btn.click(fn=get_recommendation,inputs=[quantity_input, food_type_input, expiry_input],outputs=output_text)# -------------------------# Run the app# -------------------------if __name__ == "__main__":demo.launch()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101 unmodified linefrom groq import Groqimport osimport timeimport foliumfrom folium import Markerfrom streamlit_folium import st_folium # optional if you switch to Streamlit for mapsfrom 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.")client = Noneelse: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)"prompt = f"""A restaurant has:- {quantity} meals- Food type: {food_type}- Expiry in {expiry_hours} hoursThe system selected: {recipient_name} ({recipient_type})Explain why this is the best recipient in 2-3 lines."""try:response = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "user", "content": prompt}])return response.choices[0].message.contentexcept 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__":demo.launch()
app.py+69-51