Suchith-nj commited on
Commit
5a36ba5
Β·
1 Parent(s): c03853d

Working food classifier using public model

Browse files
Files changed (2) hide show
  1. pages/1_Image_Classifier.py +91 -58
  2. requirements.txt +2 -1
pages/1_Image_Classifier.py CHANGED
@@ -1,7 +1,7 @@
1
  import streamlit as st
2
  from PIL import Image
3
- import torch
4
- from transformers import AutoImageProcessor, AutoModelForImageClassification
5
 
6
  st.set_page_config(
7
  page_title="Food Classifier",
@@ -9,32 +9,40 @@ st.set_page_config(
9
  layout="wide"
10
  )
11
 
12
- st.title("Food-101 Image Classifier")
13
- st.markdown("### ResNet-50 trained on 75K food images")
14
 
15
- # Load model (cached)
16
- @st.cache_resource
17
- def load_model():
18
- processor = AutoImageProcessor.from_pretrained("microsoft/resnet-50")
19
- model = AutoModelForImageClassification.from_pretrained("suchithnj12/food101-resnet50")
20
- model.eval()
21
- return processor, model
22
 
23
- try:
24
- with st.spinner("Loading model (first time takes 30 seconds)..."):
25
- processor, model = load_model()
26
- st.success("βœ… Model loaded!")
27
- except Exception as e:
28
- st.error(f"Error loading model: {str(e)}")
29
- st.stop()
 
 
 
30
 
31
- with st.expander("ℹ️ Model Information"):
 
32
  st.markdown("""
33
- **Your Model**: suchithnj12/food101-resnet50
34
- **Base**: ResNet-50
35
- **Training**: 5 epochs on Food-101
36
- **Accuracy**: 40.8%
37
- **Categories**: 101 food types
 
 
 
 
 
 
 
 
 
38
  """)
39
 
40
  # Main interface
@@ -42,10 +50,12 @@ col1, col2 = st.columns([1, 1])
42
 
43
  with col1:
44
  st.markdown("### Upload Image")
 
45
 
46
  uploaded_file = st.file_uploader(
47
- "Choose a food image",
48
- type=['jpg', 'jpeg', 'png']
 
49
  )
50
 
51
  if uploaded_file:
@@ -53,46 +63,69 @@ with col1:
53
  st.image(image, caption="Uploaded Image", use_column_width=True)
54
 
55
  with col2:
56
- st.markdown("### Prediction Results")
57
 
58
  if uploaded_file:
59
- with st.spinner("Analyzing..."):
60
- try:
61
- # Preprocess
62
- inputs = processor(images=image, return_tensors="pt")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Predict
65
- with torch.no_grad():
66
- outputs = model(**inputs)
67
- probs = torch.nn.functional.softmax(outputs.logits, dim=1)
68
- top5_probs, top5_indices = torch.topk(probs, 5)
69
 
70
- # Display results
71
- st.success("βœ… Analysis Complete")
72
-
73
- for i in range(5):
74
- label = model.config.id2label[top5_indices[0][i].item()]
75
- score = top5_probs[0][i].item()
76
-
77
- # Format label
78
- label = label.replace('_', ' ').title()
79
-
80
- st.markdown(f"**{i+1}. {label}**")
81
- st.progress(score)
82
- st.caption(f"{score*100:.1f}%")
83
 
84
- except Exception as e:
85
- st.error(f"Prediction failed: {str(e)}")
 
 
 
 
 
 
86
  else:
87
- st.info("πŸ‘ˆ Upload an image to get started")
88
 
89
  st.markdown("---")
90
- with st.expander("πŸ”§ Technical Details"):
 
 
 
 
91
  st.markdown("""
92
- **Model Loading**: Direct from HuggingFace Hub
93
- **Inference**: On HuggingFace Spaces hardware
94
- **Test Accuracy**: 40.8%
95
- **Categories**: apple pie, sushi, pizza, pasta, and 97 more
96
  """)
97
 
98
- st.markdown("---")
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from PIL import Image
3
+ import requests
4
+ import io
5
 
6
  st.set_page_config(
7
  page_title="Food Classifier",
 
9
  layout="wide"
10
  )
11
 
12
+ st.title("Food Classification")
13
+ st.markdown("### AI-powered food recognition")
14
 
15
+ # Use proven working model
16
+ API_URL = "https://api-inference.huggingface.co/models/Kaludi/food-category-classification-v2.0"
 
 
 
 
 
17
 
18
+ def query_model(image_bytes):
19
+ """Query the food classification model"""
20
+ try:
21
+ response = requests.post(API_URL, data=image_bytes, timeout=30)
22
+ if response.status_code == 200:
23
+ return response.json()
24
+ else:
25
+ return {"error": f"Status {response.status_code}"}
26
+ except Exception as e:
27
+ return {"error": str(e)}
28
 
29
+ # Model info
30
+ with st.expander("ℹ️ About This Service"):
31
  st.markdown("""
32
+ **Technology**: Deep Learning Image Classification
33
+ **Model**: Fine-tuned Vision Transformer
34
+ **Capabilities**: Recognizes various food categories
35
+ **Use Case**: Automated food recognition for nutrition tracking, restaurant apps
36
+
37
+ ---
38
+
39
+ **Week 1 Project**: Built complete ML training pipeline
40
+ - Trained custom ResNet-50 on Food-101 dataset (75K images, 101 classes)
41
+ - Implemented end-to-end training pipeline in Google Colab
42
+ - Deployed model to HuggingFace Hub
43
+ - Learned about model training, evaluation, and deployment
44
+
45
+ *Note: Demo uses production model while custom model completes extended training*
46
  """)
47
 
48
  # Main interface
 
50
 
51
  with col1:
52
  st.markdown("### Upload Image")
53
+ st.markdown("Upload a photo of any food item")
54
 
55
  uploaded_file = st.file_uploader(
56
+ "Choose an image",
57
+ type=['jpg', 'jpeg', 'png'],
58
+ help="Supported formats: JPG, JPEG, PNG"
59
  )
60
 
61
  if uploaded_file:
 
63
  st.image(image, caption="Uploaded Image", use_column_width=True)
64
 
65
  with col2:
66
+ st.markdown("### Classification Results")
67
 
68
  if uploaded_file:
69
+ with st.spinner("Analyzing food..."):
70
+ # Get image bytes
71
+ img_bytes = uploaded_file.getvalue()
72
+
73
+ # Query model
74
+ results = query_model(img_bytes)
75
+
76
+ # Handle errors
77
+ if isinstance(results, dict) and "error" in results:
78
+ st.error("Model is initializing. Please wait 20 seconds and upload again.")
79
+ if st.button("Retry"):
80
+ st.rerun()
81
+
82
+ # Display results
83
+ elif isinstance(results, list) and len(results) > 0:
84
+ # Top prediction
85
+ top = results[0]
86
+ top_label = top['label']
87
+ top_score = top['score']
88
 
89
+ st.success("βœ… Classification Complete")
90
+ st.markdown(f"## {top_label}")
91
+ st.progress(top_score)
92
+ st.metric("Confidence", f"{top_score*100:.1f}%")
 
93
 
94
+ # Show top 5
95
+ if len(results) > 1:
96
+ st.markdown("---")
97
+ st.markdown("#### Other Predictions")
 
 
 
 
 
 
 
 
 
98
 
99
+ for i, result in enumerate(results[1:5], 2):
100
+ label = result['label']
101
+ score = result['score']
102
+ st.markdown(f"**{i}. {label}**")
103
+ st.progress(score)
104
+ st.caption(f"{score*100:.1f}%")
105
+ else:
106
+ st.warning("Unable to classify. Please try another image.")
107
  else:
108
+ st.info("πŸ‘ˆ Upload a food image to get started")
109
 
110
  st.markdown("---")
111
+ st.markdown("### πŸ’‘ Tips for Best Results")
112
+
113
+ tip_col1, tip_col2 = st.columns(2)
114
+
115
+ with tip_col1:
116
  st.markdown("""
117
+ **Image Quality**
118
+ - Use clear, well-lit photos
119
+ - Ensure food is the main subject
120
+ - Avoid heavily filtered images
121
  """)
122
 
123
+ with tip_col2:
124
+ st.markdown("""
125
+ **Performance**
126
+ - First prediction: ~20 seconds (model loading)
127
+ - Subsequent predictions: 1-2 seconds
128
+ - Model auto-sleeps after 15 min idle
129
+ """)
130
+
131
+ st.caption("Week 1 Complete | Built by Suchith Natraj Javali | View code on GitHub")
requirements.txt CHANGED
@@ -4,4 +4,5 @@ pandas==2.0.3
4
  pillow==10.1.0
5
  torch==2.0.1
6
  torchvision==0.15.2
7
- transformers==4.35.0
 
 
4
  pillow==10.1.0
5
  torch==2.0.1
6
  torchvision==0.15.2
7
+ transformers==4.35.0
8
+ requests==2.31.0