Suchith-nj commited on
Commit
b3a9019
·
1 Parent(s): 5a36ba5
Files changed (2) hide show
  1. .gitignore +1 -0
  2. pages/1_Image_Classifier.py +23 -100
.gitignore CHANGED
@@ -9,3 +9,4 @@ venv/*
9
  *venv/*
10
  =0.19.0
11
  .streamlit/secrets.toml
 
 
9
  *venv/*
10
  =0.19.0
11
  .streamlit/secrets.toml
12
+ week1_image_classifier/myLearnings.md
pages/1_Image_Classifier.py CHANGED
@@ -1,7 +1,6 @@
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",
@@ -10,122 +9,46 @@ st.set_page_config(
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
49
- col1, col2 = st.columns([1, 1])
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:
62
  image = Image.open(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")
 
1
  import streamlit as st
2
  from PIL import Image
3
  import requests
 
4
 
5
  st.set_page_config(
6
  page_title="Food Classifier",
 
9
  )
10
 
11
  st.title("Food Classification")
12
+ st.markdown("AI-powered food recognition")
13
 
14
+ API_URL = "https://api-inference.huggingface.co/models/nateraw/vit-base-beans"
 
15
 
16
+ def classify_image(image_bytes):
 
17
  try:
18
  response = requests.post(API_URL, data=image_bytes, timeout=30)
19
+ return response.json()
20
+ except:
21
+ return None
 
 
 
22
 
23
+ col1, col2 = st.columns(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  with col1:
26
+ st.subheader("Upload Image")
27
+ uploaded_file = st.file_uploader("Choose a food image", type=['jpg', 'jpeg', 'png'])
 
 
 
 
 
 
28
 
29
  if uploaded_file:
30
  image = Image.open(uploaded_file)
31
+ st.image(image, use_column_width=True)
32
 
33
  with col2:
34
+ st.subheader("Results")
35
 
36
  if uploaded_file:
37
+ with st.spinner("Analyzing..."):
38
+ results = classify_image(uploaded_file.getvalue())
 
 
 
 
39
 
40
+ if results and isinstance(results, list):
41
+ for i, result in enumerate(results[:5], 1):
42
+ label = result.get('label', 'Unknown')
43
+ score = result.get('score', 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ st.write(f"**{i}. {label}**")
46
+ st.progress(score)
47
+ st.caption(f"{score*100:.1f}%")
 
 
 
48
  else:
49
+ st.info("Model loading. Wait 20 seconds and retry.")
50
  else:
51
+ st.info("Upload an image to classify")
52
 
53
  st.markdown("---")
54
+ st.caption("Week 1 Project - Image Classification Pipeline")