File size: 3,610 Bytes
5ae7c8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import sqlite3
import os
from datetime import datetime, timedelta
import model  # Import our AI model

app = Flask(__name__, static_folder='.')
CORS(app)  # Enable CORS for local development if needed

DB_FILE = 'food_waste.db'

# --- Database Setup ---
def init_db():
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute('''

        CREATE TABLE IF NOT EXISTS inventory (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            name TEXT NOT NULL,

            category TEXT,

            quantity TEXT,

            expiry_date DATE,

            added_date DATE DEFAULT CURRENT_DATE

        )

    ''')
    conn.commit()
    conn.close()

# Initialize on start
if not os.path.exists(DB_FILE):
    init_db()

# --- Serve Frontend ---
@app.route('/')
def serve_index():
    return send_from_directory('.', 'index.html')

@app.route('/<path:path>')
def serve_static(path):
    return send_from_directory('.', path)

# --- API Endpoints ---

@app.route('/api/add-item', methods=['POST'])
def add_item():
    data = request.json
    name = data.get('name')
    quantity = data.get('quantity', '1 unit')
    category = data.get('category', 'Uncategorized')
    expiry_date = data.get('expiryDate')
    
    # AI Prediction if no date provided
    if not expiry_date:
        days = model.predict_days(name)
        expiry_date = (datetime.now() + timedelta(days=days)).strftime('%Y-%m-%d')
        print(f"AI Predicted expiry for {name}: {expiry_date} ({days} days)")

    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute('INSERT INTO inventory (name, category, quantity, expiry_date) VALUES (?, ?, ?, ?)',
              (name, category, quantity, expiry_date))
    conn.commit()
    conn.close()
    
    return jsonify({"success": True, "message": "Item added", "expiryDate": expiry_date})

@app.route('/api/get-items', methods=['GET'])
def get_items():
    conn = sqlite3.connect(DB_FILE)
    conn.row_factory = sqlite3.Row # Access by column name
    c = conn.cursor()
    c.execute('SELECT * FROM inventory ORDER BY expiry_date ASC')
    rows = c.fetchall()
    conn.close()
    
    items = []
    for row in rows:
        items.append({
            "id": row['id'],
            "name": row['name'],
            "quantity": row['quantity'],
            "category": row['category'],
            "expiryDate": row['expiry_date']
        })
        
    return jsonify({"items": items})

@app.route('/api/suggest-recipes', methods=['POST'])
def suggest_recipes():
    # Simple Mock Logic for Recipes (Integration with Real Recipe API would go here)
    # For now, we return static logic based on inventory
    return jsonify([
        {
            "title": "Smart AI Salad",
            "image": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?w=500",
            "ingredients": "Based on your Veggies"
        },
        {
             "title": "Leftover Stir Fry",
             "image": "https://images.unsplash.com/photo-1603133872878-684f208fb74b?w=500",
             "ingredients": "Mix of everything expiring soon"
        }
    ])

@app.route('/api/dashboard-stats', methods=['GET'])
def get_stats():
    # Helper to calculate stats backend-side if needed
    pass

if __name__ == '__main__':
    # Train model on start if needed
    model.load_model()
    print("Server running on http://0.0.0.0:7860")
    app.run(host='0.0.0.0', port=7860)