File size: 1,804 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
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
import pickle
import os

# 1. Dataset of common foods and their typical shelf life (in days)
#    This acts as our "Knowledge Base"
data = [
    # Dairy
    ("Milk", 7), ("Yogurt", 14), ("Cheese", 30), ("Butter", 60), ("Cream", 10),
    # Vegetables
    ("Spinach", 5), ("Lettuce", 5), ("Tomato", 7), ("Carrot", 21), ("Potato", 30), ("Onion", 30),
    # Fruits
    ("Apple", 21), ("Banana", 5), ("Orange", 14), ("Grapes", 7), ("Strawberry", 4),
    # Meat
    ("Chicken", 2), ("Beef", 3), ("Pork", 3), ("Fish", 2), ("Ham", 5),
    # Grains
    ("Bread", 5), ("Rice", 365), ("Pasta", 365), ("Cereal", 180),
    # Misc
    ("Eggs", 21), ("Juice", 10), ("Sauce", 90), ("Canned Beans", 700)
]

MODEL_PATH = "expiry_model.pkl"

def train_model():
    print("Training Expiry Prediction Model...")
    df = pd.DataFrame(data, columns=["item", "days"])
    
    # Simple NLP pipeline: Text -> Vector -> Classifier
    model = make_pipeline(TfidfVectorizer(), MultinomialNB())
    model.fit(df["item"], df["days"])
    
    with open(MODEL_PATH, "wb") as f:
        pickle.dump(model, f)
    print("Model saved to", MODEL_PATH)
    return model

def load_model():
    if os.path.exists(MODEL_PATH):
        with open(MODEL_PATH, "rb") as f:
            return pickle.load(f)
    else:
        return train_model()

def predict_days(item_name):
    model = load_model()
    try:
        # Predict
        predicted_days = model.predict([item_name])[0]
        return int(predicted_days)
    except Exception as e:
        print(f"Prediction Error: {e}")
        return 7 # Default fallback