Abbas133 commited on
Commit
bf123e7
·
verified ·
1 Parent(s): ba85c1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -57
app.py CHANGED
@@ -7,113 +7,212 @@ from tensorflow.keras.models import load_model
7
  from io import BytesIO
8
  from PIL import Image
9
  import requests
 
10
 
11
- # Authenticate and download model from Hugging Face
 
 
 
12
  repo_id = "Hammad712/closed_eye_detection"
13
  filename = "Closed_Eye_Detection_98.h5"
14
- model_path = hf_hub_download(repo_id=repo_id, filename=filename)
15
 
16
- # Load the downloaded model
17
- model = load_model(model_path)
 
 
 
 
 
 
 
 
18
 
19
  # Set image dimensions
20
  img_height, img_width = 150, 150
21
 
22
  # Custom CSS
23
  def set_css(style):
 
 
 
24
  st.markdown(f"<style>{style}</style>", unsafe_allow_html=True)
25
 
26
  combined_css = """
 
27
  .main, .sidebar .sidebar-content { background-color: #1c1c1c; color: #f0f2f6; }
28
- .block-container { padding: 1rem 2rem; background-color: #333; border-radius: 10px; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5); }
29
- .stButton>button, .stDownloadButton>button { background: linear-gradient(135deg, #ff7e5f, #feb47b); color: white; border: none; padding: 10px 24px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 5px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  .stSpinner { color: #4CAF50; }
 
31
  .title {
32
  font-size: 3rem;
33
  font-weight: bold;
34
  display: flex;
35
  align-items: center;
36
  justify-content: center;
 
 
37
  }
 
38
  .colorful-text {
39
  background: -webkit-linear-gradient(135deg, #ff7e5f, #feb47b);
40
  -webkit-background-clip: text;
41
  -webkit-text-fill-color: transparent;
42
  }
 
43
  .black-white-text {
44
- color: black;
 
45
  }
 
46
  .small-input .stTextInput>div>input {
47
- height: 2rem;
48
- font-size: 0.9rem;
 
 
 
 
 
49
  }
 
50
  .small-file-uploader .stFileUploader>div>div {
51
- height: 2rem;
52
- font-size: 0.9rem;
53
  }
 
54
  .custom-text {
55
  font-size: 1.2rem;
56
  color: #feb47b;
57
  text-align: center;
58
- margin-top: -20px;
59
- margin-bottom: 20px;
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  }
61
  """
62
 
63
  # Streamlit application
64
- st.set_page_config(layout="wide")
65
-
66
- st.markdown(f"<style>{combined_css}</style>", unsafe_allow_html=True)
67
 
68
- st.markdown('<div class="title"><span class="colorful-text">Eye</span> <span class="black-white-text">Detection Model</span></div>', unsafe_allow_html=True)
69
- st.markdown('<div class="custom-text">Upload an image or provide a URL to predict whether the eyes are open or closed.</div>', unsafe_allow_html=True)
 
70
 
71
  # Input for image URL or path
72
- with st.expander("Input Options", expanded=True):
73
- url = st.text_input("Enter image URL", "")
74
- uploaded_file = st.file_uploader("Or upload an image", type=["jpg", "jpeg", "png"])
75
 
76
  def load_image_from_url(url):
77
- response = requests.get(url)
78
- img = Image.open(BytesIO(response.content)).convert('RGB')
79
- return np.array(img)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  if uploaded_file is not None or url:
 
82
  if uploaded_file is not None:
83
  # Read the uploaded image
84
  file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
85
- image = cv2.imdecode(file_bytes, 1)
 
86
  elif url:
87
  # Read the image from URL
