Ahtisham1583 commited on
Commit
2660746
·
1 Parent(s): d9fcdcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -66
app.py CHANGED
@@ -8,90 +8,47 @@ import matplotlib.image as mpimg
8
  def get_label(file_name):
9
  return file_name.split('-')[0]
10
 
11
- # Function to prepare data (similar to your code)
12
- def prepare_data(food_path, label_a, label_b):
13
- for img in get_image_files(food_path):
14
- if label_a in str(img):
15
- img.rename(f"{img.parent}/{label_a}-{img.name}")
16
- elif label_b in str(img):
17
- img.rename(f"{img.parent}/{label_b}-{img.name}")
18
- else:
19
- os.remove(img)
20
-
21
- # Function to train the model
22
- def train_model(food_path, label_func):
23
- dls = ImageDataLoaders.from_name_func(
24
- food_path, get_image_files(food_path), valid_pct=0.2, seed=420,
25
- label_func=label_func, item_tfms=Resize(230)
26
- )
27
-
28
- learn = cnn_learner(dls, resnet34, metrics=error_rate, pretrained=True)
29
- learn.fine_tune(epochs=1)
30
-
31
- return learn
32
-
33
  # Streamlit app
34
  def main():
35
  st.title("Food Classifier Streamlit App")
36
 
 
 
 
 
37
  # Sidebar options
38
- options = ["Train Model", "Upload Image", "Test Random Images", "Confusion Matrix"]
39
  choice = st.sidebar.selectbox("Choose an option", options)
40
 
41
- if choice == "Train Model":
42
- st.subheader("Training the Model")
43
- food_path = Path("~/.fastai/data/food-101/food-101").expanduser()
44
- if not food_path.exists():
45
- try:
46
- food_path = untar_data(URLs.FOOD)
47
- except FileExistsError:
48
- st.warning("Data directory already exists. Skipping download.")
49
- label_a = st.text_input("Enter label A:", "samosa")
50
- label_b = st.text_input("Enter label B:", "hot_and_sour_soup")
51
-
52
- if st.button("Train Model"):
53
- prepare_data(food_path, label_a, label_b)
54
- learn = train_model(food_path, get_label)
55
- st.session_state.model = learn # Save the model to session state
56
- st.success("Model trained successfully!")
57
-
58
- elif choice == "Upload Image":
59
  st.subheader("Upload Your Own Images")
60
- if "model" not in st.session_state:
61
- st.warning("Please train the model first.")
62
- else:
63
- uploaded_files = st.file_uploader("Choose images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
64
 
65
- if uploaded_files:
66
- for img in uploaded_files:
67
- img = PILImage.create(img)
68
- label, _, probs = st.session_state.model.predict(img)
69
 
70
- st.image(img, caption=f"This is a {label}.")
71
- st.write(f"{label}: {probs[1].item():.6f}")
72
- st.write(f"{label}: {probs[0].item():.6f}")
73
 
74
  elif choice == "Test Random Images":
75
  st.subheader("Test Using Images in Dataset")
76
- if "model" not in st.session_state:
77
- st.warning("Please train the model first.")
78
- else:
79
- for i in range(0, 5): # Change 5 to the number of images you want to display
80
- random_index = random.randint(0, len(get_image_files(food_path)) - 1)
81
- img_path = get_image_files(food_path)[random_index]
82
- img = mpimg.imread(img_path)
83
- label, _, probs = st.session_state.model.predict(img)
84
 
85
- st.image(img, caption=f"Predicted label: {label}")
86
 
87
  elif choice == "Confusion Matrix":
88
  st.subheader("Confusion Matrix")
89
- if "model" not in st.session_state:
90
- st.warning("Please train the model first.")
91
- else:
92
- interp = ClassificationInterpretation.from_learner(st.session_state.model)
93
- st.pyplot(interp.plot_confusion_matrix())
94
 
95
  # Run the Streamlit app
96
  if __name__ == "__main__":
97
  main()
 
 
8
  def get_label(file_name):
9
  return file_name.split('-')[0]
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  # Streamlit app
12
  def main():
13
  st.title("Food Classifier Streamlit App")
14
 
15
+ # Load the pre-trained model
16
+ model_path = "export.pkl" # Update with the correct path to your export.pkl
17
+ model = load_learner(model_path)
18
+
19
  # Sidebar options
20
+ options = ["Upload Image", "Test Random Images", "Confusion Matrix"]
21
  choice = st.sidebar.selectbox("Choose an option", options)
22
 
23
+ if choice == "Upload Image":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  st.subheader("Upload Your Own Images")
25
+ uploaded_files = st.file_uploader("Choose images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
 
 
 
26
 
27
+ if uploaded_files:
28
+ for img in uploaded_files:
29
+ img = PILImage.create(img)
30
+ label, _, probs = model.predict(img)
31
 
32
+ st.image(img, caption=f"This is a {label}.")
33
+ st.write(f"{label}: {probs[1].item():.6f}")
34
+ st.write(f"{label}: {probs[0].item():.6f}")
35
 
36
  elif choice == "Test Random Images":
37
  st.subheader("Test Using Images in Dataset")
38
+ for i in range(0, 5): # Change 5 to the number of images you want to display
39
+ random_index = random.randint(0, len(get_image_files(food_path)) - 1)
40
+ img_path = get_image_files(food_path)[random_index]
41
+ img = mpimg.imread(img_path)
42
+ label, _, probs = model.predict(img)
 
 
 
43
 
44
+ st.image(img, caption=f"Predicted label: {label}")
45
 
46
  elif choice == "Confusion Matrix":
47
  st.subheader("Confusion Matrix")
48
+ interp = ClassificationInterpretation.from_learner(model)
49
+ st.pyplot(interp.plot_confusion_matrix())
 
 
 
50
 
51
  # Run the Streamlit app
52
  if __name__ == "__main__":
53
  main()
54
+