88
- image = load_image_from_url(url)
89
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
90
-
91
- # Resize and preprocess the image
92
- resized_image = cv2.resize(image, (img_height, img_width))
93
- input_image = resized_image.reshape((1, img_height, img_width, 3)) / 255.0
94
-
95
- # Perform inference
96
- predictions = model.predict(input_image)
97
- prediction = predictions[0][0]
98
-
99
- def get_label(prediction):
100
- return "Open Eye" if prediction >= 0.5 else "Closed Eye"
101
-
102
- label = get_label(prediction)
103
-
104
- # Display the image and prediction
105
- st.image(image, channels="BGR", caption='Uploaded Image' if uploaded_file is not None else 'Image from URL')
106
- st.markdown(f"### Prediction: {prediction:.2f}, Label: {label}")
107
-
108
- # Provide a download button for the uploaded image (optional)
109
- img_byte_arr = BytesIO()
110
- img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
111
- img.save(img_byte_arr, format='JPEG')
112
- img_byte_arr = img_byte_arr.getvalue()
113
-
114
- st.download_button(
115
- label="Download Image",
116
- data=img_byte_arr,
117
- file_name="processed_image.jpg",
118
- mime="image/jpeg"
119
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  from io import BytesIO
8
  from PIL import Image
9
  import requests
10
+ # os module ki ab yahan directly zaroorat nahi hai, kyunki cache_dir specify nahi ho raha.
11
 
12
+ # IMPORTANT: Ensure your `requirements.txt` includes tensorflow==2.10.0 or 2.15.0.
13
+ # The `get_config` error often stems from incompatible TensorFlow versions.
14
+
15
+ # Download model from Hugging Face
16
  repo_id = "Hammad712/closed_eye_detection"
17
  filename = "Closed_Eye_Detection_98.h5"
 
18
 
19
+ try:
20
+ # Download the model to a local temporary file
21
+ # Removing cache_dir as Hugging Face handles caching internally
22
+ model_path = hf_hub_download(repo_id=repo_id, filename=filename)
23
+ # Load the downloaded model
24
+ model = load_model(model_path)
25
+ st.success("Model loaded successfully!")
26
+ except Exception as e:
27
+ st.error(f"Error loading model: {e}. Please ensure correct TensorFlow version in requirements.txt.")
28
+ st.stop() # Stop the app if there's an error
29
 
30
  # Set image dimensions
31
  img_height, img_width = 150, 150
32
 
33
  # Custom CSS
34
  def set_css(style):
35
+ """
36
+ Function to apply custom CSS to the webpage.
37
+ """
38
  st.markdown(f"<style>{style}</style>", unsafe_allow_html=True)
39
 
40
  combined_css = """
41
+ /* Main background and text colors */
42
  .main, .sidebar .sidebar-content { background-color: #1c1c1c; color: #f0f2f6; }
43
+ /* Styling for the main content block */
44
+ .block-container { padding: 1rem 2rem; background-color: #333; border-radius: 10px; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5); margin-bottom: 20px; }
45
+ /* Button styling */
46
+ .stButton>button, .stDownloadButton>button {
47
+ background: linear-gradient(135deg, #ff7e5f, #feb47b); /* Colorful gradient */
48
+ color: white;
49
+ border: none;
50
+ padding: 10px 24px;
51
+ text-align: center;
52
+ text-decoration: none;
53
+ display: inline-block;
54
+ font-size: 16px;
55
+ margin: 4px 2px;
56
+ cursor: pointer;
57
+ border-radius: 5px;
58
+ transition: all 0.3s ease; /* Smooth transition */
59
+ }
60
+ .stButton>button:hover, .stDownloadButton>button:hover {
61
+ opacity: 0.9;
62
+ transform: translateY(-2px); /* Lift slightly on hover */
63
+ }
64
+ /* Spinner color */
65
  .stSpinner { color: #4CAF50; }
66
+ /* Title styling */
67
  .title {
68
  font-size: 3rem;
69
  font-weight: bold;
70
  display: flex;
71
  align-items: center;
72
  justify-content: center;
73
+ text-shadow: 2px 2px 5px rgba(0,0,0,0.7); /* Shadow on title */
74
+ margin-bottom: 20px;
75
  }
76
+ /* Colorful text (gradient) */
77
  .colorful-text {
78
  background: -webkit-linear-gradient(135deg, #ff7e5f, #feb47b);
79
  -webkit-background-clip: text;
80
  -webkit-text-fill-color: transparent;
81
  }
82
+ /* Black-white text */
83
  .black-white-text {
84
+ color: white; /* White color will look better */
85
+ margin-left: 10px; /* Give a little spacing */
86
  }
87
+ /* Input field styling */
88
  .small-input .stTextInput>div>input {
89
+ height: 2.5rem;
90
+ font-size: 1rem;
91
+ border-radius: 8px;
92
+ border: 1px solid #ff7e5f; /* Border matching gradient color */
93
+ background-color: #444;
94
+ color: #f0f2f6;
95
+ padding: 0 10px;
96
  }
97
+ /* File uploader styling */
98
  .small-file-uploader .stFileUploader>div>div {
99
+ height: 2.5rem;
100
+ font-size: 1rem;
101
  }
102
+ /* Custom text (subtitle) */
103
  .custom-text {
104
  font-size: 1.2rem;
105
  color: #feb47b;
106
  text-align: center;
107
+ margin-top: -10px; /* Bring closer to title */
108
+ margin-bottom: 30px; /* More space at bottom */
109
+ }
110
+ /* Style for expander title */
111
+ .stExpander {
112
+ border: 1px solid #feb47b;
113
+ border-radius: 10px;
114
+ background-color: #282828;
115
+ }
116
+ .stExpander div[data-baseweb="button"] {
117
+ color: #feb47b !important;
118
+ font-weight: bold;
119
+ }
120
+ .stExpander > div > div > div > div > p {
121
+ color: #f0f2f6 !important;
122
  }
123
  """
124
 
125
  # Streamlit application
126
+ st.set_page_config(layout="centered", page_title="Eye Detection") # Center layout, add a page title
127
+ set_css(combined_css)
 
128
 
129
+ # Title and subtitle
130
+ st.markdown('<div class="title"><span class="colorful-text">آँख</span> <span class="black-white-text">डिटेक्शन मॉडल</span></div>', unsafe_allow_html=True)
131
+ st.markdown('<div class="custom-text">यह पहचानने के लिए एक छवि अपलोड करें या URL प्रदान करें कि आँखें खुली हैं या बंद।</div>', unsafe_allow_html=True)
132
 
133
  # Input for image URL or path
134
+ with st.expander("इनपुट विकल्प", expanded=True):
135
+ url = st.text_input("छवि URL दर्ज करें", "")
136
+ uploaded_file = st.file_uploader("या एक छवि अपलोड करें", type=["jpg", "jpeg", "png"])
137
 
138
  def load_image_from_url(url):
139
+ """
140
+ Function to load an image from a URL.
141
+ """
142
+ if not url:
143
+ return None
144
+ try:
145
+ response = requests.get(url, timeout=10) # Add a 10-second timeout
146
+ response.raise_for_status() # Raise an exception for HTTP errors
147
+ img = Image.open(BytesIO(response.content)).convert('RGB')
148
+ return np.array(img)
149
+ except requests.exceptions.Timeout:
150
+ st.error("Error: Timeout while downloading image from URL.")
151
+ return None
152
+ except requests.exceptions.RequestException as e:
153
+ st.error(f"Error fetching image from URL: {e}")
154
+ return None
155
+ except Exception as e:
156
+ st.error(f"Error processing image from URL: {e}")
157
+ return None
158
 
159
  if uploaded_file is not None or url:
160
+ image = None
161
  if uploaded_file is not None:
162
  # Read the uploaded image
163
  file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
164
+ image = cv2.imdecode(file_bytes, 1) # OpenCV reads in BGR format
165
+ st.session_state['current_image'] = image # Save image to session state
166
  elif url:
167
  # Read the image from URL
168
+ with st.spinner('URL से छवि लोड हो रही है...'):
169
+ image = load_image_from_url(url)
170
+ if image is not None:
171
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # PIL gives RGB, OpenCV wants BGR
172
+ st.session_state['current_image'] = image # Save image to session state
173
+ else:
174
+ st.warning("No valid image loaded from URL.")
175
+ st.session_state['current_image'] = None
176
+
177
+ if st.session_state.get('current_image') is not None:
178
+ image_to_predict = st.session_state['current_image']
179
+ # Resize and preprocess the image
180
+ resized_image = cv2.resize(image_to_predict, (img_height, img_width))
181
+ # Reshape for model input (batch_size, height, width, channels)
182
+ input_image = resized_image.reshape((1, img_height, img_width, 3)) / 255.0
183
+
184
+ # Perform inference
185
+ with st.spinner('अनुमान लगाया जा रहा है...'):
186
+ predictions = model.predict(input_image)
187
+ prediction = predictions[0][0] # Get the single scalar value
188
+
189
+ def get_label(prediction_value):
190
+ """
191
+ Get the label based on the prediction value.
192
+ """
193
+ return "खुली आँख" if prediction_value >= 0.5 else "बंद आँख"
194
+
195
+ label = get_label(prediction)
196
+
197
+ # Display the image and prediction
198
+ st.image(image_to_predict, channels="BGR", caption='अपलोड की गई छवि' if uploaded_file is not None else 'URL से छवि', use_column_width=True)
199
+
200
+ # Predicted result in bold and larger font
201
+ st.markdown(f"### **अनुमान:** `{prediction:.4f}`")
202
+ st.markdown(f"### **लेबल:** <span class='{'colorful-text' if label == 'खुली आँख' else 'black-white-text'}' style='font-size: 2rem;'>{label}</span>", unsafe_allow_html=True)
203
+
204
+ # Download button for the uploaded image (optional)
205
+ img_byte_arr = BytesIO()
206
+ # Convert from OpenCV (BGR) to PIL (RGB) so PIL can save correctly
207
+ img_pil = Image.fromarray(cv2.cvtColor(image_to_predict, cv2.COLOR_BGR2RGB))
208
+ img_pil.save(img_byte_arr, format='JPEG')
209
+ img_byte_arr = img_byte_arr.getvalue()
210
+
211
+ st.download_button(
212
+ label="छवि डाउनलोड करें",
213
+ data=img_byte_arr,
214
+ file_name="processed_eye_image.jpg",
215
+ mime="image/jpeg"
216
+ )
217
+ else:
218
+ st.info("कृपया आगे बढ़ने के लिए एक छवि अपलोड करें या URL प्रदान करें।")